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