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