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