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   if (TM)
1218     TM->registerPassBuilderCallbacks(PB, CodeGenOpts.DebugPassManager);
1219 
1220   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
1221 
1222   if (!CodeGenOpts.DisableLLVMPasses) {
1223     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
1224     bool IsLTO = CodeGenOpts.PrepareForLTO;
1225 
1226     if (CodeGenOpts.OptimizationLevel == 0) {
1227       // If we reached here with a non-empty index file name, then the index
1228       // file was empty and we are not performing ThinLTO backend compilation
1229       // (used in testing in a distributed build environment). Drop any the type
1230       // test assume sequences inserted for whole program vtables so that
1231       // codegen doesn't complain.
1232       if (!CodeGenOpts.ThinLTOIndexFile.empty())
1233         MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1234                                        /*ImportSummary=*/nullptr,
1235                                        /*DropTypeTests=*/true));
1236       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
1237         MPM.addPass(GCOVProfilerPass(*Options));
1238       if (Optional<InstrProfOptions> Options =
1239               getInstrProfOptions(CodeGenOpts, LangOpts))
1240         MPM.addPass(InstrProfiling(*Options, false));
1241 
1242       // Build a minimal pipeline based on the semantics required by Clang,
1243       // which is just that always inlining occurs. Further, disable generating
1244       // lifetime intrinsics to avoid enabling further optimizations during
1245       // code generation.
1246       // However, we need to insert lifetime intrinsics to avoid invalid access
1247       // caused by multithreaded coroutines.
1248       MPM.addPass(
1249           AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/LangOpts.Coroutines));
1250 
1251       // At -O0, we can still do PGO. Add all the requested passes for
1252       // instrumentation PGO, if requested.
1253       if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1254                      PGOOpt->Action == PGOOptions::IRUse))
1255         PB.addPGOInstrPassesForO0(
1256             MPM, CodeGenOpts.DebugPassManager,
1257             /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1258             /* IsCS */ false, PGOOpt->ProfileFile,
1259             PGOOpt->ProfileRemappingFile);
1260 
1261       // At -O0 we directly run necessary sanitizer passes.
1262       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1263         MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1264 
1265       // Lastly, add semantically necessary passes for LTO.
1266       if (IsLTO || IsThinLTO) {
1267         MPM.addPass(CanonicalizeAliasesPass());
1268         MPM.addPass(NameAnonGlobalPass());
1269       }
1270     } else {
1271       // Map our optimization levels into one of the distinct levels used to
1272       // configure the pipeline.
1273       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1274 
1275       // If we reached here with a non-empty index file name, then the index
1276       // file was empty and we are not performing ThinLTO backend compilation
1277       // (used in testing in a distributed build environment). Drop any the type
1278       // test assume sequences inserted for whole program vtables so that
1279       // codegen doesn't complain.
1280       if (!CodeGenOpts.ThinLTOIndexFile.empty())
1281         PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1282           MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1283                                          /*ImportSummary=*/nullptr,
1284                                          /*DropTypeTests=*/true));
1285         });
1286 
1287       PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1288         MPM.addPass(createModuleToFunctionPassAdaptor(
1289             EntryExitInstrumenterPass(/*PostInlining=*/false)));
1290       });
1291 
1292       // Register callbacks to schedule sanitizer passes at the appropriate part of
1293       // the pipeline.
1294       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1295         PB.registerScalarOptimizerLateEPCallback(
1296             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1297               FPM.addPass(BoundsCheckingPass());
1298             });
1299 
1300       if (CodeGenOpts.SanitizeCoverageType ||
1301           CodeGenOpts.SanitizeCoverageIndirectCalls ||
1302           CodeGenOpts.SanitizeCoverageTraceCmp) {
1303         PB.registerOptimizerLastEPCallback(
1304             [this](ModulePassManager &MPM,
1305                    PassBuilder::OptimizationLevel Level) {
1306               auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1307               MPM.addPass(ModuleSanitizerCoveragePass(
1308                   SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
1309                   CodeGenOpts.SanitizeCoverageBlocklistFiles));
1310             });
1311       }
1312 
1313       if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1314         int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1315         bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory);
1316         PB.registerOptimizerLastEPCallback(
1317             [TrackOrigins, Recover](ModulePassManager &MPM,
1318                                     PassBuilder::OptimizationLevel Level) {
1319               MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
1320               MPM.addPass(createModuleToFunctionPassAdaptor(
1321                   MemorySanitizerPass({TrackOrigins, Recover, false})));
1322             });
1323       }
1324       if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1325         PB.registerOptimizerLastEPCallback(
1326             [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1327               MPM.addPass(ThreadSanitizerPass());
1328               MPM.addPass(
1329                   createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1330             });
1331       }
1332       if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1333         bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
1334         bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
1335         bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1336         bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1337         PB.registerOptimizerLastEPCallback(
1338             [Recover, UseAfterScope, ModuleUseAfterScope, UseOdrIndicator](
1339                 ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1340               MPM.addPass(
1341                   RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1342               MPM.addPass(ModuleAddressSanitizerPass(
1343                   /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
1344                   UseOdrIndicator));
1345               MPM.addPass(
1346                   createModuleToFunctionPassAdaptor(AddressSanitizerPass(
1347                       /*CompileKernel=*/false, Recover, UseAfterScope)));
1348             });
1349       }
1350       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
1351         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1352           MPM.addPass(GCOVProfilerPass(*Options));
1353         });
1354       if (Optional<InstrProfOptions> Options =
1355               getInstrProfOptions(CodeGenOpts, LangOpts))
1356         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1357           MPM.addPass(InstrProfiling(*Options, false));
1358         });
1359 
1360       if (IsThinLTO) {
1361         MPM = PB.buildThinLTOPreLinkDefaultPipeline(
1362             Level, CodeGenOpts.DebugPassManager);
1363         MPM.addPass(CanonicalizeAliasesPass());
1364         MPM.addPass(NameAnonGlobalPass());
1365       } else if (IsLTO) {
1366         MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
1367                                                 CodeGenOpts.DebugPassManager);
1368         MPM.addPass(CanonicalizeAliasesPass());
1369         MPM.addPass(NameAnonGlobalPass());
1370       } else {
1371         MPM = PB.buildPerModuleDefaultPipeline(Level,
1372                                                CodeGenOpts.DebugPassManager);
1373       }
1374     }
1375 
1376     // Add UniqueInternalLinkageNames Pass which renames internal linkage
1377     // symbols with unique names.
1378     if (CodeGenOpts.UniqueInternalLinkageNames)
1379       MPM.addPass(UniqueInternalLinkageNamesPass());
1380 
1381     if (CodeGenOpts.MemProf) {
1382       MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1383       MPM.addPass(ModuleMemProfilerPass());
1384     }
1385 
1386     if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1387       bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1388       MPM.addPass(HWAddressSanitizerPass(
1389           /*CompileKernel=*/false, Recover));
1390     }
1391     if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1392       MPM.addPass(HWAddressSanitizerPass(
1393           /*CompileKernel=*/true, /*Recover=*/true));
1394     }
1395 
1396     if (CodeGenOpts.OptimizationLevel == 0) {
1397       // FIXME: the backends do not handle matrix intrinsics currently. Make
1398       // sure they are also lowered in O0. A lightweight version of the pass
1399       // should run in the backend pipeline on demand.
1400       if (LangOpts.MatrixTypes)
1401         MPM.addPass(
1402             createModuleToFunctionPassAdaptor(LowerMatrixIntrinsicsPass()));
1403 
1404       addCoroutinePassesAtO0(MPM, LangOpts, CodeGenOpts);
1405       addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
1406     }
1407   }
1408 
1409   // FIXME: We still use the legacy pass manager to do code generation. We
1410   // create that pass manager here and use it as needed below.
1411   legacy::PassManager CodeGenPasses;
1412   bool NeedCodeGen = false;
1413   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1414 
1415   // Append any output we need to the pass manager.
1416   switch (Action) {
1417   case Backend_EmitNothing:
1418     break;
1419 
1420   case Backend_EmitBC:
1421     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1422       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1423         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1424         if (!ThinLinkOS)
1425           return;
1426       }
1427       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1428                                CodeGenOpts.EnableSplitLTOUnit);
1429       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1430                                                            : nullptr));
1431     } else {
1432       // Emit a module summary by default for Regular LTO except for ld64
1433       // targets
1434       bool EmitLTOSummary =
1435           (CodeGenOpts.PrepareForLTO &&
1436            !CodeGenOpts.DisableLLVMPasses &&
1437            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1438                llvm::Triple::Apple);
1439       if (EmitLTOSummary) {
1440         if (!TheModule->getModuleFlag("ThinLTO"))
1441           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1442         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1443                                  uint32_t(1));
1444       }
1445       MPM.addPass(
1446           BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1447     }
1448     break;
1449 
1450   case Backend_EmitLL:
1451     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1452     break;
1453 
1454   case Backend_EmitAssembly:
1455   case Backend_EmitMCNull:
1456   case Backend_EmitObj:
1457     NeedCodeGen = true;
1458     CodeGenPasses.add(
1459         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1460     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1461       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1462       if (!DwoOS)
1463         return;
1464     }
1465     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1466                        DwoOS ? &DwoOS->os() : nullptr))
1467       // FIXME: Should we handle this error differently?
1468       return;
1469     break;
1470   }
1471 
1472   // Before executing passes, print the final values of the LLVM options.
1473   cl::PrintOptionValues();
1474 
1475   // Now that we have all of the passes ready, run them.
1476   {
1477     PrettyStackTraceString CrashInfo("Optimizer");
1478     MPM.run(*TheModule, MAM);
1479   }
1480 
1481   // Now if needed, run the legacy PM for codegen.
1482   if (NeedCodeGen) {
1483     PrettyStackTraceString CrashInfo("Code generation");
1484     CodeGenPasses.run(*TheModule);
1485   }
1486 
1487   if (ThinLinkOS)
1488     ThinLinkOS->keep();
1489   if (DwoOS)
1490     DwoOS->keep();
1491 }
1492 
1493 static void runThinLTOBackend(
1494     DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M,
1495     const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts,
1496     const clang::TargetOptions &TOpts, const LangOptions &LOpts,
1497     std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile,
1498     std::string ProfileRemapping, BackendAction Action) {
1499   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1500       ModuleToDefinedGVSummaries;
1501   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1502 
1503   setCommandLineOpts(CGOpts);
1504 
1505   // We can simply import the values mentioned in the combined index, since
1506   // we should only invoke this using the individual indexes written out
1507   // via a WriteIndexesThinBackend.
1508   FunctionImporter::ImportMapTy ImportList;
1509   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1510   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1511   if (!lto::loadReferencedModules(*M, *CombinedIndex, ImportList, ModuleMap,
1512                                   OwnedImports))
1513     return;
1514 
1515   auto AddStream = [&](size_t Task) {
1516     return std::make_unique<lto::NativeObjectStream>(std::move(OS));
1517   };
1518   lto::Config Conf;
1519   if (CGOpts.SaveTempsFilePrefix != "") {
1520     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1521                                     /* UseInputModulePath */ false)) {
1522       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1523         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1524                << '\n';
1525       });
1526     }
1527   }
1528   Conf.CPU = TOpts.CPU;
1529   Conf.CodeModel = getCodeModel(CGOpts);
1530   Conf.MAttrs = TOpts.Features;
1531   Conf.RelocModel = CGOpts.RelocationModel;
1532   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1533   Conf.OptLevel = CGOpts.OptimizationLevel;
1534   initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1535   Conf.SampleProfile = std::move(SampleProfile);
1536   Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1537   // For historical reasons, loop interleaving is set to mirror setting for loop
1538   // unrolling.
1539   Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1540   Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1541   Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1542   // Only enable CGProfilePass when using integrated assembler, since
1543   // non-integrated assemblers don't recognize .cgprofile section.
1544   Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1545 
1546   // Context sensitive profile.
1547   if (CGOpts.hasProfileCSIRInstr()) {
1548     Conf.RunCSIRInstr = true;
1549     Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1550   } else if (CGOpts.hasProfileCSIRUse()) {
1551     Conf.RunCSIRInstr = false;
1552     Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1553   }
1554 
1555   Conf.ProfileRemapping = std::move(ProfileRemapping);
1556   Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1557   Conf.DebugPassManager = CGOpts.DebugPassManager;
1558   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1559   Conf.RemarksFilename = CGOpts.OptRecordFile;
1560   Conf.RemarksPasses = CGOpts.OptRecordPasses;
1561   Conf.RemarksFormat = CGOpts.OptRecordFormat;
1562   Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1563   Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1564   switch (Action) {
1565   case Backend_EmitNothing:
1566     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1567       return false;
1568     };
1569     break;
1570   case Backend_EmitLL:
1571     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1572       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1573       return false;
1574     };
1575     break;
1576   case Backend_EmitBC:
1577     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1578       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1579       return false;
1580     };
1581     break;
1582   default:
1583     Conf.CGFileType = getCodeGenFileType(Action);
1584     break;
1585   }
1586   if (Error E =
1587           thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1588                       ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1589                       ModuleMap, &CGOpts.CmdArgs)) {
1590     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1591       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1592     });
1593   }
1594 }
1595 
1596 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1597                               const HeaderSearchOptions &HeaderOpts,
1598                               const CodeGenOptions &CGOpts,
1599                               const clang::TargetOptions &TOpts,
1600                               const LangOptions &LOpts,
1601                               const llvm::DataLayout &TDesc, Module *M,
1602                               BackendAction Action,
1603                               std::unique_ptr<raw_pwrite_stream> OS) {
1604 
1605   llvm::TimeTraceScope TimeScope("Backend");
1606 
1607   std::unique_ptr<llvm::Module> EmptyModule;
1608   if (!CGOpts.ThinLTOIndexFile.empty()) {
1609     // If we are performing a ThinLTO importing compile, load the function index
1610     // into memory and pass it into runThinLTOBackend, which will run the
1611     // function importer and invoke LTO passes.
1612     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1613         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1614                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1615     if (!IndexOrErr) {
1616       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1617                             "Error loading index file '" +
1618                             CGOpts.ThinLTOIndexFile + "': ");
1619       return;
1620     }
1621     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1622     // A null CombinedIndex means we should skip ThinLTO compilation
1623     // (LLVM will optionally ignore empty index files, returning null instead
1624     // of an error).
1625     if (CombinedIndex) {
1626       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1627         runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1628                           TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1629                           CGOpts.ProfileRemappingFile, Action);
1630         return;
1631       }
1632       // Distributed indexing detected that nothing from the module is needed
1633       // for the final linking. So we can skip the compilation. We sill need to
1634       // output an empty object file to make sure that a linker does not fail
1635       // trying to read it. Also for some features, like CFI, we must skip
1636       // the compilation as CombinedIndex does not contain all required
1637       // information.
1638       EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1639       EmptyModule->setTargetTriple(M->getTargetTriple());
1640       M = EmptyModule.get();
1641     }
1642   }
1643 
1644   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1645 
1646   if (CGOpts.ExperimentalNewPassManager)
1647     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1648   else
1649     AsmHelper.EmitAssembly(Action, std::move(OS));
1650 
1651   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1652   // DataLayout.
1653   if (AsmHelper.TM) {
1654     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1655     if (DLDesc != TDesc.getStringRepresentation()) {
1656       unsigned DiagID = Diags.getCustomDiagID(
1657           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1658                                     "expected target description '%1'");
1659       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1660     }
1661   }
1662 }
1663 
1664 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1665 // __LLVM,__bitcode section.
1666 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1667                          llvm::MemoryBufferRef Buf) {
1668   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1669     return;
1670   llvm::EmbedBitcodeInModule(
1671       *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1672       CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1673       &CGOpts.CmdArgs);
1674 }
1675