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