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