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   for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
662     BackendArgs.push_back(BackendOption.c_str());
663   BackendArgs.push_back(nullptr);
664   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
665                                     BackendArgs.data());
666 }
667 
668 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
669   // Create the TargetMachine for generating code.
670   std::string Error;
671   std::string Triple = TheModule->getTargetTriple();
672   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
673   if (!TheTarget) {
674     if (MustCreateTM)
675       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
676     return;
677   }
678 
679   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
680   std::string FeaturesStr =
681       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
682   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
683   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
684 
685   llvm::TargetOptions Options;
686   initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
687   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
688                                           Options, RM, CM, OptLevel));
689 }
690 
691 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
692                                        BackendAction Action,
693                                        raw_pwrite_stream &OS) {
694   // Add LibraryInfo.
695   llvm::Triple TargetTriple(TheModule->getTargetTriple());
696   std::unique_ptr<TargetLibraryInfoImpl> TLII(
697       createTLII(TargetTriple, CodeGenOpts));
698   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
699 
700   // Normal mode, emit a .s or .o file by running the code generator. Note,
701   // this also adds codegenerator level optimization passes.
702   TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
703 
704   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
705   // "codegen" passes so that it isn't run multiple times when there is
706   // inlining happening.
707   if (CodeGenOpts.OptimizationLevel > 0)
708     CodeGenPasses.add(createObjCARCContractPass());
709 
710   if (TM->addPassesToEmitFile(CodeGenPasses, OS, CGFT,
711                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
712     Diags.Report(diag::err_fe_unable_to_interface_with_target);
713     return false;
714   }
715 
716   return true;
717 }
718 
719 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
720                                       std::unique_ptr<raw_pwrite_stream> OS) {
721   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
722 
723   setCommandLineOpts(CodeGenOpts);
724 
725   bool UsesCodeGen = (Action != Backend_EmitNothing &&
726                       Action != Backend_EmitBC &&
727                       Action != Backend_EmitLL);
728   CreateTargetMachine(UsesCodeGen);
729 
730   if (UsesCodeGen && !TM)
731     return;
732   if (TM)
733     TheModule->setDataLayout(TM->createDataLayout());
734 
735   legacy::PassManager PerModulePasses;
736   PerModulePasses.add(
737       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
738 
739   legacy::FunctionPassManager PerFunctionPasses(TheModule);
740   PerFunctionPasses.add(
741       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
742 
743   CreatePasses(PerModulePasses, PerFunctionPasses);
744 
745   legacy::PassManager CodeGenPasses;
746   CodeGenPasses.add(
747       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
748 
749   std::unique_ptr<raw_fd_ostream> ThinLinkOS;
750 
751   switch (Action) {
752   case Backend_EmitNothing:
753     break;
754 
755   case Backend_EmitBC:
756     if (CodeGenOpts.EmitSummaryIndex) {
757       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
758         std::error_code EC;
759         ThinLinkOS.reset(new llvm::raw_fd_ostream(
760             CodeGenOpts.ThinLinkBitcodeFile, EC,
761             llvm::sys::fs::F_None));
762         if (EC) {
763           Diags.Report(diag::err_fe_unable_to_open_output) << CodeGenOpts.ThinLinkBitcodeFile
764                                                            << EC.message();
765           return;
766         }
767       }
768       PerModulePasses.add(
769           createWriteThinLTOBitcodePass(*OS, ThinLinkOS.get()));
770     }
771     else
772       PerModulePasses.add(
773           createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists));
774     break;
775 
776   case Backend_EmitLL:
777     PerModulePasses.add(
778         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
779     break;
780 
781   default:
782     if (!AddEmitPasses(CodeGenPasses, Action, *OS))
783       return;
784   }
785 
786   // Before executing passes, print the final values of the LLVM options.
787   cl::PrintOptionValues();
788 
789   // Run passes. For now we do all passes at once, but eventually we
790   // would like to have the option of streaming code generation.
791 
792   {
793     PrettyStackTraceString CrashInfo("Per-function optimization");
794 
795     PerFunctionPasses.doInitialization();
796     for (Function &F : *TheModule)
797       if (!F.isDeclaration())
798         PerFunctionPasses.run(F);
799     PerFunctionPasses.doFinalization();
800   }
801 
802   {
803     PrettyStackTraceString CrashInfo("Per-module optimization passes");
804     PerModulePasses.run(*TheModule);
805   }
806 
807   {
808     PrettyStackTraceString CrashInfo("Code generation");
809     CodeGenPasses.run(*TheModule);
810   }
811 }
812 
813 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
814   switch (Opts.OptimizationLevel) {
815   default:
816     llvm_unreachable("Invalid optimization level!");
817 
818   case 1:
819     return PassBuilder::O1;
820 
821   case 2:
822     switch (Opts.OptimizeSize) {
823     default:
824       llvm_unreachable("Invalid optimization level for size!");
825 
826     case 0:
827       return PassBuilder::O2;
828 
829     case 1:
830       return PassBuilder::Os;
831 
832     case 2:
833       return PassBuilder::Oz;
834     }
835 
836   case 3:
837     return PassBuilder::O3;
838   }
839 }
840 
841 /// A clean version of `EmitAssembly` that uses the new pass manager.
842 ///
843 /// Not all features are currently supported in this system, but where
844 /// necessary it falls back to the legacy pass manager to at least provide
845 /// basic functionality.
846 ///
847 /// This API is planned to have its functionality finished and then to replace
848 /// `EmitAssembly` at some point in the future when the default switches.
849 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
850     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
851   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
852   setCommandLineOpts(CodeGenOpts);
853 
854   // The new pass manager always makes a target machine available to passes
855   // during construction.
856   CreateTargetMachine(/*MustCreateTM*/ true);
857   if (!TM)
858     // This will already be diagnosed, just bail.
859     return;
860   TheModule->setDataLayout(TM->createDataLayout());
861 
862   Optional<PGOOptions> PGOOpt;
863 
864   if (CodeGenOpts.hasProfileIRInstr())
865     // -fprofile-generate.
866     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
867                             ? DefaultProfileGenName
868                             : CodeGenOpts.InstrProfileOutput,
869                         "", "", true, CodeGenOpts.DebugInfoForProfiling);
870   else if (CodeGenOpts.hasProfileIRUse())
871     // -fprofile-use.
872     PGOOpt = PGOOptions("", CodeGenOpts.ProfileInstrumentUsePath, "", false,
873                         CodeGenOpts.DebugInfoForProfiling);
874   else if (!CodeGenOpts.SampleProfileFile.empty())
875     // -fprofile-sample-use
876     PGOOpt = PGOOptions("", "", CodeGenOpts.SampleProfileFile, false,
877                         CodeGenOpts.DebugInfoForProfiling);
878   else if (CodeGenOpts.DebugInfoForProfiling)
879     // -fdebug-info-for-profiling
880     PGOOpt = PGOOptions("", "", "", false, true);
881 
882   PassBuilder PB(TM.get(), PGOOpt);
883 
884   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
885   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
886   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
887   ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
888 
889   // Register the AA manager first so that our version is the one used.
890   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
891 
892   // Register the target library analysis directly and give it a customized
893   // preset TLI.
894   Triple TargetTriple(TheModule->getTargetTriple());
895   std::unique_ptr<TargetLibraryInfoImpl> TLII(
896       createTLII(TargetTriple, CodeGenOpts));
897   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
898   MAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
899 
900   // Register all the basic analyses with the managers.
901   PB.registerModuleAnalyses(MAM);
902   PB.registerCGSCCAnalyses(CGAM);
903   PB.registerFunctionAnalyses(FAM);
904   PB.registerLoopAnalyses(LAM);
905   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
906 
907   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
908 
909   if (!CodeGenOpts.DisableLLVMPasses) {
910     bool IsThinLTO = CodeGenOpts.EmitSummaryIndex;
911     bool IsLTO = CodeGenOpts.PrepareForLTO;
912 
913     if (CodeGenOpts.OptimizationLevel == 0) {
914       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
915         MPM.addPass(GCOVProfilerPass(*Options));
916 
917       // Build a minimal pipeline based on the semantics required by Clang,
918       // which is just that always inlining occurs.
919       MPM.addPass(AlwaysInlinerPass());
920 
921       // At -O0 we directly run necessary sanitizer passes.
922       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
923         MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
924 
925       // Lastly, add a semantically necessary pass for ThinLTO.
926       if (IsThinLTO)
927         MPM.addPass(NameAnonGlobalPass());
928     } else {
929       // Map our optimization levels into one of the distinct levels used to
930       // configure the pipeline.
931       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
932 
933       // Register callbacks to schedule sanitizer passes at the appropriate part of
934       // the pipeline.
935       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
936         PB.registerScalarOptimizerLateEPCallback(
937             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
938               FPM.addPass(BoundsCheckingPass());
939             });
940       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
941         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
942           MPM.addPass(GCOVProfilerPass(*Options));
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   if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1031     return *Bm;
1032 
1033   return make_error<StringError>("Could not find module summary",
1034                                  inconvertibleErrorCode());
1035 }
1036 
1037 BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1038   for (BitcodeModule &BM : BMs) {
1039     Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1040     if (LTOInfo && LTOInfo->IsThinLTO)
1041       return &BM;
1042   }
1043   return nullptr;
1044 }
1045 
1046 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
1047                               const HeaderSearchOptions &HeaderOpts,
1048                               const CodeGenOptions &CGOpts,
1049                               const clang::TargetOptions &TOpts,
1050                               const LangOptions &LOpts,
1051                               std::unique_ptr<raw_pwrite_stream> OS,
1052                               std::string SampleProfile,
1053                               BackendAction Action) {
1054   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1055       ModuleToDefinedGVSummaries;
1056   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1057 
1058   setCommandLineOpts(CGOpts);
1059 
1060   // We can simply import the values mentioned in the combined index, since
1061   // we should only invoke this using the individual indexes written out
1062   // via a WriteIndexesThinBackend.
1063   FunctionImporter::ImportMapTy ImportList;
1064   for (auto &GlobalList : *CombinedIndex) {
1065     // Ignore entries for undefined references.
1066     if (GlobalList.second.SummaryList.empty())
1067       continue;
1068 
1069     auto GUID = GlobalList.first;
1070     assert(GlobalList.second.SummaryList.size() == 1 &&
1071            "Expected individual combined index to have one summary per GUID");
1072     auto &Summary = GlobalList.second.SummaryList[0];
1073     // Skip the summaries for the importing module. These are included to
1074     // e.g. record required linkage changes.
1075     if (Summary->modulePath() == M->getModuleIdentifier())
1076       continue;
1077     // Doesn't matter what value we plug in to the map, just needs an entry
1078     // to provoke importing by thinBackend.
1079     ImportList[Summary->modulePath()][GUID] = 1;
1080   }
1081 
1082   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1083   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1084 
1085   for (auto &I : ImportList) {
1086     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1087         llvm::MemoryBuffer::getFile(I.first());
1088     if (!MBOrErr) {
1089       errs() << "Error loading imported file '" << I.first()
1090              << "': " << MBOrErr.getError().message() << "\n";
1091       return;
1092     }
1093 
1094     Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1095     if (!BMOrErr) {
1096       handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1097         errs() << "Error loading imported file '" << I.first()
1098                << "': " << EIB.message() << '\n';
1099       });
1100       return;
1101     }
1102     ModuleMap.insert({I.first(), *BMOrErr});
1103 
1104     OwnedImports.push_back(std::move(*MBOrErr));
1105   }
1106   auto AddStream = [&](size_t Task) {
1107     return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
1108   };
1109   lto::Config Conf;
1110   Conf.CPU = TOpts.CPU;
1111   Conf.CodeModel = getCodeModel(CGOpts);
1112   Conf.MAttrs = TOpts.Features;
1113   Conf.RelocModel = CGOpts.RelocationModel;
1114   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1115   initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1116   Conf.SampleProfile = std::move(SampleProfile);
1117   Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1118   Conf.DebugPassManager = CGOpts.DebugPassManager;
1119   switch (Action) {
1120   case Backend_EmitNothing:
1121     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1122       return false;
1123     };
1124     break;
1125   case Backend_EmitLL:
1126     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1127       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1128       return false;
1129     };
1130     break;
1131   case Backend_EmitBC:
1132     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1133       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1134       return false;
1135     };
1136     break;
1137   default:
1138     Conf.CGFileType = getCodeGenFileType(Action);
1139     break;
1140   }
1141   if (Error E = thinBackend(
1142           Conf, 0, AddStream, *M, *CombinedIndex, ImportList,
1143           ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1144     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1145       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1146     });
1147   }
1148 }
1149 
1150 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1151                               const HeaderSearchOptions &HeaderOpts,
1152                               const CodeGenOptions &CGOpts,
1153                               const clang::TargetOptions &TOpts,
1154                               const LangOptions &LOpts,
1155                               const llvm::DataLayout &TDesc, Module *M,
1156                               BackendAction Action,
1157                               std::unique_ptr<raw_pwrite_stream> OS) {
1158   std::unique_ptr<llvm::Module> EmptyModule;
1159   if (!CGOpts.ThinLTOIndexFile.empty()) {
1160     // If we are performing a ThinLTO importing compile, load the function index
1161     // into memory and pass it into runThinLTOBackend, which will run the
1162     // function importer and invoke LTO passes.
1163     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1164         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1165                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1166     if (!IndexOrErr) {
1167       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1168                             "Error loading index file '" +
1169                             CGOpts.ThinLTOIndexFile + "': ");
1170       return;
1171     }
1172     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1173     // A null CombinedIndex means we should skip ThinLTO compilation
1174     // (LLVM will optionally ignore empty index files, returning null instead
1175     // of an error).
1176     if (CombinedIndex) {
1177       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1178         runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1179                           LOpts, std::move(OS), CGOpts.SampleProfileFile,
1180                           Action);
1181         return;
1182       }
1183       // Distributed indexing detected that nothing from the module is needed
1184       // for the final linking. So we can skip the compilation. We sill need to
1185       // output an empty object file to make sure that a linker does not fail
1186       // trying to read it. Also for some features, like CFI, we must skip
1187       // the compilation as CombinedIndex does not contain all required
1188       // information.
1189       EmptyModule = llvm::make_unique<llvm::Module>("empty", M->getContext());
1190       EmptyModule->setTargetTriple(M->getTargetTriple());
1191       M = EmptyModule.get();
1192     }
1193   }
1194 
1195   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1196 
1197   if (CGOpts.ExperimentalNewPassManager)
1198     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1199   else
1200     AsmHelper.EmitAssembly(Action, std::move(OS));
1201 
1202   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1203   // DataLayout.
1204   if (AsmHelper.TM) {
1205     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1206     if (DLDesc != TDesc.getStringRepresentation()) {
1207       unsigned DiagID = Diags.getCustomDiagID(
1208           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1209                                     "expected target description '%1'");
1210       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1211     }
1212   }
1213 }
1214 
1215 static const char* getSectionNameForBitcode(const Triple &T) {
1216   switch (T.getObjectFormat()) {
1217   case Triple::MachO:
1218     return "__LLVM,__bitcode";
1219   case Triple::COFF:
1220   case Triple::ELF:
1221   case Triple::Wasm:
1222   case Triple::UnknownObjectFormat:
1223     return ".llvmbc";
1224   }
1225   llvm_unreachable("Unimplemented ObjectFormatType");
1226 }
1227 
1228 static const char* getSectionNameForCommandline(const Triple &T) {
1229   switch (T.getObjectFormat()) {
1230   case Triple::MachO:
1231     return "__LLVM,__cmdline";
1232   case Triple::COFF:
1233   case Triple::ELF:
1234   case Triple::Wasm:
1235   case Triple::UnknownObjectFormat:
1236     return ".llvmcmd";
1237   }
1238   llvm_unreachable("Unimplemented ObjectFormatType");
1239 }
1240 
1241 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1242 // __LLVM,__bitcode section.
1243 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1244                          llvm::MemoryBufferRef Buf) {
1245   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1246     return;
1247 
1248   // Save llvm.compiler.used and remote it.
1249   SmallVector<Constant*, 2> UsedArray;
1250   SmallSet<GlobalValue*, 4> UsedGlobals;
1251   Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1252   GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1253   for (auto *GV : UsedGlobals) {
1254     if (GV->getName() != "llvm.embedded.module" &&
1255         GV->getName() != "llvm.cmdline")
1256       UsedArray.push_back(
1257           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1258   }
1259   if (Used)
1260     Used->eraseFromParent();
1261 
1262   // Embed the bitcode for the llvm module.
1263   std::string Data;
1264   ArrayRef<uint8_t> ModuleData;
1265   Triple T(M->getTargetTriple());
1266   // Create a constant that contains the bitcode.
1267   // In case of embedding a marker, ignore the input Buf and use the empty
1268   // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1269   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1270     if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1271                    (const unsigned char *)Buf.getBufferEnd())) {
1272       // If the input is LLVM Assembly, bitcode is produced by serializing
1273       // the module. Use-lists order need to be perserved in this case.
1274       llvm::raw_string_ostream OS(Data);
1275       llvm::WriteBitcodeToFile(*M, OS, /* ShouldPreserveUseListOrder */ true);
1276       ModuleData =
1277           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1278     } else
1279       // If the input is LLVM bitcode, write the input byte stream directly.
1280       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1281                                      Buf.getBufferSize());
1282   }
1283   llvm::Constant *ModuleConstant =
1284       llvm::ConstantDataArray::get(M->getContext(), ModuleData);
1285   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1286       *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
1287       ModuleConstant);
1288   GV->setSection(getSectionNameForBitcode(T));
1289   UsedArray.push_back(
1290       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1291   if (llvm::GlobalVariable *Old =
1292           M->getGlobalVariable("llvm.embedded.module", true)) {
1293     assert(Old->hasOneUse() &&
1294            "llvm.embedded.module can only be used once in llvm.compiler.used");
1295     GV->takeName(Old);
1296     Old->eraseFromParent();
1297   } else {
1298     GV->setName("llvm.embedded.module");
1299   }
1300 
1301   // Skip if only bitcode needs to be embedded.
1302   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1303     // Embed command-line options.
1304     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
1305                               CGOpts.CmdArgs.size());
1306     llvm::Constant *CmdConstant =
1307       llvm::ConstantDataArray::get(M->getContext(), CmdData);
1308     GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1309                                   llvm::GlobalValue::PrivateLinkage,
1310                                   CmdConstant);
1311     GV->setSection(getSectionNameForCommandline(T));
1312     UsedArray.push_back(
1313         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1314     if (llvm::GlobalVariable *Old =
1315             M->getGlobalVariable("llvm.cmdline", true)) {
1316       assert(Old->hasOneUse() &&
1317              "llvm.cmdline can only be used once in llvm.compiler.used");
1318       GV->takeName(Old);
1319       Old->eraseFromParent();
1320     } else {
1321       GV->setName("llvm.cmdline");
1322     }
1323   }
1324 
1325   if (UsedArray.empty())
1326     return;
1327 
1328   // Recreate llvm.compiler.used.
1329   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1330   auto *NewUsed = new GlobalVariable(
1331       *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1332       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1333   NewUsed->setSection("llvm.metadata");
1334 }
1335