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