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