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) {
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            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
800                llvm::Triple::Apple);
801       if (EmitLTOSummary && !TheModule->getModuleFlag("ThinLTO"))
802         TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
803 
804       PerModulePasses.add(
805           createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
806                                   EmitLTOSummary));
807     }
808     break;
809 
810   case Backend_EmitLL:
811     PerModulePasses.add(
812         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
813     break;
814 
815   default:
816     if (!CodeGenOpts.SplitDwarfFile.empty()) {
817       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfFile);
818       if (!DwoOS)
819         return;
820     }
821     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
822                        DwoOS ? &DwoOS->os() : nullptr))
823       return;
824   }
825 
826   // Before executing passes, print the final values of the LLVM options.
827   cl::PrintOptionValues();
828 
829   // Run passes. For now we do all passes at once, but eventually we
830   // would like to have the option of streaming code generation.
831 
832   {
833     PrettyStackTraceString CrashInfo("Per-function optimization");
834 
835     PerFunctionPasses.doInitialization();
836     for (Function &F : *TheModule)
837       if (!F.isDeclaration())
838         PerFunctionPasses.run(F);
839     PerFunctionPasses.doFinalization();
840   }
841 
842   {
843     PrettyStackTraceString CrashInfo("Per-module optimization passes");
844     PerModulePasses.run(*TheModule);
845   }
846 
847   {
848     PrettyStackTraceString CrashInfo("Code generation");
849     CodeGenPasses.run(*TheModule);
850   }
851 
852   if (ThinLinkOS)
853     ThinLinkOS->keep();
854   if (DwoOS)
855     DwoOS->keep();
856 }
857 
858 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
859   switch (Opts.OptimizationLevel) {
860   default:
861     llvm_unreachable("Invalid optimization level!");
862 
863   case 1:
864     return PassBuilder::O1;
865 
866   case 2:
867     switch (Opts.OptimizeSize) {
868     default:
869       llvm_unreachable("Invalid optimization level for size!");
870 
871     case 0:
872       return PassBuilder::O2;
873 
874     case 1:
875       return PassBuilder::Os;
876 
877     case 2:
878       return PassBuilder::Oz;
879     }
880 
881   case 3:
882     return PassBuilder::O3;
883   }
884 }
885 
886 /// A clean version of `EmitAssembly` that uses the new pass manager.
887 ///
888 /// Not all features are currently supported in this system, but where
889 /// necessary it falls back to the legacy pass manager to at least provide
890 /// basic functionality.
891 ///
892 /// This API is planned to have its functionality finished and then to replace
893 /// `EmitAssembly` at some point in the future when the default switches.
894 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
895     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
896   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
897   setCommandLineOpts(CodeGenOpts);
898 
899   // The new pass manager always makes a target machine available to passes
900   // during construction.
901   CreateTargetMachine(/*MustCreateTM*/ true);
902   if (!TM)
903     // This will already be diagnosed, just bail.
904     return;
905   TheModule->setDataLayout(TM->createDataLayout());
906 
907   Optional<PGOOptions> PGOOpt;
908 
909   if (CodeGenOpts.hasProfileIRInstr())
910     // -fprofile-generate.
911     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
912                             ? DefaultProfileGenName
913                             : CodeGenOpts.InstrProfileOutput,
914                         "", "", true, CodeGenOpts.DebugInfoForProfiling);
915   else if (CodeGenOpts.hasProfileIRUse())
916     // -fprofile-use.
917     PGOOpt = PGOOptions("", CodeGenOpts.ProfileInstrumentUsePath, "", false,
918                         CodeGenOpts.DebugInfoForProfiling);
919   else if (!CodeGenOpts.SampleProfileFile.empty())
920     // -fprofile-sample-use
921     PGOOpt = PGOOptions("", "", CodeGenOpts.SampleProfileFile, false,
922                         CodeGenOpts.DebugInfoForProfiling);
923   else if (CodeGenOpts.DebugInfoForProfiling)
924     // -fdebug-info-for-profiling
925     PGOOpt = PGOOptions("", "", "", false, true);
926 
927   PassBuilder PB(TM.get(), PGOOpt);
928 
929   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
930   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
931   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
932   ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
933 
934   // Register the AA manager first so that our version is the one used.
935   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
936 
937   // Register the target library analysis directly and give it a customized
938   // preset TLI.
939   Triple TargetTriple(TheModule->getTargetTriple());
940   std::unique_ptr<TargetLibraryInfoImpl> TLII(
941       createTLII(TargetTriple, CodeGenOpts));
942   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
943   MAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
944 
945   // Register all the basic analyses with the managers.
946   PB.registerModuleAnalyses(MAM);
947   PB.registerCGSCCAnalyses(CGAM);
948   PB.registerFunctionAnalyses(FAM);
949   PB.registerLoopAnalyses(LAM);
950   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
951 
952   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
953 
954   if (!CodeGenOpts.DisableLLVMPasses) {
955     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
956     bool IsLTO = CodeGenOpts.PrepareForLTO;
957 
958     if (CodeGenOpts.OptimizationLevel == 0) {
959       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
960         MPM.addPass(GCOVProfilerPass(*Options));
961 
962       // Build a minimal pipeline based on the semantics required by Clang,
963       // which is just that always inlining occurs.
964       MPM.addPass(AlwaysInlinerPass());
965 
966       // At -O0 we directly run necessary sanitizer passes.
967       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
968         MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
969 
970       // Lastly, add a semantically necessary pass for LTO.
971       if (IsLTO || IsThinLTO)
972         MPM.addPass(NameAnonGlobalPass());
973     } else {
974       // Map our optimization levels into one of the distinct levels used to
975       // configure the pipeline.
976       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
977 
978       // Register callbacks to schedule sanitizer passes at the appropriate part of
979       // the pipeline.
980       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
981         PB.registerScalarOptimizerLateEPCallback(
982             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
983               FPM.addPass(BoundsCheckingPass());
984             });
985       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
986         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
987           MPM.addPass(GCOVProfilerPass(*Options));
988         });
989 
990       if (IsThinLTO) {
991         MPM = PB.buildThinLTOPreLinkDefaultPipeline(
992             Level, CodeGenOpts.DebugPassManager);
993         MPM.addPass(NameAnonGlobalPass());
994       } else if (IsLTO) {
995         MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
996                                                 CodeGenOpts.DebugPassManager);
997         MPM.addPass(NameAnonGlobalPass());
998       } else {
999         MPM = PB.buildPerModuleDefaultPipeline(Level,
1000                                                CodeGenOpts.DebugPassManager);
1001       }
1002     }
1003   }
1004 
1005   // FIXME: We still use the legacy pass manager to do code generation. We
1006   // create that pass manager here and use it as needed below.
1007   legacy::PassManager CodeGenPasses;
1008   bool NeedCodeGen = false;
1009   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1010 
1011   // Append any output we need to the pass manager.
1012   switch (Action) {
1013   case Backend_EmitNothing:
1014     break;
1015 
1016   case Backend_EmitBC:
1017     if (CodeGenOpts.PrepareForThinLTO) {
1018       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1019         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1020         if (!ThinLinkOS)
1021           return;
1022       }
1023       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1024                                                            : nullptr));
1025     } else {
1026       // Emit a module summary by default for Regular LTO except for ld64
1027       // targets
1028       bool EmitLTOSummary =
1029           (CodeGenOpts.PrepareForLTO &&
1030            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1031                llvm::Triple::Apple);
1032       if (EmitLTOSummary && !TheModule->getModuleFlag("ThinLTO"))
1033         TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1034 
1035       MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1036                                     EmitLTOSummary));
1037     }
1038     break;
1039 
1040   case Backend_EmitLL:
1041     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1042     break;
1043 
1044   case Backend_EmitAssembly:
1045   case Backend_EmitMCNull:
1046   case Backend_EmitObj:
1047     NeedCodeGen = true;
1048     CodeGenPasses.add(
1049         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1050     if (!CodeGenOpts.SplitDwarfFile.empty()) {
1051       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfFile);
1052       if (!DwoOS)
1053         return;
1054     }
1055     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1056                        DwoOS ? &DwoOS->os() : nullptr))
1057       // FIXME: Should we handle this error differently?
1058       return;
1059     break;
1060   }
1061 
1062   // Before executing passes, print the final values of the LLVM options.
1063   cl::PrintOptionValues();
1064 
1065   // Now that we have all of the passes ready, run them.
1066   {
1067     PrettyStackTraceString CrashInfo("Optimizer");
1068     MPM.run(*TheModule, MAM);
1069   }
1070 
1071   // Now if needed, run the legacy PM for codegen.
1072   if (NeedCodeGen) {
1073     PrettyStackTraceString CrashInfo("Code generation");
1074     CodeGenPasses.run(*TheModule);
1075   }
1076 
1077   if (ThinLinkOS)
1078     ThinLinkOS->keep();
1079   if (DwoOS)
1080     DwoOS->keep();
1081 }
1082 
1083 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1084   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1085   if (!BMsOrErr)
1086     return BMsOrErr.takeError();
1087 
1088   // The bitcode file may contain multiple modules, we want the one that is
1089   // marked as being the ThinLTO module.
1090   if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1091     return *Bm;
1092 
1093   return make_error<StringError>("Could not find module summary",
1094                                  inconvertibleErrorCode());
1095 }
1096 
1097 BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1098   for (BitcodeModule &BM : BMs) {
1099     Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1100     if (LTOInfo && LTOInfo->IsThinLTO)
1101       return &BM;
1102   }
1103   return nullptr;
1104 }
1105 
1106 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
1107                               const HeaderSearchOptions &HeaderOpts,
1108                               const CodeGenOptions &CGOpts,
1109                               const clang::TargetOptions &TOpts,
1110                               const LangOptions &LOpts,
1111                               std::unique_ptr<raw_pwrite_stream> OS,
1112                               std::string SampleProfile,
1113                               BackendAction Action) {
1114   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1115       ModuleToDefinedGVSummaries;
1116   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1117 
1118   setCommandLineOpts(CGOpts);
1119 
1120   // We can simply import the values mentioned in the combined index, since
1121   // we should only invoke this using the individual indexes written out
1122   // via a WriteIndexesThinBackend.
1123   FunctionImporter::ImportMapTy ImportList;
1124   for (auto &GlobalList : *CombinedIndex) {
1125     // Ignore entries for undefined references.
1126     if (GlobalList.second.SummaryList.empty())
1127       continue;
1128 
1129     auto GUID = GlobalList.first;
1130     assert(GlobalList.second.SummaryList.size() == 1 &&
1131            "Expected individual combined index to have one summary per GUID");
1132     auto &Summary = GlobalList.second.SummaryList[0];
1133     // Skip the summaries for the importing module. These are included to
1134     // e.g. record required linkage changes.
1135     if (Summary->modulePath() == M->getModuleIdentifier())
1136       continue;
1137     // Add an entry to provoke importing by thinBackend.
1138     ImportList[Summary->modulePath()].insert(GUID);
1139   }
1140 
1141   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1142   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1143 
1144   for (auto &I : ImportList) {
1145     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1146         llvm::MemoryBuffer::getFile(I.first());
1147     if (!MBOrErr) {
1148       errs() << "Error loading imported file '" << I.first()
1149              << "': " << MBOrErr.getError().message() << "\n";
1150       return;
1151     }
1152 
1153     Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1154     if (!BMOrErr) {
1155       handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1156         errs() << "Error loading imported file '" << I.first()
1157                << "': " << EIB.message() << '\n';
1158       });
1159       return;
1160     }
1161     ModuleMap.insert({I.first(), *BMOrErr});
1162 
1163     OwnedImports.push_back(std::move(*MBOrErr));
1164   }
1165   auto AddStream = [&](size_t Task) {
1166     return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
1167   };
1168   lto::Config Conf;
1169   if (CGOpts.SaveTempsFilePrefix != "") {
1170     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1171                                     /* UseInputModulePath */ false)) {
1172       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1173         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1174                << '\n';
1175       });
1176     }
1177   }
1178   Conf.CPU = TOpts.CPU;
1179   Conf.CodeModel = getCodeModel(CGOpts);
1180   Conf.MAttrs = TOpts.Features;
1181   Conf.RelocModel = CGOpts.RelocationModel;
1182   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1183   initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1184   Conf.SampleProfile = std::move(SampleProfile);
1185   Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1186   Conf.DebugPassManager = CGOpts.DebugPassManager;
1187   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1188   Conf.RemarksFilename = CGOpts.OptRecordFile;
1189   Conf.DwoPath = CGOpts.SplitDwarfFile;
1190   switch (Action) {
1191   case Backend_EmitNothing:
1192     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1193       return false;
1194     };
1195     break;
1196   case Backend_EmitLL:
1197     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1198       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1199       return false;
1200     };
1201     break;
1202   case Backend_EmitBC:
1203     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1204       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1205       return false;
1206     };
1207     break;
1208   default:
1209     Conf.CGFileType = getCodeGenFileType(Action);
1210     break;
1211   }
1212   if (Error E = thinBackend(
1213           Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1214           ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1215     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1216       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1217     });
1218   }
1219 }
1220 
1221 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1222                               const HeaderSearchOptions &HeaderOpts,
1223                               const CodeGenOptions &CGOpts,
1224                               const clang::TargetOptions &TOpts,
1225                               const LangOptions &LOpts,
1226                               const llvm::DataLayout &TDesc, Module *M,
1227                               BackendAction Action,
1228                               std::unique_ptr<raw_pwrite_stream> OS) {
1229   std::unique_ptr<llvm::Module> EmptyModule;
1230   if (!CGOpts.ThinLTOIndexFile.empty()) {
1231     // If we are performing a ThinLTO importing compile, load the function index
1232     // into memory and pass it into runThinLTOBackend, which will run the
1233     // function importer and invoke LTO passes.
1234     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1235         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1236                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1237     if (!IndexOrErr) {
1238       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1239                             "Error loading index file '" +
1240                             CGOpts.ThinLTOIndexFile + "': ");
1241       return;
1242     }
1243     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1244     // A null CombinedIndex means we should skip ThinLTO compilation
1245     // (LLVM will optionally ignore empty index files, returning null instead
1246     // of an error).
1247     if (CombinedIndex) {
1248       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1249         runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1250                           LOpts, std::move(OS), CGOpts.SampleProfileFile,
1251                           Action);
1252         return;
1253       }
1254       // Distributed indexing detected that nothing from the module is needed
1255       // for the final linking. So we can skip the compilation. We sill need to
1256       // output an empty object file to make sure that a linker does not fail
1257       // trying to read it. Also for some features, like CFI, we must skip
1258       // the compilation as CombinedIndex does not contain all required
1259       // information.
1260       EmptyModule = llvm::make_unique<llvm::Module>("empty", M->getContext());
1261       EmptyModule->setTargetTriple(M->getTargetTriple());
1262       M = EmptyModule.get();
1263     }
1264   }
1265 
1266   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1267 
1268   if (CGOpts.ExperimentalNewPassManager)
1269     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1270   else
1271     AsmHelper.EmitAssembly(Action, std::move(OS));
1272 
1273   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1274   // DataLayout.
1275   if (AsmHelper.TM) {
1276     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1277     if (DLDesc != TDesc.getStringRepresentation()) {
1278       unsigned DiagID = Diags.getCustomDiagID(
1279           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1280                                     "expected target description '%1'");
1281       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1282     }
1283   }
1284 }
1285 
1286 static const char* getSectionNameForBitcode(const Triple &T) {
1287   switch (T.getObjectFormat()) {
1288   case Triple::MachO:
1289     return "__LLVM,__bitcode";
1290   case Triple::COFF:
1291   case Triple::ELF:
1292   case Triple::Wasm:
1293   case Triple::UnknownObjectFormat:
1294     return ".llvmbc";
1295   }
1296   llvm_unreachable("Unimplemented ObjectFormatType");
1297 }
1298 
1299 static const char* getSectionNameForCommandline(const Triple &T) {
1300   switch (T.getObjectFormat()) {
1301   case Triple::MachO:
1302     return "__LLVM,__cmdline";
1303   case Triple::COFF:
1304   case Triple::ELF:
1305   case Triple::Wasm:
1306   case Triple::UnknownObjectFormat:
1307     return ".llvmcmd";
1308   }
1309   llvm_unreachable("Unimplemented ObjectFormatType");
1310 }
1311 
1312 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1313 // __LLVM,__bitcode section.
1314 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1315                          llvm::MemoryBufferRef Buf) {
1316   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1317     return;
1318 
1319   // Save llvm.compiler.used and remote it.
1320   SmallVector<Constant*, 2> UsedArray;
1321   SmallPtrSet<GlobalValue*, 4> UsedGlobals;
1322   Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1323   GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1324   for (auto *GV : UsedGlobals) {
1325     if (GV->getName() != "llvm.embedded.module" &&
1326         GV->getName() != "llvm.cmdline")
1327       UsedArray.push_back(
1328           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1329   }
1330   if (Used)
1331     Used->eraseFromParent();
1332 
1333   // Embed the bitcode for the llvm module.
1334   std::string Data;
1335   ArrayRef<uint8_t> ModuleData;
1336   Triple T(M->getTargetTriple());
1337   // Create a constant that contains the bitcode.
1338   // In case of embedding a marker, ignore the input Buf and use the empty
1339   // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1340   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1341     if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1342                    (const unsigned char *)Buf.getBufferEnd())) {
1343       // If the input is LLVM Assembly, bitcode is produced by serializing
1344       // the module. Use-lists order need to be perserved in this case.
1345       llvm::raw_string_ostream OS(Data);
1346       llvm::WriteBitcodeToFile(*M, OS, /* ShouldPreserveUseListOrder */ true);
1347       ModuleData =
1348           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1349     } else
1350       // If the input is LLVM bitcode, write the input byte stream directly.
1351       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1352                                      Buf.getBufferSize());
1353   }
1354   llvm::Constant *ModuleConstant =
1355       llvm::ConstantDataArray::get(M->getContext(), ModuleData);
1356   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1357       *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
1358       ModuleConstant);
1359   GV->setSection(getSectionNameForBitcode(T));
1360   UsedArray.push_back(
1361       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1362   if (llvm::GlobalVariable *Old =
1363           M->getGlobalVariable("llvm.embedded.module", true)) {
1364     assert(Old->hasOneUse() &&
1365            "llvm.embedded.module can only be used once in llvm.compiler.used");
1366     GV->takeName(Old);
1367     Old->eraseFromParent();
1368   } else {
1369     GV->setName("llvm.embedded.module");
1370   }
1371 
1372   // Skip if only bitcode needs to be embedded.
1373   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1374     // Embed command-line options.
1375     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
1376                               CGOpts.CmdArgs.size());
1377     llvm::Constant *CmdConstant =
1378       llvm::ConstantDataArray::get(M->getContext(), CmdData);
1379     GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1380                                   llvm::GlobalValue::PrivateLinkage,
1381                                   CmdConstant);
1382     GV->setSection(getSectionNameForCommandline(T));
1383     UsedArray.push_back(
1384         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1385     if (llvm::GlobalVariable *Old =
1386             M->getGlobalVariable("llvm.cmdline", true)) {
1387       assert(Old->hasOneUse() &&
1388              "llvm.cmdline can only be used once in llvm.compiler.used");
1389       GV->takeName(Old);
1390       Old->eraseFromParent();
1391     } else {
1392       GV->setName("llvm.cmdline");
1393     }
1394   }
1395 
1396   if (UsedArray.empty())
1397     return;
1398 
1399   // Recreate llvm.compiler.used.
1400   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1401   auto *NewUsed = new GlobalVariable(
1402       *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1403       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1404   NewUsed->setSection("llvm.metadata");
1405 }
1406