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/CodeGenOptions.h"
12 #include "clang/Basic/Diagnostic.h"
13 #include "clang/Basic/LangOptions.h"
14 #include "clang/Basic/TargetOptions.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/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/Timer.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Transforms/Coroutines.h"
50 #include "llvm/Transforms/IPO.h"
51 #include "llvm/Transforms/IPO/AlwaysInliner.h"
52 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
53 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
54 #include "llvm/Transforms/InstCombine/InstCombine.h"
55 #include "llvm/Transforms/Instrumentation.h"
56 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
57 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
58 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
59 #include "llvm/Transforms/ObjCARC.h"
60 #include "llvm/Transforms/Scalar.h"
61 #include "llvm/Transforms/Scalar/GVN.h"
62 #include "llvm/Transforms/Utils.h"
63 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
64 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
65 #include "llvm/Transforms/Utils/SymbolRewriter.h"
66 #include <memory>
67 using namespace clang;
68 using namespace llvm;
69 
70 namespace {
71 
72 // Default filename used for profile generation.
73 static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
74 
75 class EmitAssemblyHelper {
76   DiagnosticsEngine &Diags;
77   const HeaderSearchOptions &HSOpts;
78   const CodeGenOptions &CodeGenOpts;
79   const clang::TargetOptions &TargetOpts;
80   const LangOptions &LangOpts;
81   Module *TheModule;
82 
83   Timer CodeGenerationTime;
84 
85   std::unique_ptr<raw_pwrite_stream> OS;
86 
87   TargetIRAnalysis getTargetIRAnalysis() const {
88     if (TM)
89       return TM->getTargetIRAnalysis();
90 
91     return TargetIRAnalysis();
92   }
93 
94   void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
95 
96   /// Generates the TargetMachine.
97   /// Leaves TM unchanged if it is unable to create the target machine.
98   /// Some of our clang tests specify triples which are not built
99   /// into clang. This is okay because these tests check the generated
100   /// IR, and they require DataLayout which depends on the triple.
101   /// In this case, we allow this method to fail and not report an error.
102   /// When MustCreateTM is used, we print an error if we are unable to load
103   /// the requested target.
104   void CreateTargetMachine(bool MustCreateTM);
105 
106   /// Add passes necessary to emit assembly or LLVM IR.
107   ///
108   /// \return True on success.
109   bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
110                      raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
111 
112   std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
113     std::error_code EC;
114     auto F = llvm::make_unique<llvm::ToolOutputFile>(Path, EC,
115                                                      llvm::sys::fs::F_None);
116     if (EC) {
117       Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
118       F.reset();
119     }
120     return F;
121   }
122 
123 public:
124   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
125                      const HeaderSearchOptions &HeaderSearchOpts,
126                      const CodeGenOptions &CGOpts,
127                      const clang::TargetOptions &TOpts,
128                      const LangOptions &LOpts, Module *M)
129       : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
130         TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
131         CodeGenerationTime("codegen", "Code Generation Time") {}
132 
133   ~EmitAssemblyHelper() {
134     if (CodeGenOpts.DisableFree)
135       BuryPointer(std::move(TM));
136   }
137 
138   std::unique_ptr<TargetMachine> TM;
139 
140   void EmitAssembly(BackendAction Action,
141                     std::unique_ptr<raw_pwrite_stream> OS);
142 
143   void EmitAssemblyWithNewPassManager(BackendAction Action,
144                                       std::unique_ptr<raw_pwrite_stream> OS);
145 };
146 
147 // We need this wrapper to access LangOpts and CGOpts from extension functions
148 // that we add to the PassManagerBuilder.
149 class PassManagerBuilderWrapper : public PassManagerBuilder {
150 public:
151   PassManagerBuilderWrapper(const Triple &TargetTriple,
152                             const CodeGenOptions &CGOpts,
153                             const LangOptions &LangOpts)
154       : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
155         LangOpts(LangOpts) {}
156   const Triple &getTargetTriple() const { return TargetTriple; }
157   const CodeGenOptions &getCGOpts() const { return CGOpts; }
158   const LangOptions &getLangOpts() const { return LangOpts; }
159 
160 private:
161   const Triple &TargetTriple;
162   const CodeGenOptions &CGOpts;
163   const LangOptions &LangOpts;
164 };
165 }
166 
167 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
168   if (Builder.OptLevel > 0)
169     PM.add(createObjCARCAPElimPass());
170 }
171 
172 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
173   if (Builder.OptLevel > 0)
174     PM.add(createObjCARCExpandPass());
175 }
176 
177 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
178   if (Builder.OptLevel > 0)
179     PM.add(createObjCARCOptPass());
180 }
181 
182 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
183                                      legacy::PassManagerBase &PM) {
184   PM.add(createAddDiscriminatorsPass());
185 }
186 
187 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
188                                   legacy::PassManagerBase &PM) {
189   PM.add(createBoundsCheckingLegacyPass());
190 }
191 
192 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
193                                      legacy::PassManagerBase &PM) {
194   const PassManagerBuilderWrapper &BuilderWrapper =
195       static_cast<const PassManagerBuilderWrapper&>(Builder);
196   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
197   SanitizerCoverageOptions Opts;
198   Opts.CoverageType =
199       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
200   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
201   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
202   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
203   Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
204   Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
205   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
206   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
207   Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
208   Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
209   Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
210   Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
211   Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
212   PM.add(createSanitizerCoverageModulePass(Opts));
213 }
214 
215 // Check if ASan should use GC-friendly instrumentation for globals.
216 // First of all, there is no point if -fdata-sections is off (expect for MachO,
217 // where this is not a factor). Also, on ELF this feature requires an assembler
218 // extension that only works with -integrated-as at the moment.
219 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
220   if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
221     return false;
222   switch (T.getObjectFormat()) {
223   case Triple::MachO:
224   case Triple::COFF:
225     return true;
226   case Triple::ELF:
227     return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
228   default:
229     return false;
230   }
231 }
232 
233 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
234                                       legacy::PassManagerBase &PM) {
235   const PassManagerBuilderWrapper &BuilderWrapper =
236       static_cast<const PassManagerBuilderWrapper&>(Builder);
237   const Triple &T = BuilderWrapper.getTargetTriple();
238   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
239   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
240   bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
241   bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator;
242   bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
243   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
244                                             UseAfterScope));
245   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/ false, Recover,
246                                           UseGlobalsGC, UseOdrIndicator));
247 }
248 
249 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
250                                             legacy::PassManagerBase &PM) {
251   PM.add(createAddressSanitizerFunctionPass(
252       /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false));
253   PM.add(createAddressSanitizerModulePass(
254       /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true,
255       /*UseOdrIndicator*/ false));
256 }
257 
258 static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
259                                             legacy::PassManagerBase &PM) {
260   const PassManagerBuilderWrapper &BuilderWrapper =
261       static_cast<const PassManagerBuilderWrapper &>(Builder);
262   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
263   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
264   PM.add(createHWAddressSanitizerPass(/*CompileKernel*/ false, Recover));
265 }
266 
267 static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
268                                             legacy::PassManagerBase &PM) {
269   PM.add(createHWAddressSanitizerPass(
270       /*CompileKernel*/ true, /*Recover*/ true));
271 }
272 
273 static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
274                                              legacy::PassManagerBase &PM,
275                                              bool CompileKernel) {
276   const PassManagerBuilderWrapper &BuilderWrapper =
277       static_cast<const PassManagerBuilderWrapper&>(Builder);
278   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
279   int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
280   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
281   PM.add(createMemorySanitizerLegacyPassPass(TrackOrigins, Recover, CompileKernel));
282 
283   // MemorySanitizer inserts complex instrumentation that mostly follows
284   // the logic of the original code, but operates on "shadow" values.
285   // It can benefit from re-running some general purpose optimization passes.
286   if (Builder.OptLevel > 0) {
287     PM.add(createEarlyCSEPass());
288     PM.add(createReassociatePass());
289     PM.add(createLICMPass());
290     PM.add(createGVNPass());
291     PM.add(createInstructionCombiningPass());
292     PM.add(createDeadStoreEliminationPass());
293   }
294 }
295 
296 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
297                                    legacy::PassManagerBase &PM) {
298   addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false);
299 }
300 
301 static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder,
302                                          legacy::PassManagerBase &PM) {
303   addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true);
304 }
305 
306 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
307                                    legacy::PassManagerBase &PM) {
308   PM.add(createThreadSanitizerPass());
309 }
310 
311 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
312                                      legacy::PassManagerBase &PM) {
313   const PassManagerBuilderWrapper &BuilderWrapper =
314       static_cast<const PassManagerBuilderWrapper&>(Builder);
315   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
316   PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
317 }
318 
319 static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
320                                        legacy::PassManagerBase &PM) {
321   const PassManagerBuilderWrapper &BuilderWrapper =
322       static_cast<const PassManagerBuilderWrapper&>(Builder);
323   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
324   EfficiencySanitizerOptions Opts;
325   if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
326     Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
327   else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet))
328     Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet;
329   PM.add(createEfficiencySanitizerPass(Opts));
330 }
331 
332 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
333                                          const CodeGenOptions &CodeGenOpts) {
334   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
335   if (!CodeGenOpts.SimplifyLibCalls)
336     TLII->disableAllFunctions();
337   else {
338     // Disable individual libc/libm calls in TargetLibraryInfo.
339     LibFunc F;
340     for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
341       if (TLII->getLibFunc(FuncName, F))
342         TLII->setUnavailable(F);
343   }
344 
345   switch (CodeGenOpts.getVecLib()) {
346   case CodeGenOptions::Accelerate:
347     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
348     break;
349   case CodeGenOptions::SVML:
350     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
351     break;
352   default:
353     break;
354   }
355   return TLII;
356 }
357 
358 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
359                                   legacy::PassManager *MPM) {
360   llvm::SymbolRewriter::RewriteDescriptorList DL;
361 
362   llvm::SymbolRewriter::RewriteMapParser MapParser;
363   for (const auto &MapFile : Opts.RewriteMapFiles)
364     MapParser.parse(MapFile, &DL);
365 
366   MPM->add(createRewriteSymbolsPass(DL));
367 }
368 
369 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
370   switch (CodeGenOpts.OptimizationLevel) {
371   default:
372     llvm_unreachable("Invalid optimization level!");
373   case 0:
374     return CodeGenOpt::None;
375   case 1:
376     return CodeGenOpt::Less;
377   case 2:
378     return CodeGenOpt::Default; // O2/Os/Oz
379   case 3:
380     return CodeGenOpt::Aggressive;
381   }
382 }
383 
384 static Optional<llvm::CodeModel::Model>
385 getCodeModel(const CodeGenOptions &CodeGenOpts) {
386   unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
387                            .Case("tiny", llvm::CodeModel::Tiny)
388                            .Case("small", llvm::CodeModel::Small)
389                            .Case("kernel", llvm::CodeModel::Kernel)
390                            .Case("medium", llvm::CodeModel::Medium)
391                            .Case("large", llvm::CodeModel::Large)
392                            .Case("default", ~1u)
393                            .Default(~0u);
394   assert(CodeModel != ~0u && "invalid code model!");
395   if (CodeModel == ~1u)
396     return None;
397   return static_cast<llvm::CodeModel::Model>(CodeModel);
398 }
399 
400 static TargetMachine::CodeGenFileType getCodeGenFileType(BackendAction Action) {
401   if (Action == Backend_EmitObj)
402     return TargetMachine::CGFT_ObjectFile;
403   else if (Action == Backend_EmitMCNull)
404     return TargetMachine::CGFT_Null;
405   else {
406     assert(Action == Backend_EmitAssembly && "Invalid action!");
407     return TargetMachine::CGFT_AssemblyFile;
408   }
409 }
410 
411 static void initTargetOptions(llvm::TargetOptions &Options,
412                               const CodeGenOptions &CodeGenOpts,
413                               const clang::TargetOptions &TargetOpts,
414                               const LangOptions &LangOpts,
415                               const HeaderSearchOptions &HSOpts) {
416   Options.ThreadModel =
417       llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
418           .Case("posix", llvm::ThreadModel::POSIX)
419           .Case("single", llvm::ThreadModel::Single);
420 
421   // Set float ABI type.
422   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
423           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
424          "Invalid Floating Point ABI!");
425   Options.FloatABIType =
426       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
427           .Case("soft", llvm::FloatABI::Soft)
428           .Case("softfp", llvm::FloatABI::Soft)
429           .Case("hard", llvm::FloatABI::Hard)
430           .Default(llvm::FloatABI::Default);
431 
432   // Set FP fusion mode.
433   switch (LangOpts.getDefaultFPContractMode()) {
434   case LangOptions::FPC_Off:
435     // Preserve any contraction performed by the front-end.  (Strict performs
436     // splitting of the muladd intrinsic in the backend.)
437     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
438     break;
439   case LangOptions::FPC_On:
440     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
441     break;
442   case LangOptions::FPC_Fast:
443     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
444     break;
445   }
446 
447   Options.UseInitArray = CodeGenOpts.UseInitArray;
448   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
449   Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
450   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
451 
452   // Set EABI version.
453   Options.EABIVersion = TargetOpts.EABIVersion;
454 
455   if (LangOpts.SjLjExceptions)
456     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
457   if (LangOpts.SEHExceptions)
458     Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
459   if (LangOpts.DWARFExceptions)
460     Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
461 
462   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
463   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
464   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
465   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
466   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
467   Options.FunctionSections = CodeGenOpts.FunctionSections;
468   Options.DataSections = CodeGenOpts.DataSections;
469   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
470   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
471   Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
472   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
473   Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
474   Options.EmitAddrsig = CodeGenOpts.Addrsig;
475 
476   if (CodeGenOpts.getSplitDwarfMode() != CodeGenOptions::NoFission)
477     Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
478   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
479   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
480   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
481   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
482   Options.MCOptions.MCIncrementalLinkerCompatible =
483       CodeGenOpts.IncrementalLinkerCompatible;
484   Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
485   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
486   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
487   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
488   Options.MCOptions.ABIName = TargetOpts.ABI;
489   for (const auto &Entry : HSOpts.UserEntries)
490     if (!Entry.IsFramework &&
491         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
492          Entry.Group == frontend::IncludeDirGroup::Angled ||
493          Entry.Group == frontend::IncludeDirGroup::System))
494       Options.MCOptions.IASSearchPaths.push_back(
495           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
496 }
497 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) {
498   if (CodeGenOpts.DisableGCov)
499     return None;
500   if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
501     return None;
502   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
503   // LLVM's -default-gcov-version flag is set to something invalid.
504   GCOVOptions Options;
505   Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
506   Options.EmitData = CodeGenOpts.EmitGcovArcs;
507   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
508   Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
509   Options.NoRedZone = CodeGenOpts.DisableRedZone;
510   Options.FunctionNamesInData = !CodeGenOpts.CoverageNoFunctionNamesInData;
511   Options.Filter = CodeGenOpts.ProfileFilterFiles;
512   Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
513   Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
514   return Options;
515 }
516 
517 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
518                                       legacy::FunctionPassManager &FPM) {
519   // Handle disabling of all LLVM passes, where we want to preserve the
520   // internal module before any optimization.
521   if (CodeGenOpts.DisableLLVMPasses)
522     return;
523 
524   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
525   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
526   // are inserted before PMBuilder ones - they'd get the default-constructed
527   // TLI with an unknown target otherwise.
528   Triple TargetTriple(TheModule->getTargetTriple());
529   std::unique_ptr<TargetLibraryInfoImpl> TLII(
530       createTLII(TargetTriple, CodeGenOpts));
531 
532   PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
533 
534   // At O0 and O1 we only run the always inliner which is more efficient. At
535   // higher optimization levels we run the normal inliner.
536   if (CodeGenOpts.OptimizationLevel <= 1) {
537     bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
538                                      !CodeGenOpts.DisableLifetimeMarkers);
539     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
540   } else {
541     // We do not want to inline hot callsites for SamplePGO module-summary build
542     // because profile annotation will happen again in ThinLTO backend, and we
543     // want the IR of the hot path to match the profile.
544     PMBuilder.Inliner = createFunctionInliningPass(
545         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
546         (!CodeGenOpts.SampleProfileFile.empty() &&
547          CodeGenOpts.PrepareForThinLTO));
548   }
549 
550   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
551   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
552   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
553   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
554 
555   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
556   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
557   PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
558   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
559   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
560 
561   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
562 
563   if (TM)
564     TM->adjustPassManager(PMBuilder);
565 
566   if (CodeGenOpts.DebugInfoForProfiling ||
567       !CodeGenOpts.SampleProfileFile.empty())
568     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
569                            addAddDiscriminatorsPass);
570 
571   // In ObjC ARC mode, add the main ARC optimization passes.
572   if (LangOpts.ObjCAutoRefCount) {
573     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
574                            addObjCARCExpandPass);
575     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
576                            addObjCARCAPElimPass);
577     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
578                            addObjCARCOptPass);
579   }
580 
581   if (LangOpts.CoroutinesTS)
582     addCoroutinePassesToExtensionPoints(PMBuilder);
583 
584   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
585     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
586                            addBoundsCheckingPass);
587     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
588                            addBoundsCheckingPass);
589   }
590 
591   if (CodeGenOpts.SanitizeCoverageType ||
592       CodeGenOpts.SanitizeCoverageIndirectCalls ||
593       CodeGenOpts.SanitizeCoverageTraceCmp) {
594     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
595                            addSanitizerCoveragePass);
596     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
597                            addSanitizerCoveragePass);
598   }
599 
600   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
601     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
602                            addAddressSanitizerPasses);
603     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
604                            addAddressSanitizerPasses);
605   }
606 
607   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
608     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
609                            addKernelAddressSanitizerPasses);
610     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
611                            addKernelAddressSanitizerPasses);
612   }
613 
614   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
615     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
616                            addHWAddressSanitizerPasses);
617     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
618                            addHWAddressSanitizerPasses);
619   }
620 
621   if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
622     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
623                            addKernelHWAddressSanitizerPasses);
624     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
625                            addKernelHWAddressSanitizerPasses);
626   }
627 
628   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
629     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
630                            addMemorySanitizerPass);
631     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
632                            addMemorySanitizerPass);
633   }
634 
635   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
636     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
637                            addKernelMemorySanitizerPass);
638     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
639                            addKernelMemorySanitizerPass);
640   }
641 
642   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
643     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
644                            addThreadSanitizerPass);
645     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
646                            addThreadSanitizerPass);
647   }
648 
649   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
650     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
651                            addDataFlowSanitizerPass);
652     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
653                            addDataFlowSanitizerPass);
654   }
655 
656   if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
657     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
658                            addEfficiencySanitizerPass);
659     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
660                            addEfficiencySanitizerPass);
661   }
662 
663   // Set up the per-function pass manager.
664   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
665   if (CodeGenOpts.VerifyModule)
666     FPM.add(createVerifierPass());
667 
668   // Set up the per-module pass manager.
669   if (!CodeGenOpts.RewriteMapFiles.empty())
670     addSymbolRewriterPass(CodeGenOpts, &MPM);
671 
672   if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
673     MPM.add(createGCOVProfilerPass(*Options));
674     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
675       MPM.add(createStripSymbolsPass(true));
676   }
677 
678   if (CodeGenOpts.hasProfileClangInstr()) {
679     InstrProfOptions Options;
680     Options.NoRedZone = CodeGenOpts.DisableRedZone;
681     Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
682 
683     // TODO: Surface the option to emit atomic profile counter increments at
684     // the driver level.
685     Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread);
686 
687     MPM.add(createInstrProfilingLegacyPass(Options));
688   }
689   if (CodeGenOpts.hasProfileIRInstr()) {
690     PMBuilder.EnablePGOInstrGen = true;
691     if (!CodeGenOpts.InstrProfileOutput.empty())
692       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
693     else
694       PMBuilder.PGOInstrGen = DefaultProfileGenName;
695   }
696   if (CodeGenOpts.hasProfileIRUse())
697     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
698 
699   if (!CodeGenOpts.SampleProfileFile.empty())
700     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
701 
702   PMBuilder.populateFunctionPassManager(FPM);
703   PMBuilder.populateModulePassManager(MPM);
704 }
705 
706 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
707   SmallVector<const char *, 16> BackendArgs;
708   BackendArgs.push_back("clang"); // Fake program name.
709   if (!CodeGenOpts.DebugPass.empty()) {
710     BackendArgs.push_back("-debug-pass");
711     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
712   }
713   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
714     BackendArgs.push_back("-limit-float-precision");
715     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
716   }
717   BackendArgs.push_back(nullptr);
718   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
719                                     BackendArgs.data());
720 }
721 
722 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
723   // Create the TargetMachine for generating code.
724   std::string Error;
725   std::string Triple = TheModule->getTargetTriple();
726   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
727   if (!TheTarget) {
728     if (MustCreateTM)
729       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
730     return;
731   }
732 
733   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
734   std::string FeaturesStr =
735       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
736   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
737   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
738 
739   llvm::TargetOptions Options;
740   initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
741   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
742                                           Options, RM, CM, OptLevel));
743 }
744 
745 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
746                                        BackendAction Action,
747                                        raw_pwrite_stream &OS,
748                                        raw_pwrite_stream *DwoOS) {
749   // Add LibraryInfo.
750   llvm::Triple TargetTriple(TheModule->getTargetTriple());
751   std::unique_ptr<TargetLibraryInfoImpl> TLII(
752       createTLII(TargetTriple, CodeGenOpts));
753   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
754 
755   // Normal mode, emit a .s or .o file by running the code generator. Note,
756   // this also adds codegenerator level optimization passes.
757   TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
758 
759   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
760   // "codegen" passes so that it isn't run multiple times when there is
761   // inlining happening.
762   if (CodeGenOpts.OptimizationLevel > 0)
763     CodeGenPasses.add(createObjCARCContractPass());
764 
765   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
766                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
767     Diags.Report(diag::err_fe_unable_to_interface_with_target);
768     return false;
769   }
770 
771   return true;
772 }
773 
774 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
775                                       std::unique_ptr<raw_pwrite_stream> OS) {
776   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
777 
778   setCommandLineOpts(CodeGenOpts);
779 
780   bool UsesCodeGen = (Action != Backend_EmitNothing &&
781                       Action != Backend_EmitBC &&
782                       Action != Backend_EmitLL);
783   CreateTargetMachine(UsesCodeGen);
784 
785   if (UsesCodeGen && !TM)
786     return;
787   if (TM)
788     TheModule->setDataLayout(TM->createDataLayout());
789 
790   legacy::PassManager PerModulePasses;
791   PerModulePasses.add(
792       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
793 
794   legacy::FunctionPassManager PerFunctionPasses(TheModule);
795   PerFunctionPasses.add(
796       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
797 
798   CreatePasses(PerModulePasses, PerFunctionPasses);
799 
800   legacy::PassManager CodeGenPasses;
801   CodeGenPasses.add(
802       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
803 
804   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
805 
806   switch (Action) {
807   case Backend_EmitNothing:
808     break;
809 
810   case Backend_EmitBC:
811     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
812       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
813         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
814         if (!ThinLinkOS)
815           return;
816       }
817       PerModulePasses.add(createWriteThinLTOBitcodePass(
818           *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
819     } else {
820       // Emit a module summary by default for Regular LTO except for ld64
821       // targets
822       bool EmitLTOSummary =
823           (CodeGenOpts.PrepareForLTO &&
824            !CodeGenOpts.DisableLLVMPasses &&
825            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
826                llvm::Triple::Apple);
827       if (EmitLTOSummary && !TheModule->getModuleFlag("ThinLTO"))
828         TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
829 
830       PerModulePasses.add(
831           createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
832                                   EmitLTOSummary));
833     }
834     break;
835 
836   case Backend_EmitLL:
837     PerModulePasses.add(
838         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
839     break;
840 
841   default:
842     if (!CodeGenOpts.SplitDwarfFile.empty() &&
843         (CodeGenOpts.getSplitDwarfMode() == CodeGenOptions::SplitFileFission)) {
844       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfFile);
845       if (!DwoOS)
846         return;
847     }
848     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
849                        DwoOS ? &DwoOS->os() : nullptr))
850       return;
851   }
852 
853   // Before executing passes, print the final values of the LLVM options.
854   cl::PrintOptionValues();
855 
856   // Run passes. For now we do all passes at once, but eventually we
857   // would like to have the option of streaming code generation.
858 
859   {
860     PrettyStackTraceString CrashInfo("Per-function optimization");
861 
862     PerFunctionPasses.doInitialization();
863     for (Function &F : *TheModule)
864       if (!F.isDeclaration())
865         PerFunctionPasses.run(F);
866     PerFunctionPasses.doFinalization();
867   }
868 
869   {
870     PrettyStackTraceString CrashInfo("Per-module optimization passes");
871     PerModulePasses.run(*TheModule);
872   }
873 
874   {
875     PrettyStackTraceString CrashInfo("Code generation");
876     CodeGenPasses.run(*TheModule);
877   }
878 
879   if (ThinLinkOS)
880     ThinLinkOS->keep();
881   if (DwoOS)
882     DwoOS->keep();
883 }
884 
885 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
886   switch (Opts.OptimizationLevel) {
887   default:
888     llvm_unreachable("Invalid optimization level!");
889 
890   case 1:
891     return PassBuilder::O1;
892 
893   case 2:
894     switch (Opts.OptimizeSize) {
895     default:
896       llvm_unreachable("Invalid optimization level for size!");
897 
898     case 0:
899       return PassBuilder::O2;
900 
901     case 1:
902       return PassBuilder::Os;
903 
904     case 2:
905       return PassBuilder::Oz;
906     }
907 
908   case 3:
909     return PassBuilder::O3;
910   }
911 }
912 
913 /// A clean version of `EmitAssembly` that uses the new pass manager.
914 ///
915 /// Not all features are currently supported in this system, but where
916 /// necessary it falls back to the legacy pass manager to at least provide
917 /// basic functionality.
918 ///
919 /// This API is planned to have its functionality finished and then to replace
920 /// `EmitAssembly` at some point in the future when the default switches.
921 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
922     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
923   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
924   setCommandLineOpts(CodeGenOpts);
925 
926   // The new pass manager always makes a target machine available to passes
927   // during construction.
928   CreateTargetMachine(/*MustCreateTM*/ true);
929   if (!TM)
930     // This will already be diagnosed, just bail.
931     return;
932   TheModule->setDataLayout(TM->createDataLayout());
933 
934   Optional<PGOOptions> PGOOpt;
935 
936   if (CodeGenOpts.hasProfileIRInstr())
937     // -fprofile-generate.
938     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
939                             ? DefaultProfileGenName
940                             : CodeGenOpts.InstrProfileOutput,
941                         "", "", "", true,
942                         CodeGenOpts.DebugInfoForProfiling);
943   else if (CodeGenOpts.hasProfileIRUse())
944     // -fprofile-use.
945     PGOOpt = PGOOptions("", CodeGenOpts.ProfileInstrumentUsePath, "",
946                         CodeGenOpts.ProfileRemappingFile, false,
947                         CodeGenOpts.DebugInfoForProfiling);
948   else if (!CodeGenOpts.SampleProfileFile.empty())
949     // -fprofile-sample-use
950     PGOOpt = PGOOptions("", "", CodeGenOpts.SampleProfileFile,
951                         CodeGenOpts.ProfileRemappingFile, false,
952                         CodeGenOpts.DebugInfoForProfiling);
953   else if (CodeGenOpts.DebugInfoForProfiling)
954     // -fdebug-info-for-profiling
955     PGOOpt = PGOOptions("", "", "", "", false, true);
956 
957   PassBuilder PB(TM.get(), PGOOpt);
958 
959   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
960   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
961   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
962   ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
963 
964   // Register the AA manager first so that our version is the one used.
965   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
966 
967   // Register the target library analysis directly and give it a customized
968   // preset TLI.
969   Triple TargetTriple(TheModule->getTargetTriple());
970   std::unique_ptr<TargetLibraryInfoImpl> TLII(
971       createTLII(TargetTriple, CodeGenOpts));
972   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
973   MAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
974 
975   // Register all the basic analyses with the managers.
976   PB.registerModuleAnalyses(MAM);
977   PB.registerCGSCCAnalyses(CGAM);
978   PB.registerFunctionAnalyses(FAM);
979   PB.registerLoopAnalyses(LAM);
980   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
981 
982   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
983 
984   if (!CodeGenOpts.DisableLLVMPasses) {
985     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
986     bool IsLTO = CodeGenOpts.PrepareForLTO;
987 
988     if (CodeGenOpts.OptimizationLevel == 0) {
989       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
990         MPM.addPass(GCOVProfilerPass(*Options));
991 
992       // Build a minimal pipeline based on the semantics required by Clang,
993       // which is just that always inlining occurs.
994       MPM.addPass(AlwaysInlinerPass());
995 
996       // At -O0 we directly run necessary sanitizer passes.
997       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
998         MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
999 
1000       // Lastly, add semantically necessary passes for LTO.
1001       if (IsLTO || IsThinLTO) {
1002         MPM.addPass(CanonicalizeAliasesPass());
1003         MPM.addPass(NameAnonGlobalPass());
1004       }
1005     } else {
1006       // Map our optimization levels into one of the distinct levels used to
1007       // configure the pipeline.
1008       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1009 
1010       // Register callbacks to schedule sanitizer passes at the appropriate part of
1011       // the pipeline.
1012       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1013         PB.registerScalarOptimizerLateEPCallback(
1014             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1015               FPM.addPass(BoundsCheckingPass());
1016             });
1017       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1018         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1019           MPM.addPass(GCOVProfilerPass(*Options));
1020         });
1021 
1022       if (IsThinLTO) {
1023         MPM = PB.buildThinLTOPreLinkDefaultPipeline(
1024             Level, CodeGenOpts.DebugPassManager);
1025         MPM.addPass(CanonicalizeAliasesPass());
1026         MPM.addPass(NameAnonGlobalPass());
1027       } else if (IsLTO) {
1028         MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
1029                                                 CodeGenOpts.DebugPassManager);
1030         MPM.addPass(CanonicalizeAliasesPass());
1031         MPM.addPass(NameAnonGlobalPass());
1032       } else {
1033         MPM = PB.buildPerModuleDefaultPipeline(Level,
1034                                                CodeGenOpts.DebugPassManager);
1035       }
1036     }
1037   }
1038 
1039   // FIXME: We still use the legacy pass manager to do code generation. We
1040   // create that pass manager here and use it as needed below.
1041   legacy::PassManager CodeGenPasses;
1042   bool NeedCodeGen = false;
1043   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1044 
1045   // Append any output we need to the pass manager.
1046   switch (Action) {
1047   case Backend_EmitNothing:
1048     break;
1049 
1050   case Backend_EmitBC:
1051     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1052       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1053         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1054         if (!ThinLinkOS)
1055           return;
1056       }
1057       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1058                                                            : nullptr));
1059     } else {
1060       // Emit a module summary by default for Regular LTO except for ld64
1061       // targets
1062       bool EmitLTOSummary =
1063           (CodeGenOpts.PrepareForLTO &&
1064            !CodeGenOpts.DisableLLVMPasses &&
1065            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1066                llvm::Triple::Apple);
1067       if (EmitLTOSummary && !TheModule->getModuleFlag("ThinLTO"))
1068         TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1069 
1070       MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1071                                     EmitLTOSummary));
1072     }
1073     break;
1074 
1075   case Backend_EmitLL:
1076     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1077     break;
1078 
1079   case Backend_EmitAssembly:
1080   case Backend_EmitMCNull:
1081   case Backend_EmitObj:
1082     NeedCodeGen = true;
1083     CodeGenPasses.add(
1084         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1085     if (!CodeGenOpts.SplitDwarfFile.empty()) {
1086       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfFile);
1087       if (!DwoOS)
1088         return;
1089     }
1090     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1091                        DwoOS ? &DwoOS->os() : nullptr))
1092       // FIXME: Should we handle this error differently?
1093       return;
1094     break;
1095   }
1096 
1097   // Before executing passes, print the final values of the LLVM options.
1098   cl::PrintOptionValues();
1099 
1100   // Now that we have all of the passes ready, run them.
1101   {
1102     PrettyStackTraceString CrashInfo("Optimizer");
1103     MPM.run(*TheModule, MAM);
1104   }
1105 
1106   // Now if needed, run the legacy PM for codegen.
1107   if (NeedCodeGen) {
1108     PrettyStackTraceString CrashInfo("Code generation");
1109     CodeGenPasses.run(*TheModule);
1110   }
1111 
1112   if (ThinLinkOS)
1113     ThinLinkOS->keep();
1114   if (DwoOS)
1115     DwoOS->keep();
1116 }
1117 
1118 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1119   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1120   if (!BMsOrErr)
1121     return BMsOrErr.takeError();
1122 
1123   // The bitcode file may contain multiple modules, we want the one that is
1124   // marked as being the ThinLTO module.
1125   if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1126     return *Bm;
1127 
1128   return make_error<StringError>("Could not find module summary",
1129                                  inconvertibleErrorCode());
1130 }
1131 
1132 BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1133   for (BitcodeModule &BM : BMs) {
1134     Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1135     if (LTOInfo && LTOInfo->IsThinLTO)
1136       return &BM;
1137   }
1138   return nullptr;
1139 }
1140 
1141 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
1142                               const HeaderSearchOptions &HeaderOpts,
1143                               const CodeGenOptions &CGOpts,
1144                               const clang::TargetOptions &TOpts,
1145                               const LangOptions &LOpts,
1146                               std::unique_ptr<raw_pwrite_stream> OS,
1147                               std::string SampleProfile,
1148                               std::string ProfileRemapping,
1149                               BackendAction Action) {
1150   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1151       ModuleToDefinedGVSummaries;
1152   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1153 
1154   setCommandLineOpts(CGOpts);
1155 
1156   // We can simply import the values mentioned in the combined index, since
1157   // we should only invoke this using the individual indexes written out
1158   // via a WriteIndexesThinBackend.
1159   FunctionImporter::ImportMapTy ImportList;
1160   for (auto &GlobalList : *CombinedIndex) {
1161     // Ignore entries for undefined references.
1162     if (GlobalList.second.SummaryList.empty())
1163       continue;
1164 
1165     auto GUID = GlobalList.first;
1166     for (auto &Summary : GlobalList.second.SummaryList) {
1167       // Skip the summaries for the importing module. These are included to
1168       // e.g. record required linkage changes.
1169       if (Summary->modulePath() == M->getModuleIdentifier())
1170         continue;
1171       // Add an entry to provoke importing by thinBackend.
1172       ImportList[Summary->modulePath()].insert(GUID);
1173     }
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