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