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