1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "clang/CodeGen/BackendUtil.h"
10 #include "clang/Basic/CodeGenOptions.h"
11 #include "clang/Basic/Diagnostic.h"
12 #include "clang/Basic/LangOptions.h"
13 #include "clang/Basic/TargetOptions.h"
14 #include "clang/Frontend/FrontendDiagnostic.h"
15 #include "clang/Frontend/Utils.h"
16 #include "clang/Lex/HeaderSearchOptions.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Analysis/StackSafetyAnalysis.h"
22 #include "llvm/Analysis/TargetLibraryInfo.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/Bitcode/BitcodeReader.h"
25 #include "llvm/Bitcode/BitcodeWriter.h"
26 #include "llvm/Bitcode/BitcodeWriterPass.h"
27 #include "llvm/CodeGen/RegAllocRegistry.h"
28 #include "llvm/CodeGen/SchedulerRegistry.h"
29 #include "llvm/CodeGen/TargetSubtargetInfo.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/IRPrintingPasses.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/ModuleSummaryIndex.h"
35 #include "llvm/IR/PassManager.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/LTO/LTOBackend.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/SubtargetFeature.h"
40 #include "llvm/Passes/PassBuilder.h"
41 #include "llvm/Passes/PassPlugin.h"
42 #include "llvm/Passes/StandardInstrumentations.h"
43 #include "llvm/Support/BuryPointer.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/PrettyStackTrace.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/TimeProfiler.h"
49 #include "llvm/Support/Timer.h"
50 #include "llvm/Support/ToolOutputFile.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/Target/TargetMachine.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "llvm/Transforms/Coroutines.h"
55 #include "llvm/Transforms/Coroutines/CoroCleanup.h"
56 #include "llvm/Transforms/Coroutines/CoroEarly.h"
57 #include "llvm/Transforms/Coroutines/CoroElide.h"
58 #include "llvm/Transforms/Coroutines/CoroSplit.h"
59 #include "llvm/Transforms/IPO.h"
60 #include "llvm/Transforms/IPO/AlwaysInliner.h"
61 #include "llvm/Transforms/IPO/LowerTypeTests.h"
62 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
63 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
64 #include "llvm/Transforms/InstCombine/InstCombine.h"
65 #include "llvm/Transforms/Instrumentation.h"
66 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
67 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
68 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
69 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
70 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
71 #include "llvm/Transforms/Instrumentation/MemProfiler.h"
72 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
73 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
74 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
75 #include "llvm/Transforms/ObjCARC.h"
76 #include "llvm/Transforms/Scalar.h"
77 #include "llvm/Transforms/Scalar/GVN.h"
78 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
79 #include "llvm/Transforms/Utils.h"
80 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
81 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
82 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
83 #include "llvm/Transforms/Utils/SymbolRewriter.h"
84 #include "llvm/Transforms/Utils/UniqueInternalLinkageNames.h"
85 #include <memory>
86 using namespace clang;
87 using namespace llvm;
88 
89 #define HANDLE_EXTENSION(Ext)                                                  \
90   llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
91 #include "llvm/Support/Extension.def"
92 
93 namespace {
94 
95 // Default filename used for profile generation.
96 static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
97 
98 class EmitAssemblyHelper {
99   DiagnosticsEngine &Diags;
100   const HeaderSearchOptions &HSOpts;
101   const CodeGenOptions &CodeGenOpts;
102   const clang::TargetOptions &TargetOpts;
103   const LangOptions &LangOpts;
104   Module *TheModule;
105 
106   Timer CodeGenerationTime;
107 
108   std::unique_ptr<raw_pwrite_stream> OS;
109 
110   TargetIRAnalysis getTargetIRAnalysis() const {
111     if (TM)
112       return TM->getTargetIRAnalysis();
113 
114     return TargetIRAnalysis();
115   }
116 
117   void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
118 
119   /// Generates the TargetMachine.
120   /// Leaves TM unchanged if it is unable to create the target machine.
121   /// Some of our clang tests specify triples which are not built
122   /// into clang. This is okay because these tests check the generated
123   /// IR, and they require DataLayout which depends on the triple.
124   /// In this case, we allow this method to fail and not report an error.
125   /// When MustCreateTM is used, we print an error if we are unable to load
126   /// the requested target.
127   void CreateTargetMachine(bool MustCreateTM);
128 
129   /// Add passes necessary to emit assembly or LLVM IR.
130   ///
131   /// \return True on success.
132   bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
133                      raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
134 
135   std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
136     std::error_code EC;
137     auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
138                                                      llvm::sys::fs::OF_None);
139     if (EC) {
140       Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
141       F.reset();
142     }
143     return F;
144   }
145 
146 public:
147   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
148                      const HeaderSearchOptions &HeaderSearchOpts,
149                      const CodeGenOptions &CGOpts,
150                      const clang::TargetOptions &TOpts,
151                      const LangOptions &LOpts, Module *M)
152       : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
153         TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
154         CodeGenerationTime("codegen", "Code Generation Time") {}
155 
156   ~EmitAssemblyHelper() {
157     if (CodeGenOpts.DisableFree)
158       BuryPointer(std::move(TM));
159   }
160 
161   std::unique_ptr<TargetMachine> TM;
162 
163   void EmitAssembly(BackendAction Action,
164                     std::unique_ptr<raw_pwrite_stream> OS);
165 
166   void EmitAssemblyWithNewPassManager(BackendAction Action,
167                                       std::unique_ptr<raw_pwrite_stream> OS);
168 };
169 
170 // We need this wrapper to access LangOpts and CGOpts from extension functions
171 // that we add to the PassManagerBuilder.
172 class PassManagerBuilderWrapper : public PassManagerBuilder {
173 public:
174   PassManagerBuilderWrapper(const Triple &TargetTriple,
175                             const CodeGenOptions &CGOpts,
176                             const LangOptions &LangOpts)
177       : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
178         LangOpts(LangOpts) {}
179   const Triple &getTargetTriple() const { return TargetTriple; }
180   const CodeGenOptions &getCGOpts() const { return CGOpts; }
181   const LangOptions &getLangOpts() const { return LangOpts; }
182 
183 private:
184   const Triple &TargetTriple;
185   const CodeGenOptions &CGOpts;
186   const LangOptions &LangOpts;
187 };
188 }
189 
190 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
191   if (Builder.OptLevel > 0)
192     PM.add(createObjCARCAPElimPass());
193 }
194 
195 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
196   if (Builder.OptLevel > 0)
197     PM.add(createObjCARCExpandPass());
198 }
199 
200 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
201   if (Builder.OptLevel > 0)
202     PM.add(createObjCARCOptPass());
203 }
204 
205 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
206                                      legacy::PassManagerBase &PM) {
207   PM.add(createAddDiscriminatorsPass());
208 }
209 
210 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
211                                   legacy::PassManagerBase &PM) {
212   PM.add(createBoundsCheckingLegacyPass());
213 }
214 
215 static SanitizerCoverageOptions
216 getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
217   SanitizerCoverageOptions Opts;
218   Opts.CoverageType =
219       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
220   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
221   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
222   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
223   Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
224   Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
225   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
226   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
227   Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
228   Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
229   Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
230   Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
231   Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
232   Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
233   return Opts;
234 }
235 
236 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
237                                      legacy::PassManagerBase &PM) {
238   const PassManagerBuilderWrapper &BuilderWrapper =
239       static_cast<const PassManagerBuilderWrapper &>(Builder);
240   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
241   auto Opts = getSancovOptsFromCGOpts(CGOpts);
242   PM.add(createModuleSanitizerCoverageLegacyPassPass(
243       Opts, CGOpts.SanitizeCoverageAllowlistFiles,
244       CGOpts.SanitizeCoverageBlocklistFiles));
245 }
246 
247 // Check if ASan should use GC-friendly instrumentation for globals.
248 // First of all, there is no point if -fdata-sections is off (expect for MachO,
249 // where this is not a factor). Also, on ELF this feature requires an assembler
250 // extension that only works with -integrated-as at the moment.
251 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
252   if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
253     return false;
254   switch (T.getObjectFormat()) {
255   case Triple::MachO:
256   case Triple::COFF:
257     return true;
258   case Triple::ELF:
259     return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
260   case Triple::GOFF:
261     llvm::report_fatal_error("ASan not implemented for GOFF");
262   case Triple::XCOFF:
263     llvm::report_fatal_error("ASan not implemented for XCOFF.");
264   case Triple::Wasm:
265   case Triple::UnknownObjectFormat:
266     break;
267   }
268   return false;
269 }
270 
271 static void addMemProfilerPasses(const PassManagerBuilder &Builder,
272                                  legacy::PassManagerBase &PM) {
273   PM.add(createMemProfilerFunctionPass());
274   PM.add(createModuleMemProfilerLegacyPassPass());
275 }
276 
277 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
278                                       legacy::PassManagerBase &PM) {
279   const PassManagerBuilderWrapper &BuilderWrapper =
280       static_cast<const PassManagerBuilderWrapper&>(Builder);
281   const Triple &T = BuilderWrapper.getTargetTriple();
282   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
283   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
284   bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
285   bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator;
286   bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
287   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
288                                             UseAfterScope));
289   PM.add(createModuleAddressSanitizerLegacyPassPass(
290       /*CompileKernel*/ false, Recover, UseGlobalsGC, UseOdrIndicator));
291 }
292 
293 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
294                                             legacy::PassManagerBase &PM) {
295   PM.add(createAddressSanitizerFunctionPass(
296       /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false));
297   PM.add(createModuleAddressSanitizerLegacyPassPass(
298       /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true,
299       /*UseOdrIndicator*/ false));
300 }
301 
302 static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
303                                             legacy::PassManagerBase &PM) {
304   const PassManagerBuilderWrapper &BuilderWrapper =
305       static_cast<const PassManagerBuilderWrapper &>(Builder);
306   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
307   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
308   PM.add(
309       createHWAddressSanitizerLegacyPassPass(/*CompileKernel*/ false, Recover));
310 }
311 
312 static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
313                                             legacy::PassManagerBase &PM) {
314   PM.add(createHWAddressSanitizerLegacyPassPass(
315       /*CompileKernel*/ true, /*Recover*/ true));
316 }
317 
318 static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
319                                              legacy::PassManagerBase &PM,
320                                              bool CompileKernel) {
321   const PassManagerBuilderWrapper &BuilderWrapper =
322       static_cast<const PassManagerBuilderWrapper&>(Builder);
323   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
324   int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
325   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
326   PM.add(createMemorySanitizerLegacyPassPass(
327       MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
328 
329   // MemorySanitizer inserts complex instrumentation that mostly follows
330   // the logic of the original code, but operates on "shadow" values.
331   // It can benefit from re-running some general purpose optimization passes.
332   if (Builder.OptLevel > 0) {
333     PM.add(createEarlyCSEPass());
334     PM.add(createReassociatePass());
335     PM.add(createLICMPass());
336     PM.add(createGVNPass());
337     PM.add(createInstructionCombiningPass());
338     PM.add(createDeadStoreEliminationPass());
339   }
340 }
341 
342 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
343                                    legacy::PassManagerBase &PM) {
344   addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false);
345 }
346 
347 static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder,
348                                          legacy::PassManagerBase &PM) {
349   addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true);
350 }
351 
352 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
353                                    legacy::PassManagerBase &PM) {
354   PM.add(createThreadSanitizerLegacyPassPass());
355 }
356 
357 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
358                                      legacy::PassManagerBase &PM) {
359   const PassManagerBuilderWrapper &BuilderWrapper =
360       static_cast<const PassManagerBuilderWrapper&>(Builder);
361   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
362   PM.add(
363       createDataFlowSanitizerLegacyPassPass(LangOpts.SanitizerBlacklistFiles));
364 }
365 
366 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
367                                          const CodeGenOptions &CodeGenOpts) {
368   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
369 
370   switch (CodeGenOpts.getVecLib()) {
371   case CodeGenOptions::Accelerate:
372     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
373     break;
374   case CodeGenOptions::MASSV:
375     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
376     break;
377   case CodeGenOptions::SVML:
378     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
379     break;
380   default:
381     break;
382   }
383   return TLII;
384 }
385 
386 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
387                                   legacy::PassManager *MPM) {
388   llvm::SymbolRewriter::RewriteDescriptorList DL;
389 
390   llvm::SymbolRewriter::RewriteMapParser MapParser;
391   for (const auto &MapFile : Opts.RewriteMapFiles)
392     MapParser.parse(MapFile, &DL);
393 
394   MPM->add(createRewriteSymbolsPass(DL));
395 }
396 
397 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
398   switch (CodeGenOpts.OptimizationLevel) {
399   default:
400     llvm_unreachable("Invalid optimization level!");
401   case 0:
402     return CodeGenOpt::None;
403   case 1:
404     return CodeGenOpt::Less;
405   case 2:
406     return CodeGenOpt::Default; // O2/Os/Oz
407   case 3:
408     return CodeGenOpt::Aggressive;
409   }
410 }
411 
412 static Optional<llvm::CodeModel::Model>
413 getCodeModel(const CodeGenOptions &CodeGenOpts) {
414   unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
415                            .Case("tiny", llvm::CodeModel::Tiny)
416                            .Case("small", llvm::CodeModel::Small)
417                            .Case("kernel", llvm::CodeModel::Kernel)
418                            .Case("medium", llvm::CodeModel::Medium)
419                            .Case("large", llvm::CodeModel::Large)
420                            .Case("default", ~1u)
421                            .Default(~0u);
422   assert(CodeModel != ~0u && "invalid code model!");
423   if (CodeModel == ~1u)
424     return None;
425   return static_cast<llvm::CodeModel::Model>(CodeModel);
426 }
427 
428 static CodeGenFileType getCodeGenFileType(BackendAction Action) {
429   if (Action == Backend_EmitObj)
430     return CGFT_ObjectFile;
431   else if (Action == Backend_EmitMCNull)
432     return CGFT_Null;
433   else {
434     assert(Action == Backend_EmitAssembly && "Invalid action!");
435     return CGFT_AssemblyFile;
436   }
437 }
438 
439 static void initTargetOptions(DiagnosticsEngine &Diags,
440                               llvm::TargetOptions &Options,
441                               const CodeGenOptions &CodeGenOpts,
442                               const clang::TargetOptions &TargetOpts,
443                               const LangOptions &LangOpts,
444                               const HeaderSearchOptions &HSOpts) {
445   Options.ThreadModel =
446       llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
447           .Case("posix", llvm::ThreadModel::POSIX)
448           .Case("single", llvm::ThreadModel::Single);
449 
450   // Set float ABI type.
451   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
452           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
453          "Invalid Floating Point ABI!");
454   Options.FloatABIType =
455       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
456           .Case("soft", llvm::FloatABI::Soft)
457           .Case("softfp", llvm::FloatABI::Soft)
458           .Case("hard", llvm::FloatABI::Hard)
459           .Default(llvm::FloatABI::Default);
460 
461   // Set FP fusion mode.
462   switch (LangOpts.getDefaultFPContractMode()) {
463   case LangOptions::FPM_Off:
464     // Preserve any contraction performed by the front-end.  (Strict performs
465     // splitting of the muladd intrinsic in the backend.)
466     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
467     break;
468   case LangOptions::FPM_On:
469     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
470     break;
471   case LangOptions::FPM_Fast:
472     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
473     break;
474   }
475 
476   Options.UseInitArray = CodeGenOpts.UseInitArray;
477   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
478   Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
479   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
480 
481   // Set EABI version.
482   Options.EABIVersion = TargetOpts.EABIVersion;
483 
484   if (LangOpts.SjLjExceptions)
485     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
486   if (LangOpts.SEHExceptions)
487     Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
488   if (LangOpts.DWARFExceptions)
489     Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
490   if (LangOpts.WasmExceptions)
491     Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
492 
493   Options.NoInfsFPMath = LangOpts.NoHonorInfs;
494   Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
495   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
496   Options.UnsafeFPMath = LangOpts.UnsafeFPMath;
497   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
498 
499   Options.BBSections =
500       llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections)
501           .Case("all", llvm::BasicBlockSection::All)
502           .Case("labels", llvm::BasicBlockSection::Labels)
503           .StartsWith("list=", llvm::BasicBlockSection::List)
504           .Case("none", llvm::BasicBlockSection::None)
505           .Default(llvm::BasicBlockSection::None);
506 
507   if (Options.BBSections == llvm::BasicBlockSection::List) {
508     ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
509         MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5));
510     if (!MBOrErr)
511       Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file)
512           << MBOrErr.getError().message();
513     else
514       Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
515   }
516 
517   Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
518   Options.FunctionSections = CodeGenOpts.FunctionSections;
519   Options.DataSections = CodeGenOpts.DataSections;
520   Options.IgnoreXCOFFVisibility = CodeGenOpts.IgnoreXCOFFVisibility;
521   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
522   Options.UniqueBasicBlockSectionNames =
523       CodeGenOpts.UniqueBasicBlockSectionNames;
524   Options.TLSSize = CodeGenOpts.TLSSize;
525   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
526   Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
527   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
528   Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
529   Options.EmitAddrsig = CodeGenOpts.Addrsig;
530   Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
531   Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
532   Options.ValueTrackingVariableLocations =
533       CodeGenOpts.ValueTrackingVariableLocations;
534   Options.XRayOmitFunctionIndex = CodeGenOpts.XRayOmitFunctionIndex;
535 
536   Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
537   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
538   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
539   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
540   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
541   Options.MCOptions.MCIncrementalLinkerCompatible =
542       CodeGenOpts.IncrementalLinkerCompatible;
543   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
544   Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
545   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
546   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
547   Options.MCOptions.ABIName = TargetOpts.ABI;
548   for (const auto &Entry : HSOpts.UserEntries)
549     if (!Entry.IsFramework &&
550         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
551          Entry.Group == frontend::IncludeDirGroup::Angled ||
552          Entry.Group == frontend::IncludeDirGroup::System))
553       Options.MCOptions.IASSearchPaths.push_back(
554           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
555   Options.MCOptions.Argv0 = CodeGenOpts.Argv0;
556   Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs;
557 }
558 
559 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts,
560                                             const LangOptions &LangOpts) {
561   if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
562     return None;
563   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
564   // LLVM's -default-gcov-version flag is set to something invalid.
565   GCOVOptions Options;
566   Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
567   Options.EmitData = CodeGenOpts.EmitGcovArcs;
568   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
569   Options.NoRedZone = CodeGenOpts.DisableRedZone;
570   Options.Filter = CodeGenOpts.ProfileFilterFiles;
571   Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
572   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
573   return Options;
574 }
575 
576 static Optional<InstrProfOptions>
577 getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
578                     const LangOptions &LangOpts) {
579   if (!CodeGenOpts.hasProfileClangInstr())
580     return None;
581   InstrProfOptions Options;
582   Options.NoRedZone = CodeGenOpts.DisableRedZone;
583   Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
584   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
585   return Options;
586 }
587 
588 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
589                                       legacy::FunctionPassManager &FPM) {
590   // Handle disabling of all LLVM passes, where we want to preserve the
591   // internal module before any optimization.
592   if (CodeGenOpts.DisableLLVMPasses)
593     return;
594 
595   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
596   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
597   // are inserted before PMBuilder ones - they'd get the default-constructed
598   // TLI with an unknown target otherwise.
599   Triple TargetTriple(TheModule->getTargetTriple());
600   std::unique_ptr<TargetLibraryInfoImpl> TLII(
601       createTLII(TargetTriple, CodeGenOpts));
602 
603   // If we reached here with a non-empty index file name, then the index file
604   // was empty and we are not performing ThinLTO backend compilation (used in
605   // testing in a distributed build environment). Drop any the type test
606   // assume sequences inserted for whole program vtables so that codegen doesn't
607   // complain.
608   if (!CodeGenOpts.ThinLTOIndexFile.empty())
609     MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr,
610                                      /*ImportSummary=*/nullptr,
611                                      /*DropTypeTests=*/true));
612 
613   PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
614 
615   // At O0 and O1 we only run the always inliner which is more efficient. At
616   // higher optimization levels we run the normal inliner.
617   if (CodeGenOpts.OptimizationLevel <= 1) {
618     bool InsertLifetimeIntrinsics = ((CodeGenOpts.OptimizationLevel != 0 &&
619                                       !CodeGenOpts.DisableLifetimeMarkers) ||
620                                      LangOpts.Coroutines);
621     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
622   } else {
623     // We do not want to inline hot callsites for SamplePGO module-summary build
624     // because profile annotation will happen again in ThinLTO backend, and we
625     // want the IR of the hot path to match the profile.
626     PMBuilder.Inliner = createFunctionInliningPass(
627         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
628         (!CodeGenOpts.SampleProfileFile.empty() &&
629          CodeGenOpts.PrepareForThinLTO));
630   }
631 
632   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
633   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
634   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
635   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
636   // Only enable CGProfilePass when using integrated assembler, since
637   // non-integrated assemblers don't recognize .cgprofile section.
638   PMBuilder.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
639 
640   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
641   // Loop interleaving in the loop vectorizer has historically been set to be
642   // enabled when loop unrolling is enabled.
643   PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
644   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
645   PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
646   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
647   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
648 
649   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
650 
651   if (TM)
652     TM->adjustPassManager(PMBuilder);
653 
654   if (CodeGenOpts.DebugInfoForProfiling ||
655       !CodeGenOpts.SampleProfileFile.empty())
656     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
657                            addAddDiscriminatorsPass);
658 
659   // In ObjC ARC mode, add the main ARC optimization passes.
660   if (LangOpts.ObjCAutoRefCount) {
661     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
662                            addObjCARCExpandPass);
663     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
664                            addObjCARCAPElimPass);
665     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
666                            addObjCARCOptPass);
667   }
668 
669   if (LangOpts.Coroutines)
670     addCoroutinePassesToExtensionPoints(PMBuilder);
671 
672   if (CodeGenOpts.MemProf) {
673     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
674                            addMemProfilerPasses);
675     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
676                            addMemProfilerPasses);
677   }
678 
679   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
680     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
681                            addBoundsCheckingPass);
682     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
683                            addBoundsCheckingPass);
684   }
685 
686   if (CodeGenOpts.SanitizeCoverageType ||
687       CodeGenOpts.SanitizeCoverageIndirectCalls ||
688       CodeGenOpts.SanitizeCoverageTraceCmp) {
689     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
690                            addSanitizerCoveragePass);
691     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
692                            addSanitizerCoveragePass);
693   }
694 
695   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
696     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
697                            addAddressSanitizerPasses);
698     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
699                            addAddressSanitizerPasses);
700   }
701 
702   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
703     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
704                            addKernelAddressSanitizerPasses);
705     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
706                            addKernelAddressSanitizerPasses);
707   }
708 
709   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
710     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
711                            addHWAddressSanitizerPasses);
712     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
713                            addHWAddressSanitizerPasses);
714   }
715 
716   if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
717     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
718                            addKernelHWAddressSanitizerPasses);
719     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
720                            addKernelHWAddressSanitizerPasses);
721   }
722 
723   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
724     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
725                            addMemorySanitizerPass);
726     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
727                            addMemorySanitizerPass);
728   }
729 
730   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
731     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
732                            addKernelMemorySanitizerPass);
733     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
734                            addKernelMemorySanitizerPass);
735   }
736 
737   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
738     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
739                            addThreadSanitizerPass);
740     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
741                            addThreadSanitizerPass);
742   }
743 
744   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
745     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
746                            addDataFlowSanitizerPass);
747     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
748                            addDataFlowSanitizerPass);
749   }
750 
751   // Set up the per-function pass manager.
752   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
753   if (CodeGenOpts.VerifyModule)
754     FPM.add(createVerifierPass());
755 
756   // Set up the per-module pass manager.
757   if (!CodeGenOpts.RewriteMapFiles.empty())
758     addSymbolRewriterPass(CodeGenOpts, &MPM);
759 
760   // Add UniqueInternalLinkageNames Pass which renames internal linkage symbols
761   // with unique names.
762   if (CodeGenOpts.UniqueInternalLinkageNames) {
763     MPM.add(createUniqueInternalLinkageNamesPass());
764   }
765 
766   if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts)) {
767     MPM.add(createGCOVProfilerPass(*Options));
768     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
769       MPM.add(createStripSymbolsPass(true));
770   }
771 
772   if (Optional<InstrProfOptions> Options =
773           getInstrProfOptions(CodeGenOpts, LangOpts))
774     MPM.add(createInstrProfilingLegacyPass(*Options, false));
775 
776   bool hasIRInstr = false;
777   if (CodeGenOpts.hasProfileIRInstr()) {
778     PMBuilder.EnablePGOInstrGen = true;
779     hasIRInstr = true;
780   }
781   if (CodeGenOpts.hasProfileCSIRInstr()) {
782     assert(!CodeGenOpts.hasProfileCSIRUse() &&
783            "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
784            "same time");
785     assert(!hasIRInstr &&
786            "Cannot have both ProfileGen pass and CSProfileGen pass at the "
787            "same time");
788     PMBuilder.EnablePGOCSInstrGen = true;
789     hasIRInstr = true;
790   }
791   if (hasIRInstr) {
792     if (!CodeGenOpts.InstrProfileOutput.empty())
793       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
794     else
795       PMBuilder.PGOInstrGen = std::string(DefaultProfileGenName);
796   }
797   if (CodeGenOpts.hasProfileIRUse()) {
798     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
799     PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
800   }
801 
802   if (!CodeGenOpts.SampleProfileFile.empty())
803     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
804 
805   PMBuilder.populateFunctionPassManager(FPM);
806   PMBuilder.populateModulePassManager(MPM);
807 }
808 
809 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
810   SmallVector<const char *, 16> BackendArgs;
811   BackendArgs.push_back("clang"); // Fake program name.
812   if (!CodeGenOpts.DebugPass.empty()) {
813     BackendArgs.push_back("-debug-pass");
814     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
815   }
816   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
817     BackendArgs.push_back("-limit-float-precision");
818     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
819   }
820   BackendArgs.push_back(nullptr);
821   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
822                                     BackendArgs.data());
823 }
824 
825 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
826   // Create the TargetMachine for generating code.
827   std::string Error;
828   std::string Triple = TheModule->getTargetTriple();
829   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
830   if (!TheTarget) {
831     if (MustCreateTM)
832       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
833     return;
834   }
835 
836   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
837   std::string FeaturesStr =
838       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
839   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
840   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
841 
842   llvm::TargetOptions Options;
843   initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
844   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
845                                           Options, RM, CM, OptLevel));
846 }
847 
848 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
849                                        BackendAction Action,
850                                        raw_pwrite_stream &OS,
851                                        raw_pwrite_stream *DwoOS) {
852   // Add LibraryInfo.
853   llvm::Triple TargetTriple(TheModule->getTargetTriple());
854   std::unique_ptr<TargetLibraryInfoImpl> TLII(
855       createTLII(TargetTriple, CodeGenOpts));
856   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
857 
858   // Normal mode, emit a .s or .o file by running the code generator. Note,
859   // this also adds codegenerator level optimization passes.
860   CodeGenFileType CGFT = getCodeGenFileType(Action);
861 
862   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
863   // "codegen" passes so that it isn't run multiple times when there is
864   // inlining happening.
865   if (CodeGenOpts.OptimizationLevel > 0)
866     CodeGenPasses.add(createObjCARCContractPass());
867 
868   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
869                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
870     Diags.Report(diag::err_fe_unable_to_interface_with_target);
871     return false;
872   }
873 
874   return true;
875 }
876 
877 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
878                                       std::unique_ptr<raw_pwrite_stream> OS) {
879   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
880 
881   setCommandLineOpts(CodeGenOpts);
882 
883   bool UsesCodeGen = (Action != Backend_EmitNothing &&
884                       Action != Backend_EmitBC &&
885                       Action != Backend_EmitLL);
886   CreateTargetMachine(UsesCodeGen);
887 
888   if (UsesCodeGen && !TM)
889     return;
890   if (TM)
891     TheModule->setDataLayout(TM->createDataLayout());
892 
893   legacy::PassManager PerModulePasses;
894   PerModulePasses.add(
895       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
896 
897   legacy::FunctionPassManager PerFunctionPasses(TheModule);
898   PerFunctionPasses.add(
899       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
900 
901   CreatePasses(PerModulePasses, PerFunctionPasses);
902 
903   legacy::PassManager CodeGenPasses;
904   CodeGenPasses.add(
905       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
906 
907   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
908 
909   switch (Action) {
910   case Backend_EmitNothing:
911     break;
912 
913   case Backend_EmitBC:
914     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
915       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
916         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
917         if (!ThinLinkOS)
918           return;
919       }
920       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
921                                CodeGenOpts.EnableSplitLTOUnit);
922       PerModulePasses.add(createWriteThinLTOBitcodePass(
923           *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
924     } else {
925       // Emit a module summary by default for Regular LTO except for ld64
926       // targets
927       bool EmitLTOSummary =
928           (CodeGenOpts.PrepareForLTO &&
929            !CodeGenOpts.DisableLLVMPasses &&
930            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
931                llvm::Triple::Apple);
932       if (EmitLTOSummary) {
933         if (!TheModule->getModuleFlag("ThinLTO"))
934           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
935         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
936                                  uint32_t(1));
937       }
938 
939       PerModulePasses.add(createBitcodeWriterPass(
940           *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
941     }
942     break;
943 
944   case Backend_EmitLL:
945     PerModulePasses.add(
946         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
947     break;
948 
949   default:
950     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
951       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
952       if (!DwoOS)
953         return;
954     }
955     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
956                        DwoOS ? &DwoOS->os() : nullptr))
957       return;
958   }
959 
960   // Before executing passes, print the final values of the LLVM options.
961   cl::PrintOptionValues();
962 
963   // Run passes. For now we do all passes at once, but eventually we
964   // would like to have the option of streaming code generation.
965 
966   {
967     PrettyStackTraceString CrashInfo("Per-function optimization");
968     llvm::TimeTraceScope TimeScope("PerFunctionPasses");
969 
970     PerFunctionPasses.doInitialization();
971     for (Function &F : *TheModule)
972       if (!F.isDeclaration())
973         PerFunctionPasses.run(F);
974     PerFunctionPasses.doFinalization();
975   }
976 
977   {
978     PrettyStackTraceString CrashInfo("Per-module optimization passes");
979     llvm::TimeTraceScope TimeScope("PerModulePasses");
980     PerModulePasses.run(*TheModule);
981   }
982 
983   {
984     PrettyStackTraceString CrashInfo("Code generation");
985     llvm::TimeTraceScope TimeScope("CodeGenPasses");
986     CodeGenPasses.run(*TheModule);
987   }
988 
989   if (ThinLinkOS)
990     ThinLinkOS->keep();
991   if (DwoOS)
992     DwoOS->keep();
993 }
994 
995 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
996   switch (Opts.OptimizationLevel) {
997   default:
998     llvm_unreachable("Invalid optimization level!");
999 
1000   case 1:
1001     return PassBuilder::OptimizationLevel::O1;
1002 
1003   case 2:
1004     switch (Opts.OptimizeSize) {
1005     default:
1006       llvm_unreachable("Invalid optimization level for size!");
1007 
1008     case 0:
1009       return PassBuilder::OptimizationLevel::O2;
1010 
1011     case 1:
1012       return PassBuilder::OptimizationLevel::Os;
1013 
1014     case 2:
1015       return PassBuilder::OptimizationLevel::Oz;
1016     }
1017 
1018   case 3:
1019     return PassBuilder::OptimizationLevel::O3;
1020   }
1021 }
1022 
1023 static void addCoroutinePassesAtO0(ModulePassManager &MPM,
1024                                    const LangOptions &LangOpts,
1025                                    const CodeGenOptions &CodeGenOpts) {
1026   if (!LangOpts.Coroutines)
1027     return;
1028 
1029   MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass()));
1030 
1031   CGSCCPassManager CGPM(CodeGenOpts.DebugPassManager);
1032   CGPM.addPass(CoroSplitPass());
1033   CGPM.addPass(createCGSCCToFunctionPassAdaptor(CoroElidePass()));
1034   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1035 
1036   MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
1037 }
1038 
1039 static void addSanitizersAtO0(ModulePassManager &MPM,
1040                               const Triple &TargetTriple,
1041                               const LangOptions &LangOpts,
1042                               const CodeGenOptions &CodeGenOpts) {
1043   if (CodeGenOpts.SanitizeCoverageType ||
1044       CodeGenOpts.SanitizeCoverageIndirectCalls ||
1045       CodeGenOpts.SanitizeCoverageTraceCmp) {
1046     auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1047     MPM.addPass(ModuleSanitizerCoveragePass(
1048         SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
1049         CodeGenOpts.SanitizeCoverageBlocklistFiles));
1050   }
1051 
1052   auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1053     MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1054     bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1055     MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass(
1056         CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope)));
1057     bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1058     MPM.addPass(
1059         ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope,
1060                                    CodeGenOpts.SanitizeAddressUseOdrIndicator));
1061   };
1062 
1063   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1064     ASanPass(SanitizerKind::Address, /*CompileKernel=*/false);
1065   }
1066 
1067   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
1068     ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true);
1069   }
1070 
1071   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1072     bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1073     MPM.addPass(HWAddressSanitizerPass(
1074         /*CompileKernel=*/false, Recover));
1075   }
1076   if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1077     MPM.addPass(HWAddressSanitizerPass(
1078         /*CompileKernel=*/true, /*Recover=*/true));
1079   }
1080 
1081   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1082     bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory);
1083     int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1084     MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
1085     MPM.addPass(createModuleToFunctionPassAdaptor(
1086         MemorySanitizerPass({TrackOrigins, Recover, false})));
1087   }
1088 
1089   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
1090     MPM.addPass(createModuleToFunctionPassAdaptor(
1091         MemorySanitizerPass({0, false, /*Kernel=*/true})));
1092   }
1093 
1094   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1095     MPM.addPass(ThreadSanitizerPass());
1096     MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1097   }
1098 }
1099 
1100 /// A clean version of `EmitAssembly` that uses the new pass manager.
1101 ///
1102 /// Not all features are currently supported in this system, but where
1103 /// necessary it falls back to the legacy pass manager to at least provide
1104 /// basic functionality.
1105 ///
1106 /// This API is planned to have its functionality finished and then to replace
1107 /// `EmitAssembly` at some point in the future when the default switches.
1108 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
1109     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
1110   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
1111   setCommandLineOpts(CodeGenOpts);
1112 
1113   bool RequiresCodeGen = (Action != Backend_EmitNothing &&
1114                           Action != Backend_EmitBC &&
1115                           Action != Backend_EmitLL);
1116   CreateTargetMachine(RequiresCodeGen);
1117 
1118   if (RequiresCodeGen && !TM)
1119     return;
1120   if (TM)
1121     TheModule->setDataLayout(TM->createDataLayout());
1122 
1123   Optional<PGOOptions> PGOOpt;
1124 
1125   if (CodeGenOpts.hasProfileIRInstr())
1126     // -fprofile-generate.
1127     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
1128                             ? std::string(DefaultProfileGenName)
1129                             : CodeGenOpts.InstrProfileOutput,
1130                         "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
1131                         CodeGenOpts.DebugInfoForProfiling);
1132   else if (CodeGenOpts.hasProfileIRUse()) {
1133     // -fprofile-use.
1134     auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
1135                                                     : PGOOptions::NoCSAction;
1136     PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1137                         CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1138                         CSAction, CodeGenOpts.DebugInfoForProfiling);
1139   } else if (!CodeGenOpts.SampleProfileFile.empty())
1140     // -fprofile-sample-use
1141     PGOOpt =
1142         PGOOptions(CodeGenOpts.SampleProfileFile, "",
1143                    CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse,
1144                    PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling);
1145   else if (CodeGenOpts.DebugInfoForProfiling)
1146     // -fdebug-info-for-profiling
1147     PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1148                         PGOOptions::NoCSAction, true);
1149 
1150   // Check to see if we want to generate a CS profile.
1151   if (CodeGenOpts.hasProfileCSIRInstr()) {
1152     assert(!CodeGenOpts.hasProfileCSIRUse() &&
1153            "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1154            "the same time");
1155     if (PGOOpt.hasValue()) {
1156       assert(PGOOpt->Action != PGOOptions::IRInstr &&
1157              PGOOpt->Action != PGOOptions::SampleUse &&
1158              "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1159              " pass");
1160       PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
1161                                      ? std::string(DefaultProfileGenName)
1162                                      : CodeGenOpts.InstrProfileOutput;
1163       PGOOpt->CSAction = PGOOptions::CSIRInstr;
1164     } else
1165       PGOOpt = PGOOptions("",
1166                           CodeGenOpts.InstrProfileOutput.empty()
1167                               ? std::string(DefaultProfileGenName)
1168                               : CodeGenOpts.InstrProfileOutput,
1169                           "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1170                           CodeGenOpts.DebugInfoForProfiling);
1171   }
1172 
1173   PipelineTuningOptions PTO;
1174   PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
1175   // For historical reasons, loop interleaving is set to mirror setting for loop
1176   // unrolling.
1177   PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1178   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1179   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
1180   // Only enable CGProfilePass when using integrated assembler, since
1181   // non-integrated assemblers don't recognize .cgprofile section.
1182   PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
1183   PTO.Coroutines = LangOpts.Coroutines;
1184 
1185   PassInstrumentationCallbacks PIC;
1186   StandardInstrumentations SI(CodeGenOpts.DebugPassManager);
1187   SI.registerCallbacks(PIC);
1188   PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
1189 
1190   // Attempt to load pass plugins and register their callbacks with PB.
1191   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1192     auto PassPlugin = PassPlugin::Load(PluginFN);
1193     if (PassPlugin) {
1194       PassPlugin->registerPassBuilderCallbacks(PB);
1195     } else {
1196       Diags.Report(diag::err_fe_unable_to_load_plugin)
1197           << PluginFN << toString(PassPlugin.takeError());
1198     }
1199   }
1200 #define HANDLE_EXTENSION(Ext)                                                  \
1201   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1202 #include "llvm/Support/Extension.def"
1203 
1204   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
1205   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
1206   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
1207   ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
1208 
1209   // Register the AA manager first so that our version is the one used.
1210   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1211 
1212   // Register the target library analysis directly and give it a customized
1213   // preset TLI.
1214   Triple TargetTriple(TheModule->getTargetTriple());
1215   std::unique_ptr<TargetLibraryInfoImpl> TLII(
1216       createTLII(TargetTriple, CodeGenOpts));
1217   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1218 
1219   // Register all the basic analyses with the managers.
1220   PB.registerModuleAnalyses(MAM);
1221   PB.registerCGSCCAnalyses(CGAM);
1222   PB.registerFunctionAnalyses(FAM);
1223   PB.registerLoopAnalyses(LAM);
1224   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1225 
1226   if (TM)
1227     TM->registerPassBuilderCallbacks(PB, CodeGenOpts.DebugPassManager);
1228 
1229   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
1230 
1231   if (!CodeGenOpts.DisableLLVMPasses) {
1232     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
1233     bool IsLTO = CodeGenOpts.PrepareForLTO;
1234 
1235     if (CodeGenOpts.OptimizationLevel == 0) {
1236       // If we reached here with a non-empty index file name, then the index
1237       // file was empty and we are not performing ThinLTO backend compilation
1238       // (used in testing in a distributed build environment). Drop any the type
1239       // test assume sequences inserted for whole program vtables so that
1240       // codegen doesn't complain.
1241       if (!CodeGenOpts.ThinLTOIndexFile.empty())
1242         MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1243                                        /*ImportSummary=*/nullptr,
1244                                        /*DropTypeTests=*/true));
1245       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
1246         MPM.addPass(GCOVProfilerPass(*Options));
1247       if (Optional<InstrProfOptions> Options =
1248               getInstrProfOptions(CodeGenOpts, LangOpts))
1249         MPM.addPass(InstrProfiling(*Options, false));
1250 
1251       // Build a minimal pipeline based on the semantics required by Clang,
1252       // which is just that always inlining occurs. Further, disable generating
1253       // lifetime intrinsics to avoid enabling further optimizations during
1254       // code generation.
1255       // However, we need to insert lifetime intrinsics to avoid invalid access
1256       // caused by multithreaded coroutines.
1257       MPM.addPass(
1258           AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/LangOpts.Coroutines));
1259 
1260       // At -O0, we can still do PGO. Add all the requested passes for
1261       // instrumentation PGO, if requested.
1262       if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1263                      PGOOpt->Action == PGOOptions::IRUse))
1264         PB.addPGOInstrPassesForO0(
1265             MPM, CodeGenOpts.DebugPassManager,
1266             /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1267             /* IsCS */ false, PGOOpt->ProfileFile,
1268             PGOOpt->ProfileRemappingFile);
1269 
1270       // At -O0 we directly run necessary sanitizer passes.
1271       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1272         MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1273 
1274       // Lastly, add semantically necessary passes for LTO.
1275       if (IsLTO || IsThinLTO) {
1276         MPM.addPass(CanonicalizeAliasesPass());
1277         MPM.addPass(NameAnonGlobalPass());
1278       }
1279     } else {
1280       // Map our optimization levels into one of the distinct levels used to
1281       // configure the pipeline.
1282       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1283 
1284       // If we reached here with a non-empty index file name, then the index
1285       // file was empty and we are not performing ThinLTO backend compilation
1286       // (used in testing in a distributed build environment). Drop any the type
1287       // test assume sequences inserted for whole program vtables so that
1288       // codegen doesn't complain.
1289       if (!CodeGenOpts.ThinLTOIndexFile.empty())
1290         PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1291           MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1292                                          /*ImportSummary=*/nullptr,
1293                                          /*DropTypeTests=*/true));
1294         });
1295 
1296       PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1297         MPM.addPass(createModuleToFunctionPassAdaptor(
1298             EntryExitInstrumenterPass(/*PostInlining=*/false)));
1299       });
1300 
1301       // Register callbacks to schedule sanitizer passes at the appropriate part of
1302       // the pipeline.
1303       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1304         PB.registerScalarOptimizerLateEPCallback(
1305             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1306               FPM.addPass(BoundsCheckingPass());
1307             });
1308 
1309       if (CodeGenOpts.SanitizeCoverageType ||
1310           CodeGenOpts.SanitizeCoverageIndirectCalls ||
1311           CodeGenOpts.SanitizeCoverageTraceCmp) {
1312         PB.registerOptimizerLastEPCallback(
1313             [this](ModulePassManager &MPM,
1314                    PassBuilder::OptimizationLevel Level) {
1315               auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1316               MPM.addPass(ModuleSanitizerCoveragePass(
1317                   SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
1318                   CodeGenOpts.SanitizeCoverageBlocklistFiles));
1319             });
1320       }
1321 
1322       if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1323         int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1324         bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory);
1325         PB.registerOptimizerLastEPCallback(
1326             [TrackOrigins, Recover](ModulePassManager &MPM,
1327                                     PassBuilder::OptimizationLevel Level) {
1328               MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
1329               MPM.addPass(createModuleToFunctionPassAdaptor(
1330                   MemorySanitizerPass({TrackOrigins, Recover, false})));
1331             });
1332       }
1333       if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1334         PB.registerOptimizerLastEPCallback(
1335             [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1336               MPM.addPass(ThreadSanitizerPass());
1337               MPM.addPass(
1338                   createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1339             });
1340       }
1341       if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1342         bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
1343         bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
1344         bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1345         bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1346         PB.registerOptimizerLastEPCallback(
1347             [Recover, UseAfterScope, ModuleUseAfterScope, UseOdrIndicator](
1348                 ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1349               MPM.addPass(
1350                   RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1351               MPM.addPass(ModuleAddressSanitizerPass(
1352                   /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
1353                   UseOdrIndicator));
1354               MPM.addPass(
1355                   createModuleToFunctionPassAdaptor(AddressSanitizerPass(
1356                       /*CompileKernel=*/false, Recover, UseAfterScope)));
1357             });
1358       }
1359 
1360       if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1361         bool Recover =
1362             CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1363         PB.registerOptimizerLastEPCallback(
1364             [Recover](ModulePassManager &MPM,
1365                       PassBuilder::OptimizationLevel Level) {
1366               MPM.addPass(HWAddressSanitizerPass(
1367                   /*CompileKernel=*/false, Recover));
1368             });
1369       }
1370       if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1371         bool Recover =
1372             CodeGenOpts.SanitizeRecover.has(SanitizerKind::KernelHWAddress);
1373         PB.registerOptimizerLastEPCallback(
1374             [Recover](ModulePassManager &MPM,
1375                       PassBuilder::OptimizationLevel Level) {
1376               MPM.addPass(HWAddressSanitizerPass(
1377                   /*CompileKernel=*/true, Recover));
1378             });
1379       }
1380 
1381       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
1382         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1383           MPM.addPass(GCOVProfilerPass(*Options));
1384         });
1385       if (Optional<InstrProfOptions> Options =
1386               getInstrProfOptions(CodeGenOpts, LangOpts))
1387         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1388           MPM.addPass(InstrProfiling(*Options, false));
1389         });
1390 
1391       if (IsThinLTO) {
1392         MPM = PB.buildThinLTOPreLinkDefaultPipeline(
1393             Level, CodeGenOpts.DebugPassManager);
1394         MPM.addPass(CanonicalizeAliasesPass());
1395         MPM.addPass(NameAnonGlobalPass());
1396       } else if (IsLTO) {
1397         MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
1398                                                 CodeGenOpts.DebugPassManager);
1399         MPM.addPass(CanonicalizeAliasesPass());
1400         MPM.addPass(NameAnonGlobalPass());
1401       } else {
1402         MPM = PB.buildPerModuleDefaultPipeline(Level,
1403                                                CodeGenOpts.DebugPassManager);
1404       }
1405     }
1406 
1407     // Add UniqueInternalLinkageNames Pass which renames internal linkage
1408     // symbols with unique names.
1409     if (CodeGenOpts.UniqueInternalLinkageNames)
1410       MPM.addPass(UniqueInternalLinkageNamesPass());
1411 
1412     if (CodeGenOpts.MemProf) {
1413       MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1414       MPM.addPass(ModuleMemProfilerPass());
1415     }
1416 
1417     if (CodeGenOpts.OptimizationLevel == 0) {
1418       // FIXME: the backends do not handle matrix intrinsics currently. Make
1419       // sure they are also lowered in O0. A lightweight version of the pass
1420       // should run in the backend pipeline on demand.
1421       if (LangOpts.MatrixTypes)
1422         MPM.addPass(
1423             createModuleToFunctionPassAdaptor(LowerMatrixIntrinsicsPass()));
1424 
1425       addCoroutinePassesAtO0(MPM, LangOpts, CodeGenOpts);
1426       addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
1427     }
1428   }
1429 
1430   // FIXME: We still use the legacy pass manager to do code generation. We
1431   // create that pass manager here and use it as needed below.
1432   legacy::PassManager CodeGenPasses;
1433   bool NeedCodeGen = false;
1434   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1435 
1436   // Append any output we need to the pass manager.
1437   switch (Action) {
1438   case Backend_EmitNothing:
1439     break;
1440 
1441   case Backend_EmitBC:
1442     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1443       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1444         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1445         if (!ThinLinkOS)
1446           return;
1447       }
1448       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1449                                CodeGenOpts.EnableSplitLTOUnit);
1450       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1451                                                            : nullptr));
1452     } else {
1453       // Emit a module summary by default for Regular LTO except for ld64
1454       // targets
1455       bool EmitLTOSummary =
1456           (CodeGenOpts.PrepareForLTO &&
1457            !CodeGenOpts.DisableLLVMPasses &&
1458            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1459                llvm::Triple::Apple);
1460       if (EmitLTOSummary) {
1461         if (!TheModule->getModuleFlag("ThinLTO"))
1462           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1463         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1464                                  uint32_t(1));
1465       }
1466       MPM.addPass(
1467           BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1468     }
1469     break;
1470 
1471   case Backend_EmitLL:
1472     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1473     break;
1474 
1475   case Backend_EmitAssembly:
1476   case Backend_EmitMCNull:
1477   case Backend_EmitObj:
1478     NeedCodeGen = true;
1479     CodeGenPasses.add(
1480         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1481     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1482       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1483       if (!DwoOS)
1484         return;
1485     }
1486     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1487                        DwoOS ? &DwoOS->os() : nullptr))
1488       // FIXME: Should we handle this error differently?
1489       return;
1490     break;
1491   }
1492 
1493   // Before executing passes, print the final values of the LLVM options.
1494   cl::PrintOptionValues();
1495 
1496   // Now that we have all of the passes ready, run them.
1497   {
1498     PrettyStackTraceString CrashInfo("Optimizer");
1499     MPM.run(*TheModule, MAM);
1500   }
1501 
1502   // Now if needed, run the legacy PM for codegen.
1503   if (NeedCodeGen) {
1504     PrettyStackTraceString CrashInfo("Code generation");
1505     CodeGenPasses.run(*TheModule);
1506   }
1507 
1508   if (ThinLinkOS)
1509     ThinLinkOS->keep();
1510   if (DwoOS)
1511     DwoOS->keep();
1512 }
1513 
1514 static void runThinLTOBackend(
1515     DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M,
1516     const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts,
1517     const clang::TargetOptions &TOpts, const LangOptions &LOpts,
1518     std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile,
1519     std::string ProfileRemapping, BackendAction Action) {
1520   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1521       ModuleToDefinedGVSummaries;
1522   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1523 
1524   setCommandLineOpts(CGOpts);
1525 
1526   // We can simply import the values mentioned in the combined index, since
1527   // we should only invoke this using the individual indexes written out
1528   // via a WriteIndexesThinBackend.
1529   FunctionImporter::ImportMapTy ImportList;
1530   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1531   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1532   if (!lto::loadReferencedModules(*M, *CombinedIndex, ImportList, ModuleMap,
1533                                   OwnedImports))
1534     return;
1535 
1536   auto AddStream = [&](size_t Task) {
1537     return std::make_unique<lto::NativeObjectStream>(std::move(OS));
1538   };
1539   lto::Config Conf;
1540   if (CGOpts.SaveTempsFilePrefix != "") {
1541     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1542                                     /* UseInputModulePath */ false)) {
1543       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1544         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1545                << '\n';
1546       });
1547     }
1548   }
1549   Conf.CPU = TOpts.CPU;
1550   Conf.CodeModel = getCodeModel(CGOpts);
1551   Conf.MAttrs = TOpts.Features;
1552   Conf.RelocModel = CGOpts.RelocationModel;
1553   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1554   Conf.OptLevel = CGOpts.OptimizationLevel;
1555   initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1556   Conf.SampleProfile = std::move(SampleProfile);
1557   Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1558   // For historical reasons, loop interleaving is set to mirror setting for loop
1559   // unrolling.
1560   Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1561   Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1562   Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1563   // Only enable CGProfilePass when using integrated assembler, since
1564   // non-integrated assemblers don't recognize .cgprofile section.
1565   Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1566 
1567   // Context sensitive profile.
1568   if (CGOpts.hasProfileCSIRInstr()) {
1569     Conf.RunCSIRInstr = true;
1570     Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1571   } else if (CGOpts.hasProfileCSIRUse()) {
1572     Conf.RunCSIRInstr = false;
1573     Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1574   }
1575 
1576   Conf.ProfileRemapping = std::move(ProfileRemapping);
1577   Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1578   Conf.DebugPassManager = CGOpts.DebugPassManager;
1579   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1580   Conf.RemarksFilename = CGOpts.OptRecordFile;
1581   Conf.RemarksPasses = CGOpts.OptRecordPasses;
1582   Conf.RemarksFormat = CGOpts.OptRecordFormat;
1583   Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1584   Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1585   switch (Action) {
1586   case Backend_EmitNothing:
1587     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1588       return false;
1589     };
1590     break;
1591   case Backend_EmitLL:
1592     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1593       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1594       return false;
1595     };
1596     break;
1597   case Backend_EmitBC:
1598     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1599       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1600       return false;
1601     };
1602     break;
1603   default:
1604     Conf.CGFileType = getCodeGenFileType(Action);
1605     break;
1606   }
1607   if (Error E =
1608           thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1609                       ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1610                       ModuleMap, &CGOpts.CmdArgs)) {
1611     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1612       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1613     });
1614   }
1615 }
1616 
1617 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1618                               const HeaderSearchOptions &HeaderOpts,
1619                               const CodeGenOptions &CGOpts,
1620                               const clang::TargetOptions &TOpts,
1621                               const LangOptions &LOpts,
1622                               const llvm::DataLayout &TDesc, Module *M,
1623                               BackendAction Action,
1624                               std::unique_ptr<raw_pwrite_stream> OS) {
1625 
1626   llvm::TimeTraceScope TimeScope("Backend");
1627 
1628   std::unique_ptr<llvm::Module> EmptyModule;
1629   if (!CGOpts.ThinLTOIndexFile.empty()) {
1630     // If we are performing a ThinLTO importing compile, load the function index
1631     // into memory and pass it into runThinLTOBackend, which will run the
1632     // function importer and invoke LTO passes.
1633     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1634         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1635                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1636     if (!IndexOrErr) {
1637       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1638                             "Error loading index file '" +
1639                             CGOpts.ThinLTOIndexFile + "': ");
1640       return;
1641     }
1642     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1643     // A null CombinedIndex means we should skip ThinLTO compilation
1644     // (LLVM will optionally ignore empty index files, returning null instead
1645     // of an error).
1646     if (CombinedIndex) {
1647       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1648         runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1649                           TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1650                           CGOpts.ProfileRemappingFile, Action);
1651         return;
1652       }
1653       // Distributed indexing detected that nothing from the module is needed
1654       // for the final linking. So we can skip the compilation. We sill need to
1655       // output an empty object file to make sure that a linker does not fail
1656       // trying to read it. Also for some features, like CFI, we must skip
1657       // the compilation as CombinedIndex does not contain all required
1658       // information.
1659       EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1660       EmptyModule->setTargetTriple(M->getTargetTriple());
1661       M = EmptyModule.get();
1662     }
1663   }
1664 
1665   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1666 
1667   if (CGOpts.ExperimentalNewPassManager)
1668     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1669   else
1670     AsmHelper.EmitAssembly(Action, std::move(OS));
1671 
1672   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1673   // DataLayout.
1674   if (AsmHelper.TM) {
1675     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1676     if (DLDesc != TDesc.getStringRepresentation()) {
1677       unsigned DiagID = Diags.getCustomDiagID(
1678           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1679                                     "expected target description '%1'");
1680       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1681     }
1682   }
1683 }
1684 
1685 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1686 // __LLVM,__bitcode section.
1687 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1688                          llvm::MemoryBufferRef Buf) {
1689   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1690     return;
1691   llvm::EmbedBitcodeInModule(
1692       *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1693       CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1694       &CGOpts.CmdArgs);
1695 }
1696