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