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