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 void addMemTagOptimizationPasses(const PassManagerBuilder &Builder,
356                                         legacy::PassManagerBase &PM) {
357   PM.add(createStackSafetyGlobalInfoWrapperPass());
358 }
359 
360 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
361                                          const CodeGenOptions &CodeGenOpts) {
362   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
363 
364   switch (CodeGenOpts.getVecLib()) {
365   case CodeGenOptions::Accelerate:
366     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
367     break;
368   case CodeGenOptions::MASSV:
369     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
370     break;
371   case CodeGenOptions::SVML:
372     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
373     break;
374   default:
375     break;
376   }
377   return TLII;
378 }
379 
380 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
381                                   legacy::PassManager *MPM) {
382   llvm::SymbolRewriter::RewriteDescriptorList DL;
383 
384   llvm::SymbolRewriter::RewriteMapParser MapParser;
385   for (const auto &MapFile : Opts.RewriteMapFiles)
386     MapParser.parse(MapFile, &DL);
387 
388   MPM->add(createRewriteSymbolsPass(DL));
389 }
390 
391 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
392   switch (CodeGenOpts.OptimizationLevel) {
393   default:
394     llvm_unreachable("Invalid optimization level!");
395   case 0:
396     return CodeGenOpt::None;
397   case 1:
398     return CodeGenOpt::Less;
399   case 2:
400     return CodeGenOpt::Default; // O2/Os/Oz
401   case 3:
402     return CodeGenOpt::Aggressive;
403   }
404 }
405 
406 static Optional<llvm::CodeModel::Model>
407 getCodeModel(const CodeGenOptions &CodeGenOpts) {
408   unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
409                            .Case("tiny", llvm::CodeModel::Tiny)
410                            .Case("small", llvm::CodeModel::Small)
411                            .Case("kernel", llvm::CodeModel::Kernel)
412                            .Case("medium", llvm::CodeModel::Medium)
413                            .Case("large", llvm::CodeModel::Large)
414                            .Case("default", ~1u)
415                            .Default(~0u);
416   assert(CodeModel != ~0u && "invalid code model!");
417   if (CodeModel == ~1u)
418     return None;
419   return static_cast<llvm::CodeModel::Model>(CodeModel);
420 }
421 
422 static CodeGenFileType getCodeGenFileType(BackendAction Action) {
423   if (Action == Backend_EmitObj)
424     return CGFT_ObjectFile;
425   else if (Action == Backend_EmitMCNull)
426     return CGFT_Null;
427   else {
428     assert(Action == Backend_EmitAssembly && "Invalid action!");
429     return CGFT_AssemblyFile;
430   }
431 }
432 
433 static void initTargetOptions(DiagnosticsEngine &Diags,
434                               llvm::TargetOptions &Options,
435                               const CodeGenOptions &CodeGenOpts,
436                               const clang::TargetOptions &TargetOpts,
437                               const LangOptions &LangOpts,
438                               const HeaderSearchOptions &HSOpts) {
439   Options.ThreadModel =
440       llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
441           .Case("posix", llvm::ThreadModel::POSIX)
442           .Case("single", llvm::ThreadModel::Single);
443 
444   // Set float ABI type.
445   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
446           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
447          "Invalid Floating Point ABI!");
448   Options.FloatABIType =
449       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
450           .Case("soft", llvm::FloatABI::Soft)
451           .Case("softfp", llvm::FloatABI::Soft)
452           .Case("hard", llvm::FloatABI::Hard)
453           .Default(llvm::FloatABI::Default);
454 
455   // Set FP fusion mode.
456   switch (LangOpts.getDefaultFPContractMode()) {
457   case LangOptions::FPM_Off:
458     // Preserve any contraction performed by the front-end.  (Strict performs
459     // splitting of the muladd intrinsic in the backend.)
460     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
461     break;
462   case LangOptions::FPM_On:
463     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
464     break;
465   case LangOptions::FPM_Fast:
466     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
467     break;
468   }
469 
470   Options.UseInitArray = CodeGenOpts.UseInitArray;
471   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
472   Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
473   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
474 
475   // Set EABI version.
476   Options.EABIVersion = TargetOpts.EABIVersion;
477 
478   if (LangOpts.SjLjExceptions)
479     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
480   if (LangOpts.SEHExceptions)
481     Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
482   if (LangOpts.DWARFExceptions)
483     Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
484   if (LangOpts.WasmExceptions)
485     Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
486 
487   Options.NoInfsFPMath = LangOpts.NoHonorInfs;
488   Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
489   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
490   Options.UnsafeFPMath = LangOpts.UnsafeFPMath;
491   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
492 
493   Options.BBSections =
494       llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections)
495           .Case("all", llvm::BasicBlockSection::All)
496           .Case("labels", llvm::BasicBlockSection::Labels)
497           .StartsWith("list=", llvm::BasicBlockSection::List)
498           .Case("none", llvm::BasicBlockSection::None)
499           .Default(llvm::BasicBlockSection::None);
500 
501   if (Options.BBSections == llvm::BasicBlockSection::List) {
502     ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
503         MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5));
504     if (!MBOrErr)
505       Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file)
506           << MBOrErr.getError().message();
507     else
508       Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
509   }
510 
511   Options.FunctionSections = CodeGenOpts.FunctionSections;
512   Options.DataSections = CodeGenOpts.DataSections;
513   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
514   Options.UniqueBasicBlockSectionNames =
515       CodeGenOpts.UniqueBasicBlockSectionNames;
516   Options.TLSSize = CodeGenOpts.TLSSize;
517   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
518   Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
519   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
520   Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
521   Options.EmitAddrsig = CodeGenOpts.Addrsig;
522   Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
523   Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
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 }
545 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) {
546   if (CodeGenOpts.DisableGCov)
547     return None;
548   if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
549     return None;
550   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
551   // LLVM's -default-gcov-version flag is set to something invalid.
552   GCOVOptions Options;
553   Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
554   Options.EmitData = CodeGenOpts.EmitGcovArcs;
555   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
556   Options.NoRedZone = CodeGenOpts.DisableRedZone;
557   Options.Filter = CodeGenOpts.ProfileFilterFiles;
558   Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
559   return Options;
560 }
561 
562 static Optional<InstrProfOptions>
563 getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
564                     const LangOptions &LangOpts) {
565   if (!CodeGenOpts.hasProfileClangInstr())
566     return None;
567   InstrProfOptions Options;
568   Options.NoRedZone = CodeGenOpts.DisableRedZone;
569   Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
570 
571   // TODO: Surface the option to emit atomic profile counter increments at
572   // the driver level.
573   Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread);
574   return Options;
575 }
576 
577 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
578                                       legacy::FunctionPassManager &FPM) {
579   // Handle disabling of all LLVM passes, where we want to preserve the
580   // internal module before any optimization.
581   if (CodeGenOpts.DisableLLVMPasses)
582     return;
583 
584   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
585   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
586   // are inserted before PMBuilder ones - they'd get the default-constructed
587   // TLI with an unknown target otherwise.
588   Triple TargetTriple(TheModule->getTargetTriple());
589   std::unique_ptr<TargetLibraryInfoImpl> TLII(
590       createTLII(TargetTriple, CodeGenOpts));
591 
592   // If we reached here with a non-empty index file name, then the index file
593   // was empty and we are not performing ThinLTO backend compilation (used in
594   // testing in a distributed build environment). Drop any the type test
595   // assume sequences inserted for whole program vtables so that codegen doesn't
596   // complain.
597   if (!CodeGenOpts.ThinLTOIndexFile.empty())
598     MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr,
599                                      /*ImportSummary=*/nullptr,
600                                      /*DropTypeTests=*/true));
601 
602   PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
603 
604   // At O0 and O1 we only run the always inliner which is more efficient. At
605   // higher optimization levels we run the normal inliner.
606   if (CodeGenOpts.OptimizationLevel <= 1) {
607     bool InsertLifetimeIntrinsics = ((CodeGenOpts.OptimizationLevel != 0 &&
608                                       !CodeGenOpts.DisableLifetimeMarkers) ||
609                                      LangOpts.Coroutines);
610     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
611   } else {
612     // We do not want to inline hot callsites for SamplePGO module-summary build
613     // because profile annotation will happen again in ThinLTO backend, and we
614     // want the IR of the hot path to match the profile.
615     PMBuilder.Inliner = createFunctionInliningPass(
616         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
617         (!CodeGenOpts.SampleProfileFile.empty() &&
618          CodeGenOpts.PrepareForThinLTO));
619   }
620 
621   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
622   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
623   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
624   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
625 
626   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
627   // Loop interleaving in the loop vectorizer has historically been set to be
628   // enabled when loop unrolling is enabled.
629   PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
630   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
631   PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
632   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
633   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
634 
635   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
636 
637   if (TM)
638     TM->adjustPassManager(PMBuilder);
639 
640   if (CodeGenOpts.DebugInfoForProfiling ||
641       !CodeGenOpts.SampleProfileFile.empty())
642     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
643                            addAddDiscriminatorsPass);
644 
645   // In ObjC ARC mode, add the main ARC optimization passes.
646   if (LangOpts.ObjCAutoRefCount) {
647     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
648                            addObjCARCExpandPass);
649     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
650                            addObjCARCAPElimPass);
651     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
652                            addObjCARCOptPass);
653   }
654 
655   if (LangOpts.Coroutines)
656     addCoroutinePassesToExtensionPoints(PMBuilder);
657 
658   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
659     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
660                            addBoundsCheckingPass);
661     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
662                            addBoundsCheckingPass);
663   }
664 
665   if (CodeGenOpts.SanitizeCoverageType ||
666       CodeGenOpts.SanitizeCoverageIndirectCalls ||
667       CodeGenOpts.SanitizeCoverageTraceCmp) {
668     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
669                            addSanitizerCoveragePass);
670     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
671                            addSanitizerCoveragePass);
672   }
673 
674   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
675     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
676                            addAddressSanitizerPasses);
677     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
678                            addAddressSanitizerPasses);
679   }
680 
681   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
682     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
683                            addKernelAddressSanitizerPasses);
684     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
685                            addKernelAddressSanitizerPasses);
686   }
687 
688   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
689     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
690                            addHWAddressSanitizerPasses);
691     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
692                            addHWAddressSanitizerPasses);
693   }
694 
695   if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
696     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
697                            addKernelHWAddressSanitizerPasses);
698     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
699                            addKernelHWAddressSanitizerPasses);
700   }
701 
702   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
703     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
704                            addMemorySanitizerPass);
705     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
706                            addMemorySanitizerPass);
707   }
708 
709   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
710     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
711                            addKernelMemorySanitizerPass);
712     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
713                            addKernelMemorySanitizerPass);
714   }
715 
716   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
717     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
718                            addThreadSanitizerPass);
719     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
720                            addThreadSanitizerPass);
721   }
722 
723   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
724     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
725                            addDataFlowSanitizerPass);
726     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
727                            addDataFlowSanitizerPass);
728   }
729 
730   if (LangOpts.Sanitize.has(SanitizerKind::MemTag)) {
731     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
732                            addMemTagOptimizationPasses);
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.SanitizeCoverageWhitelistFiles,
1033         CodeGenOpts.SanitizeCoverageBlacklistFiles));
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   PTO.CallGraphProfile = CodeGenOpts.CallGraphProfile;
1155   PTO.Coroutines = LangOpts.Coroutines;
1156 
1157   PassInstrumentationCallbacks PIC;
1158   StandardInstrumentations SI;
1159   SI.registerCallbacks(PIC);
1160   PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
1161 
1162   // Attempt to load pass plugins and register their callbacks with PB.
1163   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1164     auto PassPlugin = PassPlugin::Load(PluginFN);
1165     if (PassPlugin) {
1166       PassPlugin->registerPassBuilderCallbacks(PB);
1167     } else {
1168       Diags.Report(diag::err_fe_unable_to_load_plugin)
1169           << PluginFN << toString(PassPlugin.takeError());
1170     }
1171   }
1172 #define HANDLE_EXTENSION(Ext)                                                  \
1173   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1174 #include "llvm/Support/Extension.def"
1175 
1176   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
1177   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
1178   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
1179   ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
1180 
1181   // Register the AA manager first so that our version is the one used.
1182   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1183 
1184   // Register the target library analysis directly and give it a customized
1185   // preset TLI.
1186   Triple TargetTriple(TheModule->getTargetTriple());
1187   std::unique_ptr<TargetLibraryInfoImpl> TLII(
1188       createTLII(TargetTriple, CodeGenOpts));
1189   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1190 
1191   // Register all the basic analyses with the managers.
1192   PB.registerModuleAnalyses(MAM);
1193   PB.registerCGSCCAnalyses(CGAM);
1194   PB.registerFunctionAnalyses(FAM);
1195   PB.registerLoopAnalyses(LAM);
1196   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1197 
1198   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
1199 
1200   if (!CodeGenOpts.DisableLLVMPasses) {
1201     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
1202     bool IsLTO = CodeGenOpts.PrepareForLTO;
1203 
1204     if (CodeGenOpts.OptimizationLevel == 0) {
1205       // If we reached here with a non-empty index file name, then the index
1206       // file was empty and we are not performing ThinLTO backend compilation
1207       // (used in testing in a distributed build environment). Drop any the type
1208       // test assume sequences inserted for whole program vtables so that
1209       // codegen doesn't complain.
1210       if (!CodeGenOpts.ThinLTOIndexFile.empty())
1211         MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1212                                        /*ImportSummary=*/nullptr,
1213                                        /*DropTypeTests=*/true));
1214       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1215         MPM.addPass(GCOVProfilerPass(*Options));
1216       if (Optional<InstrProfOptions> Options =
1217               getInstrProfOptions(CodeGenOpts, LangOpts))
1218         MPM.addPass(InstrProfiling(*Options, false));
1219 
1220       // Build a minimal pipeline based on the semantics required by Clang,
1221       // which is just that always inlining occurs. Further, disable generating
1222       // lifetime intrinsics to avoid enabling further optimizations during
1223       // code generation.
1224       // However, we need to insert lifetime intrinsics to avoid invalid access
1225       // caused by multithreaded coroutines.
1226       MPM.addPass(
1227           AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/LangOpts.Coroutines));
1228 
1229       // At -O0, we can still do PGO. Add all the requested passes for
1230       // instrumentation PGO, if requested.
1231       if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1232                      PGOOpt->Action == PGOOptions::IRUse))
1233         PB.addPGOInstrPassesForO0(
1234             MPM, CodeGenOpts.DebugPassManager,
1235             /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1236             /* IsCS */ false, PGOOpt->ProfileFile,
1237             PGOOpt->ProfileRemappingFile);
1238 
1239       // At -O0 we directly run necessary sanitizer passes.
1240       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1241         MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1242 
1243       // Add UniqueInternalLinkageNames Pass which renames internal linkage
1244       // symbols with unique names.
1245       if (CodeGenOpts.UniqueInternalLinkageNames) {
1246         MPM.addPass(UniqueInternalLinkageNamesPass());
1247       }
1248 
1249       // Lastly, add semantically necessary passes for LTO.
1250       if (IsLTO || IsThinLTO) {
1251         MPM.addPass(CanonicalizeAliasesPass());
1252         MPM.addPass(NameAnonGlobalPass());
1253       }
1254     } else {
1255       // Map our optimization levels into one of the distinct levels used to
1256       // configure the pipeline.
1257       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1258 
1259       // If we reached here with a non-empty index file name, then the index
1260       // file was empty and we are not performing ThinLTO backend compilation
1261       // (used in testing in a distributed build environment). Drop any the type
1262       // test assume sequences inserted for whole program vtables so that
1263       // codegen doesn't complain.
1264       if (!CodeGenOpts.ThinLTOIndexFile.empty())
1265         PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1266           MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1267                                          /*ImportSummary=*/nullptr,
1268                                          /*DropTypeTests=*/true));
1269         });
1270 
1271       PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1272         MPM.addPass(createModuleToFunctionPassAdaptor(
1273             EntryExitInstrumenterPass(/*PostInlining=*/false)));
1274       });
1275 
1276       // Register callbacks to schedule sanitizer passes at the appropriate part of
1277       // the pipeline.
1278       // FIXME: either handle asan/the remaining sanitizers or error out
1279       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1280         PB.registerScalarOptimizerLateEPCallback(
1281             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1282               FPM.addPass(BoundsCheckingPass());
1283             });
1284 
1285       if (CodeGenOpts.SanitizeCoverageType ||
1286           CodeGenOpts.SanitizeCoverageIndirectCalls ||
1287           CodeGenOpts.SanitizeCoverageTraceCmp) {
1288         PB.registerOptimizerLastEPCallback(
1289             [this](ModulePassManager &MPM,
1290                    PassBuilder::OptimizationLevel Level) {
1291               auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1292               MPM.addPass(ModuleSanitizerCoveragePass(
1293                   SancovOpts, CodeGenOpts.SanitizeCoverageWhitelistFiles,
1294                   CodeGenOpts.SanitizeCoverageBlacklistFiles));
1295             });
1296       }
1297 
1298       if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1299         int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1300         bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory);
1301         PB.registerPipelineStartEPCallback(
1302             [TrackOrigins, Recover](ModulePassManager &MPM) {
1303               MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
1304             });
1305         PB.registerOptimizerLastEPCallback(
1306             [TrackOrigins, Recover](ModulePassManager &MPM,
1307                                     PassBuilder::OptimizationLevel Level) {
1308               MPM.addPass(createModuleToFunctionPassAdaptor(
1309                   MemorySanitizerPass({TrackOrigins, Recover, false})));
1310             });
1311       }
1312       if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1313         PB.registerPipelineStartEPCallback(
1314             [](ModulePassManager &MPM) { MPM.addPass(ThreadSanitizerPass()); });
1315         PB.registerOptimizerLastEPCallback(
1316             [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1317               MPM.addPass(
1318                   createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1319             });
1320       }
1321       if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1322         PB.registerPipelineStartEPCallback([&](ModulePassManager &MPM) {
1323           MPM.addPass(
1324               RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1325         });
1326         bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
1327         bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
1328         PB.registerOptimizerLastEPCallback(
1329             [Recover, UseAfterScope](ModulePassManager &MPM,
1330                                      PassBuilder::OptimizationLevel Level) {
1331               MPM.addPass(
1332                   createModuleToFunctionPassAdaptor(AddressSanitizerPass(
1333                       /*CompileKernel=*/false, Recover, UseAfterScope)));
1334             });
1335         bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1336         bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1337         PB.registerPipelineStartEPCallback(
1338             [Recover, ModuleUseAfterScope,
1339              UseOdrIndicator](ModulePassManager &MPM) {
1340               MPM.addPass(ModuleAddressSanitizerPass(
1341                   /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
1342                   UseOdrIndicator));
1343             });
1344       }
1345       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1346         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1347           MPM.addPass(GCOVProfilerPass(*Options));
1348         });
1349       if (Optional<InstrProfOptions> Options =
1350               getInstrProfOptions(CodeGenOpts, LangOpts))
1351         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1352           MPM.addPass(InstrProfiling(*Options, false));
1353         });
1354 
1355       // Add UniqueInternalLinkageNames Pass which renames internal linkage
1356       // symbols with unique names.
1357       if (CodeGenOpts.UniqueInternalLinkageNames) {
1358         MPM.addPass(UniqueInternalLinkageNamesPass());
1359       }
1360 
1361       if (IsThinLTO) {
1362         MPM = PB.buildThinLTOPreLinkDefaultPipeline(
1363             Level, CodeGenOpts.DebugPassManager);
1364         MPM.addPass(CanonicalizeAliasesPass());
1365         MPM.addPass(NameAnonGlobalPass());
1366       } else if (IsLTO) {
1367         MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
1368                                                 CodeGenOpts.DebugPassManager);
1369         MPM.addPass(CanonicalizeAliasesPass());
1370         MPM.addPass(NameAnonGlobalPass());
1371       } else {
1372         MPM = PB.buildPerModuleDefaultPipeline(Level,
1373                                                CodeGenOpts.DebugPassManager);
1374       }
1375     }
1376 
1377     if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1378       bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1379       MPM.addPass(HWAddressSanitizerPass(
1380           /*CompileKernel=*/false, Recover));
1381     }
1382     if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1383       MPM.addPass(HWAddressSanitizerPass(
1384           /*CompileKernel=*/true, /*Recover=*/true));
1385     }
1386 
1387     if (CodeGenOpts.OptimizationLevel > 0 &&
1388         LangOpts.Sanitize.has(SanitizerKind::MemTag)) {
1389       MPM.addPass(StackSafetyGlobalAnnotatorPass());
1390     }
1391 
1392     if (CodeGenOpts.OptimizationLevel == 0) {
1393       addCoroutinePassesAtO0(MPM, LangOpts, CodeGenOpts);
1394       addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
1395     }
1396   }
1397 
1398   // FIXME: We still use the legacy pass manager to do code generation. We
1399   // create that pass manager here and use it as needed below.
1400   legacy::PassManager CodeGenPasses;
1401   bool NeedCodeGen = false;
1402   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1403 
1404   // Append any output we need to the pass manager.
1405   switch (Action) {
1406   case Backend_EmitNothing:
1407     break;
1408 
1409   case Backend_EmitBC:
1410     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1411       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1412         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1413         if (!ThinLinkOS)
1414           return;
1415       }
1416       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1417                                CodeGenOpts.EnableSplitLTOUnit);
1418       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1419                                                            : nullptr));
1420     } else {
1421       // Emit a module summary by default for Regular LTO except for ld64
1422       // targets
1423       bool EmitLTOSummary =
1424           (CodeGenOpts.PrepareForLTO &&
1425            !CodeGenOpts.DisableLLVMPasses &&
1426            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1427                llvm::Triple::Apple);
1428       if (EmitLTOSummary) {
1429         if (!TheModule->getModuleFlag("ThinLTO"))
1430           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1431         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1432                                  uint32_t(1));
1433       }
1434       MPM.addPass(
1435           BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1436     }
1437     break;
1438 
1439   case Backend_EmitLL:
1440     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1441     break;
1442 
1443   case Backend_EmitAssembly:
1444   case Backend_EmitMCNull:
1445   case Backend_EmitObj:
1446     NeedCodeGen = true;
1447     CodeGenPasses.add(
1448         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1449     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1450       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1451       if (!DwoOS)
1452         return;
1453     }
1454     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1455                        DwoOS ? &DwoOS->os() : nullptr))
1456       // FIXME: Should we handle this error differently?
1457       return;
1458     break;
1459   }
1460 
1461   // Before executing passes, print the final values of the LLVM options.
1462   cl::PrintOptionValues();
1463 
1464   // Now that we have all of the passes ready, run them.
1465   {
1466     PrettyStackTraceString CrashInfo("Optimizer");
1467     MPM.run(*TheModule, MAM);
1468   }
1469 
1470   // Now if needed, run the legacy PM for codegen.
1471   if (NeedCodeGen) {
1472     PrettyStackTraceString CrashInfo("Code generation");
1473     CodeGenPasses.run(*TheModule);
1474   }
1475 
1476   if (ThinLinkOS)
1477     ThinLinkOS->keep();
1478   if (DwoOS)
1479     DwoOS->keep();
1480 }
1481 
1482 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1483   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1484   if (!BMsOrErr)
1485     return BMsOrErr.takeError();
1486 
1487   // The bitcode file may contain multiple modules, we want the one that is
1488   // marked as being the ThinLTO module.
1489   if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1490     return *Bm;
1491 
1492   return make_error<StringError>("Could not find module summary",
1493                                  inconvertibleErrorCode());
1494 }
1495 
1496 BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1497   for (BitcodeModule &BM : BMs) {
1498     Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1499     if (LTOInfo && LTOInfo->IsThinLTO)
1500       return &BM;
1501   }
1502   return nullptr;
1503 }
1504 
1505 static void runThinLTOBackend(
1506     DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M,
1507     const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts,
1508     const clang::TargetOptions &TOpts, const LangOptions &LOpts,
1509     std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile,
1510     std::string ProfileRemapping, BackendAction Action) {
1511   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1512       ModuleToDefinedGVSummaries;
1513   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1514 
1515   setCommandLineOpts(CGOpts);
1516 
1517   // We can simply import the values mentioned in the combined index, since
1518   // we should only invoke this using the individual indexes written out
1519   // via a WriteIndexesThinBackend.
1520   FunctionImporter::ImportMapTy ImportList;
1521   for (auto &GlobalList : *CombinedIndex) {
1522     // Ignore entries for undefined references.
1523     if (GlobalList.second.SummaryList.empty())
1524       continue;
1525 
1526     auto GUID = GlobalList.first;
1527     for (auto &Summary : GlobalList.second.SummaryList) {
1528       // Skip the summaries for the importing module. These are included to
1529       // e.g. record required linkage changes.
1530       if (Summary->modulePath() == M->getModuleIdentifier())
1531         continue;
1532       // Add an entry to provoke importing by thinBackend.
1533       ImportList[Summary->modulePath()].insert(GUID);
1534     }
1535   }
1536 
1537   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1538   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1539 
1540   for (auto &I : ImportList) {
1541     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1542         llvm::MemoryBuffer::getFile(I.first());
1543     if (!MBOrErr) {
1544       errs() << "Error loading imported file '" << I.first()
1545              << "': " << MBOrErr.getError().message() << "\n";
1546       return;
1547     }
1548 
1549     Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1550     if (!BMOrErr) {
1551       handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1552         errs() << "Error loading imported file '" << I.first()
1553                << "': " << EIB.message() << '\n';
1554       });
1555       return;
1556     }
1557     ModuleMap.insert({I.first(), *BMOrErr});
1558 
1559     OwnedImports.push_back(std::move(*MBOrErr));
1560   }
1561   auto AddStream = [&](size_t Task) {
1562     return std::make_unique<lto::NativeObjectStream>(std::move(OS));
1563   };
1564   lto::Config Conf;
1565   if (CGOpts.SaveTempsFilePrefix != "") {
1566     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1567                                     /* UseInputModulePath */ false)) {
1568       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1569         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1570                << '\n';
1571       });
1572     }
1573   }
1574   Conf.CPU = TOpts.CPU;
1575   Conf.CodeModel = getCodeModel(CGOpts);
1576   Conf.MAttrs = TOpts.Features;
1577   Conf.RelocModel = CGOpts.RelocationModel;
1578   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1579   Conf.OptLevel = CGOpts.OptimizationLevel;
1580   initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1581   Conf.SampleProfile = std::move(SampleProfile);
1582   Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1583   // For historical reasons, loop interleaving is set to mirror setting for loop
1584   // unrolling.
1585   Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1586   Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1587   Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1588   Conf.PTO.CallGraphProfile = CGOpts.CallGraphProfile;
1589 
1590   // Context sensitive profile.
1591   if (CGOpts.hasProfileCSIRInstr()) {
1592     Conf.RunCSIRInstr = true;
1593     Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1594   } else if (CGOpts.hasProfileCSIRUse()) {
1595     Conf.RunCSIRInstr = false;
1596     Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1597   }
1598 
1599   Conf.ProfileRemapping = std::move(ProfileRemapping);
1600   Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1601   Conf.DebugPassManager = CGOpts.DebugPassManager;
1602   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1603   Conf.RemarksFilename = CGOpts.OptRecordFile;
1604   Conf.RemarksPasses = CGOpts.OptRecordPasses;
1605   Conf.RemarksFormat = CGOpts.OptRecordFormat;
1606   Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1607   Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1608   switch (Action) {
1609   case Backend_EmitNothing:
1610     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1611       return false;
1612     };
1613     break;
1614   case Backend_EmitLL:
1615     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1616       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1617       return false;
1618     };
1619     break;
1620   case Backend_EmitBC:
1621     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1622       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1623       return false;
1624     };
1625     break;
1626   default:
1627     Conf.CGFileType = getCodeGenFileType(Action);
1628     break;
1629   }
1630   if (Error E = thinBackend(
1631           Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1632           ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1633     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1634       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1635     });
1636   }
1637 }
1638 
1639 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1640                               const HeaderSearchOptions &HeaderOpts,
1641                               const CodeGenOptions &CGOpts,
1642                               const clang::TargetOptions &TOpts,
1643                               const LangOptions &LOpts,
1644                               const llvm::DataLayout &TDesc, Module *M,
1645                               BackendAction Action,
1646                               std::unique_ptr<raw_pwrite_stream> OS) {
1647 
1648   llvm::TimeTraceScope TimeScope("Backend");
1649 
1650   std::unique_ptr<llvm::Module> EmptyModule;
1651   if (!CGOpts.ThinLTOIndexFile.empty()) {
1652     // If we are performing a ThinLTO importing compile, load the function index
1653     // into memory and pass it into runThinLTOBackend, which will run the
1654     // function importer and invoke LTO passes.
1655     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1656         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1657                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1658     if (!IndexOrErr) {
1659       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1660                             "Error loading index file '" +
1661                             CGOpts.ThinLTOIndexFile + "': ");
1662       return;
1663     }
1664     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1665     // A null CombinedIndex means we should skip ThinLTO compilation
1666     // (LLVM will optionally ignore empty index files, returning null instead
1667     // of an error).
1668     if (CombinedIndex) {
1669       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1670         runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1671                           TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1672                           CGOpts.ProfileRemappingFile, Action);
1673         return;
1674       }
1675       // Distributed indexing detected that nothing from the module is needed
1676       // for the final linking. So we can skip the compilation. We sill need to
1677       // output an empty object file to make sure that a linker does not fail
1678       // trying to read it. Also for some features, like CFI, we must skip
1679       // the compilation as CombinedIndex does not contain all required
1680       // information.
1681       EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1682       EmptyModule->setTargetTriple(M->getTargetTriple());
1683       M = EmptyModule.get();
1684     }
1685   }
1686 
1687   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1688 
1689   if (CGOpts.ExperimentalNewPassManager)
1690     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1691   else
1692     AsmHelper.EmitAssembly(Action, std::move(OS));
1693 
1694   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1695   // DataLayout.
1696   if (AsmHelper.TM) {
1697     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1698     if (DLDesc != TDesc.getStringRepresentation()) {
1699       unsigned DiagID = Diags.getCustomDiagID(
1700           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1701                                     "expected target description '%1'");
1702       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1703     }
1704   }
1705 }
1706 
1707 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1708 // __LLVM,__bitcode section.
1709 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1710                          llvm::MemoryBufferRef Buf) {
1711   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1712     return;
1713   llvm::EmbedBitcodeInModule(
1714       *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1715       CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1716       &CGOpts.CmdArgs);
1717 }
1718