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