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.StackProtectorGuard =
525       llvm::StringSwitch<llvm::StackProtectorGuards>(CodeGenOpts
526           .StackProtectorGuard)
527           .Case("tls", llvm::StackProtectorGuards::TLS)
528           .Case("global", llvm::StackProtectorGuards::Global)
529           .Default(llvm::StackProtectorGuards::None);
530   Options.StackProtectorGuardOffset = CodeGenOpts.StackProtectorGuardOffset;
531   Options.StackProtectorGuardReg = CodeGenOpts.StackProtectorGuardReg;
532   Options.TLSSize = CodeGenOpts.TLSSize;
533   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
534   Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
535   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
536   Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
537   Options.EmitAddrsig = CodeGenOpts.Addrsig;
538   Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
539   Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
540   Options.ValueTrackingVariableLocations =
541       CodeGenOpts.ValueTrackingVariableLocations;
542   Options.XRayOmitFunctionIndex = CodeGenOpts.XRayOmitFunctionIndex;
543 
544   Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
545   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
546   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
547   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
548   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
549   Options.MCOptions.MCIncrementalLinkerCompatible =
550       CodeGenOpts.IncrementalLinkerCompatible;
551   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
552   Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
553   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
554   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
555   Options.MCOptions.ABIName = TargetOpts.ABI;
556   for (const auto &Entry : HSOpts.UserEntries)
557     if (!Entry.IsFramework &&
558         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
559          Entry.Group == frontend::IncludeDirGroup::Angled ||
560          Entry.Group == frontend::IncludeDirGroup::System))
561       Options.MCOptions.IASSearchPaths.push_back(
562           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
563   Options.MCOptions.Argv0 = CodeGenOpts.Argv0;
564   Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs;
565 }
566 
567 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts,
568                                             const LangOptions &LangOpts) {
569   if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
570     return None;
571   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
572   // LLVM's -default-gcov-version flag is set to something invalid.
573   GCOVOptions Options;
574   Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
575   Options.EmitData = CodeGenOpts.EmitGcovArcs;
576   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
577   Options.NoRedZone = CodeGenOpts.DisableRedZone;
578   Options.Filter = CodeGenOpts.ProfileFilterFiles;
579   Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
580   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
581   return Options;
582 }
583 
584 static Optional<InstrProfOptions>
585 getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
586                     const LangOptions &LangOpts) {
587   if (!CodeGenOpts.hasProfileClangInstr())
588     return None;
589   InstrProfOptions Options;
590   Options.NoRedZone = CodeGenOpts.DisableRedZone;
591   Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
592   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
593   return Options;
594 }
595 
596 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
597                                       legacy::FunctionPassManager &FPM) {
598   // Handle disabling of all LLVM passes, where we want to preserve the
599   // internal module before any optimization.
600   if (CodeGenOpts.DisableLLVMPasses)
601     return;
602 
603   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
604   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
605   // are inserted before PMBuilder ones - they'd get the default-constructed
606   // TLI with an unknown target otherwise.
607   Triple TargetTriple(TheModule->getTargetTriple());
608   std::unique_ptr<TargetLibraryInfoImpl> TLII(
609       createTLII(TargetTriple, CodeGenOpts));
610 
611   // If we reached here with a non-empty index file name, then the index file
612   // was empty and we are not performing ThinLTO backend compilation (used in
613   // testing in a distributed build environment). Drop any the type test
614   // assume sequences inserted for whole program vtables so that codegen doesn't
615   // complain.
616   if (!CodeGenOpts.ThinLTOIndexFile.empty())
617     MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr,
618                                      /*ImportSummary=*/nullptr,
619                                      /*DropTypeTests=*/true));
620 
621   PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
622 
623   // At O0 and O1 we only run the always inliner which is more efficient. At
624   // higher optimization levels we run the normal inliner.
625   if (CodeGenOpts.OptimizationLevel <= 1) {
626     bool InsertLifetimeIntrinsics = ((CodeGenOpts.OptimizationLevel != 0 &&
627                                       !CodeGenOpts.DisableLifetimeMarkers) ||
628                                      LangOpts.Coroutines);
629     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
630   } else {
631     // We do not want to inline hot callsites for SamplePGO module-summary build
632     // because profile annotation will happen again in ThinLTO backend, and we
633     // want the IR of the hot path to match the profile.
634     PMBuilder.Inliner = createFunctionInliningPass(
635         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
636         (!CodeGenOpts.SampleProfileFile.empty() &&
637          CodeGenOpts.PrepareForThinLTO));
638   }
639 
640   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
641   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
642   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
643   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
644   // Only enable CGProfilePass when using integrated assembler, since
645   // non-integrated assemblers don't recognize .cgprofile section.
646   PMBuilder.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
647 
648   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
649   // Loop interleaving in the loop vectorizer has historically been set to be
650   // enabled when loop unrolling is enabled.
651   PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
652   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
653   PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
654   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
655   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
656 
657   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
658 
659   if (TM)
660     TM->adjustPassManager(PMBuilder);
661 
662   if (CodeGenOpts.DebugInfoForProfiling ||
663       !CodeGenOpts.SampleProfileFile.empty())
664     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
665                            addAddDiscriminatorsPass);
666 
667   // In ObjC ARC mode, add the main ARC optimization passes.
668   if (LangOpts.ObjCAutoRefCount) {
669     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
670                            addObjCARCExpandPass);
671     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
672                            addObjCARCAPElimPass);
673     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
674                            addObjCARCOptPass);
675   }
676 
677   if (LangOpts.Coroutines)
678     addCoroutinePassesToExtensionPoints(PMBuilder);
679 
680   if (CodeGenOpts.MemProf) {
681     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
682                            addMemProfilerPasses);
683     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
684                            addMemProfilerPasses);
685   }
686 
687   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
688     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
689                            addBoundsCheckingPass);
690     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
691                            addBoundsCheckingPass);
692   }
693 
694   if (CodeGenOpts.SanitizeCoverageType ||
695       CodeGenOpts.SanitizeCoverageIndirectCalls ||
696       CodeGenOpts.SanitizeCoverageTraceCmp) {
697     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
698                            addSanitizerCoveragePass);
699     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
700                            addSanitizerCoveragePass);
701   }
702 
703   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
704     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
705                            addAddressSanitizerPasses);
706     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
707                            addAddressSanitizerPasses);
708   }
709 
710   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
711     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
712                            addKernelAddressSanitizerPasses);
713     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
714                            addKernelAddressSanitizerPasses);
715   }
716 
717   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
718     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
719                            addHWAddressSanitizerPasses);
720     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
721                            addHWAddressSanitizerPasses);
722   }
723 
724   if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
725     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
726                            addKernelHWAddressSanitizerPasses);
727     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
728                            addKernelHWAddressSanitizerPasses);
729   }
730 
731   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
732     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
733                            addMemorySanitizerPass);
734     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
735                            addMemorySanitizerPass);
736   }
737 
738   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
739     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
740                            addKernelMemorySanitizerPass);
741     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
742                            addKernelMemorySanitizerPass);
743   }
744 
745   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
746     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
747                            addThreadSanitizerPass);
748     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
749                            addThreadSanitizerPass);
750   }
751 
752   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
753     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
754                            addDataFlowSanitizerPass);
755     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
756                            addDataFlowSanitizerPass);
757   }
758 
759   // Set up the per-function pass manager.
760   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
761   if (CodeGenOpts.VerifyModule)
762     FPM.add(createVerifierPass());
763 
764   // Set up the per-module pass manager.
765   if (!CodeGenOpts.RewriteMapFiles.empty())
766     addSymbolRewriterPass(CodeGenOpts, &MPM);
767 
768   // Add UniqueInternalLinkageNames Pass which renames internal linkage symbols
769   // with unique names.
770   if (CodeGenOpts.UniqueInternalLinkageNames) {
771     MPM.add(createUniqueInternalLinkageNamesPass());
772   }
773 
774   if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts)) {
775     MPM.add(createGCOVProfilerPass(*Options));
776     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
777       MPM.add(createStripSymbolsPass(true));
778   }
779 
780   if (Optional<InstrProfOptions> Options =
781           getInstrProfOptions(CodeGenOpts, LangOpts))
782     MPM.add(createInstrProfilingLegacyPass(*Options, false));
783 
784   bool hasIRInstr = false;
785   if (CodeGenOpts.hasProfileIRInstr()) {
786     PMBuilder.EnablePGOInstrGen = true;
787     hasIRInstr = true;
788   }
789   if (CodeGenOpts.hasProfileCSIRInstr()) {
790     assert(!CodeGenOpts.hasProfileCSIRUse() &&
791            "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
792            "same time");
793     assert(!hasIRInstr &&
794            "Cannot have both ProfileGen pass and CSProfileGen pass at the "
795            "same time");
796     PMBuilder.EnablePGOCSInstrGen = true;
797     hasIRInstr = true;
798   }
799   if (hasIRInstr) {
800     if (!CodeGenOpts.InstrProfileOutput.empty())
801       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
802     else
803       PMBuilder.PGOInstrGen = std::string(DefaultProfileGenName);
804   }
805   if (CodeGenOpts.hasProfileIRUse()) {
806     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
807     PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
808   }
809 
810   if (!CodeGenOpts.SampleProfileFile.empty())
811     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
812 
813   PMBuilder.populateFunctionPassManager(FPM);
814   PMBuilder.populateModulePassManager(MPM);
815 }
816 
817 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
818   SmallVector<const char *, 16> BackendArgs;
819   BackendArgs.push_back("clang"); // Fake program name.
820   if (!CodeGenOpts.DebugPass.empty()) {
821     BackendArgs.push_back("-debug-pass");
822     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
823   }
824   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
825     BackendArgs.push_back("-limit-float-precision");
826     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
827   }
828   BackendArgs.push_back(nullptr);
829   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
830                                     BackendArgs.data());
831 }
832 
833 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
834   // Create the TargetMachine for generating code.
835   std::string Error;
836   std::string Triple = TheModule->getTargetTriple();
837   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
838   if (!TheTarget) {
839     if (MustCreateTM)
840       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
841     return;
842   }
843 
844   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
845   std::string FeaturesStr =
846       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
847   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
848   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
849 
850   llvm::TargetOptions Options;
851   initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
852   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
853                                           Options, RM, CM, OptLevel));
854 }
855 
856 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
857                                        BackendAction Action,
858                                        raw_pwrite_stream &OS,
859                                        raw_pwrite_stream *DwoOS) {
860   // Add LibraryInfo.
861   llvm::Triple TargetTriple(TheModule->getTargetTriple());
862   std::unique_ptr<TargetLibraryInfoImpl> TLII(
863       createTLII(TargetTriple, CodeGenOpts));
864   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
865 
866   // Normal mode, emit a .s or .o file by running the code generator. Note,
867   // this also adds codegenerator level optimization passes.
868   CodeGenFileType CGFT = getCodeGenFileType(Action);
869 
870   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
871   // "codegen" passes so that it isn't run multiple times when there is
872   // inlining happening.
873   if (CodeGenOpts.OptimizationLevel > 0)
874     CodeGenPasses.add(createObjCARCContractPass());
875 
876   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
877                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
878     Diags.Report(diag::err_fe_unable_to_interface_with_target);
879     return false;
880   }
881 
882   return true;
883 }
884 
885 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
886                                       std::unique_ptr<raw_pwrite_stream> OS) {
887   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
888 
889   setCommandLineOpts(CodeGenOpts);
890 
891   bool UsesCodeGen = (Action != Backend_EmitNothing &&
892                       Action != Backend_EmitBC &&
893                       Action != Backend_EmitLL);
894   CreateTargetMachine(UsesCodeGen);
895 
896   if (UsesCodeGen && !TM)
897     return;
898   if (TM)
899     TheModule->setDataLayout(TM->createDataLayout());
900 
901   legacy::PassManager PerModulePasses;
902   PerModulePasses.add(
903       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
904 
905   legacy::FunctionPassManager PerFunctionPasses(TheModule);
906   PerFunctionPasses.add(
907       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
908 
909   CreatePasses(PerModulePasses, PerFunctionPasses);
910 
911   legacy::PassManager CodeGenPasses;
912   CodeGenPasses.add(
913       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
914 
915   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
916 
917   switch (Action) {
918   case Backend_EmitNothing:
919     break;
920 
921   case Backend_EmitBC:
922     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
923       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
924         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
925         if (!ThinLinkOS)
926           return;
927       }
928       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
929                                CodeGenOpts.EnableSplitLTOUnit);
930       PerModulePasses.add(createWriteThinLTOBitcodePass(
931           *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
932     } else {
933       // Emit a module summary by default for Regular LTO except for ld64
934       // targets
935       bool EmitLTOSummary =
936           (CodeGenOpts.PrepareForLTO &&
937            !CodeGenOpts.DisableLLVMPasses &&
938            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
939                llvm::Triple::Apple);
940       if (EmitLTOSummary) {
941         if (!TheModule->getModuleFlag("ThinLTO"))
942           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
943         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
944                                  uint32_t(1));
945       }
946 
947       PerModulePasses.add(createBitcodeWriterPass(
948           *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
949     }
950     break;
951 
952   case Backend_EmitLL:
953     PerModulePasses.add(
954         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
955     break;
956 
957   default:
958     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
959       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
960       if (!DwoOS)
961         return;
962     }
963     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
964                        DwoOS ? &DwoOS->os() : nullptr))
965       return;
966   }
967 
968   // Before executing passes, print the final values of the LLVM options.
969   cl::PrintOptionValues();
970 
971   // Run passes. For now we do all passes at once, but eventually we
972   // would like to have the option of streaming code generation.
973 
974   {
975     PrettyStackTraceString CrashInfo("Per-function optimization");
976     llvm::TimeTraceScope TimeScope("PerFunctionPasses");
977 
978     PerFunctionPasses.doInitialization();
979     for (Function &F : *TheModule)
980       if (!F.isDeclaration())
981         PerFunctionPasses.run(F);
982     PerFunctionPasses.doFinalization();
983   }
984 
985   {
986     PrettyStackTraceString CrashInfo("Per-module optimization passes");
987     llvm::TimeTraceScope TimeScope("PerModulePasses");
988     PerModulePasses.run(*TheModule);
989   }
990 
991   {
992     PrettyStackTraceString CrashInfo("Code generation");
993     llvm::TimeTraceScope TimeScope("CodeGenPasses");
994     CodeGenPasses.run(*TheModule);
995   }
996 
997   if (ThinLinkOS)
998     ThinLinkOS->keep();
999   if (DwoOS)
1000     DwoOS->keep();
1001 }
1002 
1003 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
1004   switch (Opts.OptimizationLevel) {
1005   default:
1006     llvm_unreachable("Invalid optimization level!");
1007 
1008   case 1:
1009     return PassBuilder::OptimizationLevel::O1;
1010 
1011   case 2:
1012     switch (Opts.OptimizeSize) {
1013     default:
1014       llvm_unreachable("Invalid optimization level for size!");
1015 
1016     case 0:
1017       return PassBuilder::OptimizationLevel::O2;
1018 
1019     case 1:
1020       return PassBuilder::OptimizationLevel::Os;
1021 
1022     case 2:
1023       return PassBuilder::OptimizationLevel::Oz;
1024     }
1025 
1026   case 3:
1027     return PassBuilder::OptimizationLevel::O3;
1028   }
1029 }
1030 
1031 static void addCoroutinePassesAtO0(ModulePassManager &MPM,
1032                                    const LangOptions &LangOpts,
1033                                    const CodeGenOptions &CodeGenOpts) {
1034   if (!LangOpts.Coroutines)
1035     return;
1036 
1037   MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass()));
1038 
1039   CGSCCPassManager CGPM(CodeGenOpts.DebugPassManager);
1040   CGPM.addPass(CoroSplitPass());
1041   CGPM.addPass(createCGSCCToFunctionPassAdaptor(CoroElidePass()));
1042   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1043 
1044   MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
1045 }
1046 
1047 static void addSanitizersAtO0(ModulePassManager &MPM,
1048                               const Triple &TargetTriple,
1049                               const LangOptions &LangOpts,
1050                               const CodeGenOptions &CodeGenOpts) {
1051   if (CodeGenOpts.SanitizeCoverageType ||
1052       CodeGenOpts.SanitizeCoverageIndirectCalls ||
1053       CodeGenOpts.SanitizeCoverageTraceCmp) {
1054     auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1055     MPM.addPass(ModuleSanitizerCoveragePass(
1056         SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
1057         CodeGenOpts.SanitizeCoverageBlocklistFiles));
1058   }
1059 
1060   auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1061     MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1062     bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1063     MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass(
1064         CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope)));
1065     bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1066     MPM.addPass(
1067         ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope,
1068                                    CodeGenOpts.SanitizeAddressUseOdrIndicator));
1069   };
1070 
1071   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1072     ASanPass(SanitizerKind::Address, /*CompileKernel=*/false);
1073   }
1074 
1075   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
1076     ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true);
1077   }
1078 
1079   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1080     bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1081     MPM.addPass(HWAddressSanitizerPass(
1082         /*CompileKernel=*/false, Recover));
1083   }
1084   if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1085     MPM.addPass(HWAddressSanitizerPass(
1086         /*CompileKernel=*/true, /*Recover=*/true));
1087   }
1088 
1089   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1090     bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory);
1091     int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1092     MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
1093     MPM.addPass(createModuleToFunctionPassAdaptor(
1094         MemorySanitizerPass({TrackOrigins, Recover, false})));
1095   }
1096 
1097   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
1098     MPM.addPass(createModuleToFunctionPassAdaptor(
1099         MemorySanitizerPass({0, false, /*Kernel=*/true})));
1100   }
1101 
1102   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1103     MPM.addPass(ThreadSanitizerPass());
1104     MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1105   }
1106 }
1107 
1108 /// A clean version of `EmitAssembly` that uses the new pass manager.
1109 ///
1110 /// Not all features are currently supported in this system, but where
1111 /// necessary it falls back to the legacy pass manager to at least provide
1112 /// basic functionality.
1113 ///
1114 /// This API is planned to have its functionality finished and then to replace
1115 /// `EmitAssembly` at some point in the future when the default switches.
1116 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
1117     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
1118   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
1119   setCommandLineOpts(CodeGenOpts);
1120 
1121   bool RequiresCodeGen = (Action != Backend_EmitNothing &&
1122                           Action != Backend_EmitBC &&
1123                           Action != Backend_EmitLL);
1124   CreateTargetMachine(RequiresCodeGen);
1125 
1126   if (RequiresCodeGen && !TM)
1127     return;
1128   if (TM)
1129     TheModule->setDataLayout(TM->createDataLayout());
1130 
1131   Optional<PGOOptions> PGOOpt;
1132 
1133   if (CodeGenOpts.hasProfileIRInstr())
1134     // -fprofile-generate.
1135     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
1136                             ? std::string(DefaultProfileGenName)
1137                             : CodeGenOpts.InstrProfileOutput,
1138                         "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
1139                         CodeGenOpts.DebugInfoForProfiling);
1140   else if (CodeGenOpts.hasProfileIRUse()) {
1141     // -fprofile-use.
1142     auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
1143                                                     : PGOOptions::NoCSAction;
1144     PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1145                         CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1146                         CSAction, CodeGenOpts.DebugInfoForProfiling);
1147   } else if (!CodeGenOpts.SampleProfileFile.empty())
1148     // -fprofile-sample-use
1149     PGOOpt =
1150         PGOOptions(CodeGenOpts.SampleProfileFile, "",
1151                    CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse,
1152                    PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling);
1153   else if (CodeGenOpts.DebugInfoForProfiling)
1154     // -fdebug-info-for-profiling
1155     PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1156                         PGOOptions::NoCSAction, true);
1157 
1158   // Check to see if we want to generate a CS profile.
1159   if (CodeGenOpts.hasProfileCSIRInstr()) {
1160     assert(!CodeGenOpts.hasProfileCSIRUse() &&
1161            "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1162            "the same time");
1163     if (PGOOpt.hasValue()) {
1164       assert(PGOOpt->Action != PGOOptions::IRInstr &&
1165              PGOOpt->Action != PGOOptions::SampleUse &&
1166              "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1167              " pass");
1168       PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
1169                                      ? std::string(DefaultProfileGenName)
1170                                      : CodeGenOpts.InstrProfileOutput;
1171       PGOOpt->CSAction = PGOOptions::CSIRInstr;
1172     } else
1173       PGOOpt = PGOOptions("",
1174                           CodeGenOpts.InstrProfileOutput.empty()
1175                               ? std::string(DefaultProfileGenName)
1176                               : CodeGenOpts.InstrProfileOutput,
1177                           "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1178                           CodeGenOpts.DebugInfoForProfiling);
1179   }
1180 
1181   PipelineTuningOptions PTO;
1182   PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
1183   // For historical reasons, loop interleaving is set to mirror setting for loop
1184   // unrolling.
1185   PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1186   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1187   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
1188   // Only enable CGProfilePass when using integrated assembler, since
1189   // non-integrated assemblers don't recognize .cgprofile section.
1190   PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
1191   PTO.Coroutines = LangOpts.Coroutines;
1192 
1193   PassInstrumentationCallbacks PIC;
1194   StandardInstrumentations SI(CodeGenOpts.DebugPassManager);
1195   SI.registerCallbacks(PIC);
1196   PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
1197 
1198   // Attempt to load pass plugins and register their callbacks with PB.
1199   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1200     auto PassPlugin = PassPlugin::Load(PluginFN);
1201     if (PassPlugin) {
1202       PassPlugin->registerPassBuilderCallbacks(PB);
1203     } else {
1204       Diags.Report(diag::err_fe_unable_to_load_plugin)
1205           << PluginFN << toString(PassPlugin.takeError());
1206     }
1207   }
1208 #define HANDLE_EXTENSION(Ext)                                                  \
1209   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1210 #include "llvm/Support/Extension.def"
1211 
1212   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
1213   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
1214   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
1215   ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
1216 
1217   // Register the AA manager first so that our version is the one used.
1218   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1219 
1220   // Register the target library analysis directly and give it a customized
1221   // preset TLI.
1222   Triple TargetTriple(TheModule->getTargetTriple());
1223   std::unique_ptr<TargetLibraryInfoImpl> TLII(
1224       createTLII(TargetTriple, CodeGenOpts));
1225   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1226 
1227   // Register all the basic analyses with the managers.
1228   PB.registerModuleAnalyses(MAM);
1229   PB.registerCGSCCAnalyses(CGAM);
1230   PB.registerFunctionAnalyses(FAM);
1231   PB.registerLoopAnalyses(LAM);
1232   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1233 
1234   if (TM)
1235     TM->registerPassBuilderCallbacks(PB, CodeGenOpts.DebugPassManager);
1236 
1237   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
1238 
1239   if (!CodeGenOpts.DisableLLVMPasses) {
1240     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
1241     bool IsLTO = CodeGenOpts.PrepareForLTO;
1242 
1243     if (CodeGenOpts.OptimizationLevel == 0) {
1244       // If we reached here with a non-empty index file name, then the index
1245       // file was empty and we are not performing ThinLTO backend compilation
1246       // (used in testing in a distributed build environment). Drop any the type
1247       // test assume sequences inserted for whole program vtables so that
1248       // codegen doesn't complain.
1249       if (!CodeGenOpts.ThinLTOIndexFile.empty())
1250         MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1251                                        /*ImportSummary=*/nullptr,
1252                                        /*DropTypeTests=*/true));
1253       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
1254         MPM.addPass(GCOVProfilerPass(*Options));
1255       if (Optional<InstrProfOptions> Options =
1256               getInstrProfOptions(CodeGenOpts, LangOpts))
1257         MPM.addPass(InstrProfiling(*Options, false));
1258 
1259       // Build a minimal pipeline based on the semantics required by Clang,
1260       // which is just that always inlining occurs. Further, disable generating
1261       // lifetime intrinsics to avoid enabling further optimizations during
1262       // code generation.
1263       // However, we need to insert lifetime intrinsics to avoid invalid access
1264       // caused by multithreaded coroutines.
1265       MPM.addPass(
1266           AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/LangOpts.Coroutines));
1267 
1268       // At -O0, we can still do PGO. Add all the requested passes for
1269       // instrumentation PGO, if requested.
1270       if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1271                      PGOOpt->Action == PGOOptions::IRUse))
1272         PB.addPGOInstrPassesForO0(
1273             MPM, CodeGenOpts.DebugPassManager,
1274             /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1275             /* IsCS */ false, PGOOpt->ProfileFile,
1276             PGOOpt->ProfileRemappingFile);
1277 
1278       // At -O0 we directly run necessary sanitizer passes.
1279       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1280         MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1281 
1282       // Lastly, add semantically necessary passes for LTO.
1283       if (IsLTO || IsThinLTO) {
1284         MPM.addPass(CanonicalizeAliasesPass());
1285         MPM.addPass(NameAnonGlobalPass());
1286       }
1287     } else {
1288       // Map our optimization levels into one of the distinct levels used to
1289       // configure the pipeline.
1290       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1291 
1292       // If we reached here with a non-empty index file name, then the index
1293       // file was empty and we are not performing ThinLTO backend compilation
1294       // (used in testing in a distributed build environment). Drop any the type
1295       // test assume sequences inserted for whole program vtables so that
1296       // codegen doesn't complain.
1297       if (!CodeGenOpts.ThinLTOIndexFile.empty())
1298         PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1299           MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1300                                          /*ImportSummary=*/nullptr,
1301                                          /*DropTypeTests=*/true));
1302         });
1303 
1304       PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1305         MPM.addPass(createModuleToFunctionPassAdaptor(
1306             EntryExitInstrumenterPass(/*PostInlining=*/false)));
1307       });
1308 
1309       // Register callbacks to schedule sanitizer passes at the appropriate part of
1310       // the pipeline.
1311       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1312         PB.registerScalarOptimizerLateEPCallback(
1313             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1314               FPM.addPass(BoundsCheckingPass());
1315             });
1316 
1317       if (CodeGenOpts.SanitizeCoverageType ||
1318           CodeGenOpts.SanitizeCoverageIndirectCalls ||
1319           CodeGenOpts.SanitizeCoverageTraceCmp) {
1320         PB.registerOptimizerLastEPCallback(
1321             [this](ModulePassManager &MPM,
1322                    PassBuilder::OptimizationLevel Level) {
1323               auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1324               MPM.addPass(ModuleSanitizerCoveragePass(
1325                   SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
1326                   CodeGenOpts.SanitizeCoverageBlocklistFiles));
1327             });
1328       }
1329 
1330       if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1331         int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1332         bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory);
1333         PB.registerOptimizerLastEPCallback(
1334             [TrackOrigins, Recover](ModulePassManager &MPM,
1335                                     PassBuilder::OptimizationLevel Level) {
1336               MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
1337               MPM.addPass(createModuleToFunctionPassAdaptor(
1338                   MemorySanitizerPass({TrackOrigins, Recover, false})));
1339             });
1340       }
1341       if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1342         PB.registerOptimizerLastEPCallback(
1343             [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1344               MPM.addPass(ThreadSanitizerPass());
1345               MPM.addPass(
1346                   createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1347             });
1348       }
1349       if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1350         bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
1351         bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
1352         bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1353         bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1354         PB.registerOptimizerLastEPCallback(
1355             [Recover, UseAfterScope, ModuleUseAfterScope, UseOdrIndicator](
1356                 ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1357               MPM.addPass(
1358                   RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1359               MPM.addPass(ModuleAddressSanitizerPass(
1360                   /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
1361                   UseOdrIndicator));
1362               MPM.addPass(
1363                   createModuleToFunctionPassAdaptor(AddressSanitizerPass(
1364                       /*CompileKernel=*/false, Recover, UseAfterScope)));
1365             });
1366       }
1367 
1368       if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1369         bool Recover =
1370             CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1371         PB.registerOptimizerLastEPCallback(
1372             [Recover](ModulePassManager &MPM,
1373                       PassBuilder::OptimizationLevel Level) {
1374               MPM.addPass(HWAddressSanitizerPass(
1375                   /*CompileKernel=*/false, Recover));
1376             });
1377       }
1378       if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1379         bool Recover =
1380             CodeGenOpts.SanitizeRecover.has(SanitizerKind::KernelHWAddress);
1381         PB.registerOptimizerLastEPCallback(
1382             [Recover](ModulePassManager &MPM,
1383                       PassBuilder::OptimizationLevel Level) {
1384               MPM.addPass(HWAddressSanitizerPass(
1385                   /*CompileKernel=*/true, Recover));
1386             });
1387       }
1388 
1389       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
1390         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1391           MPM.addPass(GCOVProfilerPass(*Options));
1392         });
1393       if (Optional<InstrProfOptions> Options =
1394               getInstrProfOptions(CodeGenOpts, LangOpts))
1395         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1396           MPM.addPass(InstrProfiling(*Options, false));
1397         });
1398 
1399       if (IsThinLTO) {
1400         MPM = PB.buildThinLTOPreLinkDefaultPipeline(
1401             Level, CodeGenOpts.DebugPassManager);
1402         MPM.addPass(CanonicalizeAliasesPass());
1403         MPM.addPass(NameAnonGlobalPass());
1404       } else if (IsLTO) {
1405         MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
1406                                                 CodeGenOpts.DebugPassManager);
1407         MPM.addPass(CanonicalizeAliasesPass());
1408         MPM.addPass(NameAnonGlobalPass());
1409       } else {
1410         MPM = PB.buildPerModuleDefaultPipeline(Level,
1411                                                CodeGenOpts.DebugPassManager);
1412       }
1413     }
1414 
1415     // Add UniqueInternalLinkageNames Pass which renames internal linkage
1416     // symbols with unique names.
1417     if (CodeGenOpts.UniqueInternalLinkageNames)
1418       MPM.addPass(UniqueInternalLinkageNamesPass());
1419 
1420     if (CodeGenOpts.MemProf) {
1421       MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1422       MPM.addPass(ModuleMemProfilerPass());
1423     }
1424 
1425     if (CodeGenOpts.OptimizationLevel == 0) {
1426       // FIXME: the backends do not handle matrix intrinsics currently. Make
1427       // sure they are also lowered in O0. A lightweight version of the pass
1428       // should run in the backend pipeline on demand.
1429       if (LangOpts.MatrixTypes)
1430         MPM.addPass(
1431             createModuleToFunctionPassAdaptor(LowerMatrixIntrinsicsPass()));
1432 
1433       addCoroutinePassesAtO0(MPM, LangOpts, CodeGenOpts);
1434       addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
1435     }
1436   }
1437 
1438   // FIXME: We still use the legacy pass manager to do code generation. We
1439   // create that pass manager here and use it as needed below.
1440   legacy::PassManager CodeGenPasses;
1441   bool NeedCodeGen = false;
1442   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1443 
1444   // Append any output we need to the pass manager.
1445   switch (Action) {
1446   case Backend_EmitNothing:
1447     break;
1448 
1449   case Backend_EmitBC:
1450     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1451       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1452         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1453         if (!ThinLinkOS)
1454           return;
1455       }
1456       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1457                                CodeGenOpts.EnableSplitLTOUnit);
1458       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1459                                                            : nullptr));
1460     } else {
1461       // Emit a module summary by default for Regular LTO except for ld64
1462       // targets
1463       bool EmitLTOSummary =
1464           (CodeGenOpts.PrepareForLTO &&
1465            !CodeGenOpts.DisableLLVMPasses &&
1466            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1467                llvm::Triple::Apple);
1468       if (EmitLTOSummary) {
1469         if (!TheModule->getModuleFlag("ThinLTO"))
1470           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1471         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1472                                  uint32_t(1));
1473       }
1474       MPM.addPass(
1475           BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1476     }
1477     break;
1478 
1479   case Backend_EmitLL:
1480     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1481     break;
1482 
1483   case Backend_EmitAssembly:
1484   case Backend_EmitMCNull:
1485   case Backend_EmitObj:
1486     NeedCodeGen = true;
1487     CodeGenPasses.add(
1488         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1489     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1490       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1491       if (!DwoOS)
1492         return;
1493     }
1494     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1495                        DwoOS ? &DwoOS->os() : nullptr))
1496       // FIXME: Should we handle this error differently?
1497       return;
1498     break;
1499   }
1500 
1501   // Before executing passes, print the final values of the LLVM options.
1502   cl::PrintOptionValues();
1503 
1504   // Now that we have all of the passes ready, run them.
1505   {
1506     PrettyStackTraceString CrashInfo("Optimizer");
1507     MPM.run(*TheModule, MAM);
1508   }
1509 
1510   // Now if needed, run the legacy PM for codegen.
1511   if (NeedCodeGen) {
1512     PrettyStackTraceString CrashInfo("Code generation");
1513     CodeGenPasses.run(*TheModule);
1514   }
1515 
1516   if (ThinLinkOS)
1517     ThinLinkOS->keep();
1518   if (DwoOS)
1519     DwoOS->keep();
1520 }
1521 
1522 static void runThinLTOBackend(
1523     DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M,
1524     const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts,
1525     const clang::TargetOptions &TOpts, const LangOptions &LOpts,
1526     std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile,
1527     std::string ProfileRemapping, BackendAction Action) {
1528   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1529       ModuleToDefinedGVSummaries;
1530   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1531 
1532   setCommandLineOpts(CGOpts);
1533 
1534   // We can simply import the values mentioned in the combined index, since
1535   // we should only invoke this using the individual indexes written out
1536   // via a WriteIndexesThinBackend.
1537   FunctionImporter::ImportMapTy ImportList;
1538   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1539   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1540   if (!lto::loadReferencedModules(*M, *CombinedIndex, ImportList, ModuleMap,
1541                                   OwnedImports))
1542     return;
1543 
1544   auto AddStream = [&](size_t Task) {
1545     return std::make_unique<lto::NativeObjectStream>(std::move(OS));
1546   };
1547   lto::Config Conf;
1548   if (CGOpts.SaveTempsFilePrefix != "") {
1549     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1550                                     /* UseInputModulePath */ false)) {
1551       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1552         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1553                << '\n';
1554       });
1555     }
1556   }
1557   Conf.CPU = TOpts.CPU;
1558   Conf.CodeModel = getCodeModel(CGOpts);
1559   Conf.MAttrs = TOpts.Features;
1560   Conf.RelocModel = CGOpts.RelocationModel;
1561   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1562   Conf.OptLevel = CGOpts.OptimizationLevel;
1563   initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1564   Conf.SampleProfile = std::move(SampleProfile);
1565   Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1566   // For historical reasons, loop interleaving is set to mirror setting for loop
1567   // unrolling.
1568   Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1569   Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1570   Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1571   // Only enable CGProfilePass when using integrated assembler, since
1572   // non-integrated assemblers don't recognize .cgprofile section.
1573   Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1574 
1575   // Context sensitive profile.
1576   if (CGOpts.hasProfileCSIRInstr()) {
1577     Conf.RunCSIRInstr = true;
1578     Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1579   } else if (CGOpts.hasProfileCSIRUse()) {
1580     Conf.RunCSIRInstr = false;
1581     Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1582   }
1583 
1584   Conf.ProfileRemapping = std::move(ProfileRemapping);
1585   Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1586   Conf.DebugPassManager = CGOpts.DebugPassManager;
1587   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1588   Conf.RemarksFilename = CGOpts.OptRecordFile;
1589   Conf.RemarksPasses = CGOpts.OptRecordPasses;
1590   Conf.RemarksFormat = CGOpts.OptRecordFormat;
1591   Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1592   Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1593   switch (Action) {
1594   case Backend_EmitNothing:
1595     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1596       return false;
1597     };
1598     break;
1599   case Backend_EmitLL:
1600     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1601       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1602       return false;
1603     };
1604     break;
1605   case Backend_EmitBC:
1606     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1607       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1608       return false;
1609     };
1610     break;
1611   default:
1612     Conf.CGFileType = getCodeGenFileType(Action);
1613     break;
1614   }
1615   if (Error E =
1616           thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1617                       ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1618                       ModuleMap, &CGOpts.CmdArgs)) {
1619     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1620       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1621     });
1622   }
1623 }
1624 
1625 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1626                               const HeaderSearchOptions &HeaderOpts,
1627                               const CodeGenOptions &CGOpts,
1628                               const clang::TargetOptions &TOpts,
1629                               const LangOptions &LOpts,
1630                               const llvm::DataLayout &TDesc, Module *M,
1631                               BackendAction Action,
1632                               std::unique_ptr<raw_pwrite_stream> OS) {
1633 
1634   llvm::TimeTraceScope TimeScope("Backend");
1635 
1636   std::unique_ptr<llvm::Module> EmptyModule;
1637   if (!CGOpts.ThinLTOIndexFile.empty()) {
1638     // If we are performing a ThinLTO importing compile, load the function index
1639     // into memory and pass it into runThinLTOBackend, which will run the
1640     // function importer and invoke LTO passes.
1641     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1642         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1643                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1644     if (!IndexOrErr) {
1645       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1646                             "Error loading index file '" +
1647                             CGOpts.ThinLTOIndexFile + "': ");
1648       return;
1649     }
1650     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1651     // A null CombinedIndex means we should skip ThinLTO compilation
1652     // (LLVM will optionally ignore empty index files, returning null instead
1653     // of an error).
1654     if (CombinedIndex) {
1655       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1656         runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1657                           TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1658                           CGOpts.ProfileRemappingFile, Action);
1659         return;
1660       }
1661       // Distributed indexing detected that nothing from the module is needed
1662       // for the final linking. So we can skip the compilation. We sill need to
1663       // output an empty object file to make sure that a linker does not fail
1664       // trying to read it. Also for some features, like CFI, we must skip
1665       // the compilation as CombinedIndex does not contain all required
1666       // information.
1667       EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1668       EmptyModule->setTargetTriple(M->getTargetTriple());
1669       M = EmptyModule.get();
1670     }
1671   }
1672 
1673   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1674 
1675   if (CGOpts.ExperimentalNewPassManager)
1676     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1677   else
1678     AsmHelper.EmitAssembly(Action, std::move(OS));
1679 
1680   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1681   // DataLayout.
1682   if (AsmHelper.TM) {
1683     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1684     if (DLDesc != TDesc.getStringRepresentation()) {
1685       unsigned DiagID = Diags.getCustomDiagID(
1686           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1687                                     "expected target description '%1'");
1688       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1689     }
1690   }
1691 }
1692 
1693 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1694 // __LLVM,__bitcode section.
1695 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1696                          llvm::MemoryBufferRef Buf) {
1697   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1698     return;
1699   llvm::EmbedBitcodeInModule(
1700       *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1701       CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1702       &CGOpts.CmdArgs);
1703 }
1704