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