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