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