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