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