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