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