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