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   Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
537   return Options;
538 }
539 
540 static Optional<InstrProfOptions>
541 getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
542                     const LangOptions &LangOpts) {
543   if (!CodeGenOpts.hasProfileClangInstr())
544     return None;
545   InstrProfOptions Options;
546   Options.NoRedZone = CodeGenOpts.DisableRedZone;
547   Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
548 
549   // TODO: Surface the option to emit atomic profile counter increments at
550   // the driver level.
551   Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread);
552   return Options;
553 }
554 
555 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
556                                       legacy::FunctionPassManager &FPM) {
557   // Handle disabling of all LLVM passes, where we want to preserve the
558   // internal module before any optimization.
559   if (CodeGenOpts.DisableLLVMPasses)
560     return;
561 
562   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
563   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
564   // are inserted before PMBuilder ones - they'd get the default-constructed
565   // TLI with an unknown target otherwise.
566   Triple TargetTriple(TheModule->getTargetTriple());
567   std::unique_ptr<TargetLibraryInfoImpl> TLII(
568       createTLII(TargetTriple, CodeGenOpts));
569 
570   // If we reached here with a non-empty index file name, then the index file
571   // was empty and we are not performing ThinLTO backend compilation (used in
572   // testing in a distributed build environment). Drop any the type test
573   // assume sequences inserted for whole program vtables so that codegen doesn't
574   // complain.
575   if (!CodeGenOpts.ThinLTOIndexFile.empty())
576     MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr,
577                                      /*ImportSummary=*/nullptr,
578                                      /*DropTypeTests=*/true));
579 
580   PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
581 
582   // At O0 and O1 we only run the always inliner which is more efficient. At
583   // higher optimization levels we run the normal inliner.
584   if (CodeGenOpts.OptimizationLevel <= 1) {
585     bool InsertLifetimeIntrinsics = ((CodeGenOpts.OptimizationLevel != 0 &&
586                                       !CodeGenOpts.DisableLifetimeMarkers) ||
587                                      LangOpts.Coroutines);
588     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
589   } else {
590     // We do not want to inline hot callsites for SamplePGO module-summary build
591     // because profile annotation will happen again in ThinLTO backend, and we
592     // want the IR of the hot path to match the profile.
593     PMBuilder.Inliner = createFunctionInliningPass(
594         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
595         (!CodeGenOpts.SampleProfileFile.empty() &&
596          CodeGenOpts.PrepareForThinLTO));
597   }
598 
599   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
600   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
601   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
602   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
603 
604   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
605   // Loop interleaving in the loop vectorizer has historically been set to be
606   // enabled when loop unrolling is enabled.
607   PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
608   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
609   PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
610   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
611   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
612 
613   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
614 
615   if (TM)
616     TM->adjustPassManager(PMBuilder);
617 
618   if (CodeGenOpts.DebugInfoForProfiling ||
619       !CodeGenOpts.SampleProfileFile.empty())
620     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
621                            addAddDiscriminatorsPass);
622 
623   // In ObjC ARC mode, add the main ARC optimization passes.
624   if (LangOpts.ObjCAutoRefCount) {
625     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
626                            addObjCARCExpandPass);
627     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
628                            addObjCARCAPElimPass);
629     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
630                            addObjCARCOptPass);
631   }
632 
633   if (LangOpts.Coroutines)
634     addCoroutinePassesToExtensionPoints(PMBuilder);
635 
636   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
637     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
638                            addBoundsCheckingPass);
639     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
640                            addBoundsCheckingPass);
641   }
642 
643   if (CodeGenOpts.SanitizeCoverageType ||
644       CodeGenOpts.SanitizeCoverageIndirectCalls ||
645       CodeGenOpts.SanitizeCoverageTraceCmp) {
646     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
647                            addSanitizerCoveragePass);
648     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
649                            addSanitizerCoveragePass);
650   }
651 
652   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
653     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
654                            addAddressSanitizerPasses);
655     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
656                            addAddressSanitizerPasses);
657   }
658 
659   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
660     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
661                            addKernelAddressSanitizerPasses);
662     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
663                            addKernelAddressSanitizerPasses);
664   }
665 
666   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
667     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
668                            addHWAddressSanitizerPasses);
669     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
670                            addHWAddressSanitizerPasses);
671   }
672 
673   if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
674     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
675                            addKernelHWAddressSanitizerPasses);
676     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
677                            addKernelHWAddressSanitizerPasses);
678   }
679 
680   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
681     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
682                            addMemorySanitizerPass);
683     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
684                            addMemorySanitizerPass);
685   }
686 
687   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
688     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
689                            addKernelMemorySanitizerPass);
690     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
691                            addKernelMemorySanitizerPass);
692   }
693 
694   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
695     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
696                            addThreadSanitizerPass);
697     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
698                            addThreadSanitizerPass);
699   }
700 
701   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
702     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
703                            addDataFlowSanitizerPass);
704     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
705                            addDataFlowSanitizerPass);
706   }
707 
708   if (LangOpts.Sanitize.has(SanitizerKind::MemTag)) {
709     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
710                            addMemTagOptimizationPasses);
711   }
712 
713   // Set up the per-function pass manager.
714   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
715   if (CodeGenOpts.VerifyModule)
716     FPM.add(createVerifierPass());
717 
718   // Set up the per-module pass manager.
719   if (!CodeGenOpts.RewriteMapFiles.empty())
720     addSymbolRewriterPass(CodeGenOpts, &MPM);
721 
722   // Add UniqueInternalLinkageNames Pass which renames internal linkage symbols
723   // with unique names.
724   if (CodeGenOpts.UniqueInternalLinkageNames) {
725     MPM.add(createUniqueInternalLinkageNamesPass());
726   }
727 
728   if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
729     MPM.add(createGCOVProfilerPass(*Options));
730     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
731       MPM.add(createStripSymbolsPass(true));
732   }
733 
734   if (Optional<InstrProfOptions> Options =
735           getInstrProfOptions(CodeGenOpts, LangOpts))
736     MPM.add(createInstrProfilingLegacyPass(*Options, false));
737 
738   bool hasIRInstr = false;
739   if (CodeGenOpts.hasProfileIRInstr()) {
740     PMBuilder.EnablePGOInstrGen = true;
741     hasIRInstr = true;
742   }
743   if (CodeGenOpts.hasProfileCSIRInstr()) {
744     assert(!CodeGenOpts.hasProfileCSIRUse() &&
745            "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
746            "same time");
747     assert(!hasIRInstr &&
748            "Cannot have both ProfileGen pass and CSProfileGen pass at the "
749            "same time");
750     PMBuilder.EnablePGOCSInstrGen = true;
751     hasIRInstr = true;
752   }
753   if (hasIRInstr) {
754     if (!CodeGenOpts.InstrProfileOutput.empty())
755       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
756     else
757       PMBuilder.PGOInstrGen = std::string(DefaultProfileGenName);
758   }
759   if (CodeGenOpts.hasProfileIRUse()) {
760     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
761     PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
762   }
763 
764   if (!CodeGenOpts.SampleProfileFile.empty())
765     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
766 
767   PMBuilder.populateFunctionPassManager(FPM);
768   PMBuilder.populateModulePassManager(MPM);
769 }
770 
771 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
772   SmallVector<const char *, 16> BackendArgs;
773   BackendArgs.push_back("clang"); // Fake program name.
774   if (!CodeGenOpts.DebugPass.empty()) {
775     BackendArgs.push_back("-debug-pass");
776     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
777   }
778   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
779     BackendArgs.push_back("-limit-float-precision");
780     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
781   }
782   BackendArgs.push_back(nullptr);
783   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
784                                     BackendArgs.data());
785 }
786 
787 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
788   // Create the TargetMachine for generating code.
789   std::string Error;
790   std::string Triple = TheModule->getTargetTriple();
791   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
792   if (!TheTarget) {
793     if (MustCreateTM)
794       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
795     return;
796   }
797 
798   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
799   std::string FeaturesStr =
800       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
801   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
802   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
803 
804   llvm::TargetOptions Options;
805   initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
806   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
807                                           Options, RM, CM, OptLevel));
808 }
809 
810 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
811                                        BackendAction Action,
812                                        raw_pwrite_stream &OS,
813                                        raw_pwrite_stream *DwoOS) {
814   // Add LibraryInfo.
815   llvm::Triple TargetTriple(TheModule->getTargetTriple());
816   std::unique_ptr<TargetLibraryInfoImpl> TLII(
817       createTLII(TargetTriple, CodeGenOpts));
818   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
819 
820   // Normal mode, emit a .s or .o file by running the code generator. Note,
821   // this also adds codegenerator level optimization passes.
822   CodeGenFileType CGFT = getCodeGenFileType(Action);
823 
824   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
825   // "codegen" passes so that it isn't run multiple times when there is
826   // inlining happening.
827   if (CodeGenOpts.OptimizationLevel > 0)
828     CodeGenPasses.add(createObjCARCContractPass());
829 
830   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
831                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
832     Diags.Report(diag::err_fe_unable_to_interface_with_target);
833     return false;
834   }
835 
836   return true;
837 }
838 
839 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
840                                       std::unique_ptr<raw_pwrite_stream> OS) {
841   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
842 
843   setCommandLineOpts(CodeGenOpts);
844 
845   bool UsesCodeGen = (Action != Backend_EmitNothing &&
846                       Action != Backend_EmitBC &&
847                       Action != Backend_EmitLL);
848   CreateTargetMachine(UsesCodeGen);
849 
850   if (UsesCodeGen && !TM)
851     return;
852   if (TM)
853     TheModule->setDataLayout(TM->createDataLayout());
854 
855   legacy::PassManager PerModulePasses;
856   PerModulePasses.add(
857       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
858 
859   legacy::FunctionPassManager PerFunctionPasses(TheModule);
860   PerFunctionPasses.add(
861       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
862 
863   CreatePasses(PerModulePasses, PerFunctionPasses);
864 
865   legacy::PassManager CodeGenPasses;
866   CodeGenPasses.add(
867       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
868 
869   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
870 
871   switch (Action) {
872   case Backend_EmitNothing:
873     break;
874 
875   case Backend_EmitBC:
876     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
877       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
878         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
879         if (!ThinLinkOS)
880           return;
881       }
882       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
883                                CodeGenOpts.EnableSplitLTOUnit);
884       PerModulePasses.add(createWriteThinLTOBitcodePass(
885           *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
886     } else {
887       // Emit a module summary by default for Regular LTO except for ld64
888       // targets
889       bool EmitLTOSummary =
890           (CodeGenOpts.PrepareForLTO &&
891            !CodeGenOpts.DisableLLVMPasses &&
892            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
893                llvm::Triple::Apple);
894       if (EmitLTOSummary) {
895         if (!TheModule->getModuleFlag("ThinLTO"))
896           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
897         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
898                                  uint32_t(1));
899       }
900 
901       PerModulePasses.add(createBitcodeWriterPass(
902           *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
903     }
904     break;
905 
906   case Backend_EmitLL:
907     PerModulePasses.add(
908         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
909     break;
910 
911   default:
912     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
913       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
914       if (!DwoOS)
915         return;
916     }
917     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
918                        DwoOS ? &DwoOS->os() : nullptr))
919       return;
920   }
921 
922   // Before executing passes, print the final values of the LLVM options.
923   cl::PrintOptionValues();
924 
925   // Run passes. For now we do all passes at once, but eventually we
926   // would like to have the option of streaming code generation.
927 
928   {
929     PrettyStackTraceString CrashInfo("Per-function optimization");
930     llvm::TimeTraceScope TimeScope("PerFunctionPasses");
931 
932     PerFunctionPasses.doInitialization();
933     for (Function &F : *TheModule)
934       if (!F.isDeclaration())
935         PerFunctionPasses.run(F);
936     PerFunctionPasses.doFinalization();
937   }
938 
939   {
940     PrettyStackTraceString CrashInfo("Per-module optimization passes");
941     llvm::TimeTraceScope TimeScope("PerModulePasses");
942     PerModulePasses.run(*TheModule);
943   }
944 
945   {
946     PrettyStackTraceString CrashInfo("Code generation");
947     llvm::TimeTraceScope TimeScope("CodeGenPasses");
948     CodeGenPasses.run(*TheModule);
949   }
950 
951   if (ThinLinkOS)
952     ThinLinkOS->keep();
953   if (DwoOS)
954     DwoOS->keep();
955 }
956 
957 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
958   switch (Opts.OptimizationLevel) {
959   default:
960     llvm_unreachable("Invalid optimization level!");
961 
962   case 1:
963     return PassBuilder::OptimizationLevel::O1;
964 
965   case 2:
966     switch (Opts.OptimizeSize) {
967     default:
968       llvm_unreachable("Invalid optimization level for size!");
969 
970     case 0:
971       return PassBuilder::OptimizationLevel::O2;
972 
973     case 1:
974       return PassBuilder::OptimizationLevel::Os;
975 
976     case 2:
977       return PassBuilder::OptimizationLevel::Oz;
978     }
979 
980   case 3:
981     return PassBuilder::OptimizationLevel::O3;
982   }
983 }
984 
985 static void addCoroutinePassesAtO0(ModulePassManager &MPM,
986                                    const LangOptions &LangOpts,
987                                    const CodeGenOptions &CodeGenOpts) {
988   if (!LangOpts.Coroutines)
989     return;
990 
991   MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass()));
992 
993   CGSCCPassManager CGPM(CodeGenOpts.DebugPassManager);
994   CGPM.addPass(CoroSplitPass());
995   CGPM.addPass(createCGSCCToFunctionPassAdaptor(CoroElidePass()));
996   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
997 
998   MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
999 }
1000 
1001 static void addSanitizersAtO0(ModulePassManager &MPM,
1002                               const Triple &TargetTriple,
1003                               const LangOptions &LangOpts,
1004                               const CodeGenOptions &CodeGenOpts) {
1005   auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1006     MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1007     bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1008     MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass(
1009         CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope)));
1010     bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1011     MPM.addPass(
1012         ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope,
1013                                    CodeGenOpts.SanitizeAddressUseOdrIndicator));
1014   };
1015 
1016   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1017     ASanPass(SanitizerKind::Address, /*CompileKernel=*/false);
1018   }
1019 
1020   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
1021     ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true);
1022   }
1023 
1024   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1025     bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory);
1026     int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1027     MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
1028     MPM.addPass(createModuleToFunctionPassAdaptor(
1029         MemorySanitizerPass({TrackOrigins, Recover, false})));
1030   }
1031 
1032   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
1033     MPM.addPass(createModuleToFunctionPassAdaptor(
1034         MemorySanitizerPass({0, false, /*Kernel=*/true})));
1035   }
1036 
1037   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1038     MPM.addPass(ThreadSanitizerPass());
1039     MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1040   }
1041 }
1042 
1043 /// A clean version of `EmitAssembly` that uses the new pass manager.
1044 ///
1045 /// Not all features are currently supported in this system, but where
1046 /// necessary it falls back to the legacy pass manager to at least provide
1047 /// basic functionality.
1048 ///
1049 /// This API is planned to have its functionality finished and then to replace
1050 /// `EmitAssembly` at some point in the future when the default switches.
1051 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
1052     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
1053   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
1054   setCommandLineOpts(CodeGenOpts);
1055 
1056   bool RequiresCodeGen = (Action != Backend_EmitNothing &&
1057                           Action != Backend_EmitBC &&
1058                           Action != Backend_EmitLL);
1059   CreateTargetMachine(RequiresCodeGen);
1060 
1061   if (RequiresCodeGen && !TM)
1062     return;
1063   if (TM)
1064     TheModule->setDataLayout(TM->createDataLayout());
1065 
1066   Optional<PGOOptions> PGOOpt;
1067 
1068   if (CodeGenOpts.hasProfileIRInstr())
1069     // -fprofile-generate.
1070     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
1071                             ? std::string(DefaultProfileGenName)
1072                             : CodeGenOpts.InstrProfileOutput,
1073                         "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
1074                         CodeGenOpts.DebugInfoForProfiling);
1075   else if (CodeGenOpts.hasProfileIRUse()) {
1076     // -fprofile-use.
1077     auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
1078                                                     : PGOOptions::NoCSAction;
1079     PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1080                         CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1081                         CSAction, CodeGenOpts.DebugInfoForProfiling);
1082   } else if (!CodeGenOpts.SampleProfileFile.empty())
1083     // -fprofile-sample-use
1084     PGOOpt =
1085         PGOOptions(CodeGenOpts.SampleProfileFile, "",
1086                    CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse,
1087                    PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling);
1088   else if (CodeGenOpts.DebugInfoForProfiling)
1089     // -fdebug-info-for-profiling
1090     PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1091                         PGOOptions::NoCSAction, true);
1092 
1093   // Check to see if we want to generate a CS profile.
1094   if (CodeGenOpts.hasProfileCSIRInstr()) {
1095     assert(!CodeGenOpts.hasProfileCSIRUse() &&
1096            "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1097            "the same time");
1098     if (PGOOpt.hasValue()) {
1099       assert(PGOOpt->Action != PGOOptions::IRInstr &&
1100              PGOOpt->Action != PGOOptions::SampleUse &&
1101              "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1102              " pass");
1103       PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
1104                                      ? std::string(DefaultProfileGenName)
1105                                      : CodeGenOpts.InstrProfileOutput;
1106       PGOOpt->CSAction = PGOOptions::CSIRInstr;
1107     } else
1108       PGOOpt = PGOOptions("",
1109                           CodeGenOpts.InstrProfileOutput.empty()
1110                               ? std::string(DefaultProfileGenName)
1111                               : CodeGenOpts.InstrProfileOutput,
1112                           "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1113                           CodeGenOpts.DebugInfoForProfiling);
1114   }
1115 
1116   PipelineTuningOptions PTO;
1117   PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
1118   // For historical reasons, loop interleaving is set to mirror setting for loop
1119   // unrolling.
1120   PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1121   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1122   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
1123   PTO.CallGraphProfile = CodeGenOpts.CallGraphProfile;
1124   PTO.Coroutines = LangOpts.Coroutines;
1125 
1126   PassInstrumentationCallbacks PIC;
1127   StandardInstrumentations SI;
1128   SI.registerCallbacks(PIC);
1129   PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
1130 
1131   // Attempt to load pass plugins and register their callbacks with PB.
1132   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1133     auto PassPlugin = PassPlugin::Load(PluginFN);
1134     if (PassPlugin) {
1135       PassPlugin->registerPassBuilderCallbacks(PB);
1136     } else {
1137       Diags.Report(diag::err_fe_unable_to_load_plugin)
1138           << PluginFN << toString(PassPlugin.takeError());
1139     }
1140   }
1141 #define HANDLE_EXTENSION(Ext)                                                  \
1142   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1143 #include "llvm/Support/Extension.def"
1144 
1145   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
1146   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
1147   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
1148   ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
1149 
1150   // Register the AA manager first so that our version is the one used.
1151   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1152 
1153   // Register the target library analysis directly and give it a customized
1154   // preset TLI.
1155   Triple TargetTriple(TheModule->getTargetTriple());
1156   std::unique_ptr<TargetLibraryInfoImpl> TLII(
1157       createTLII(TargetTriple, CodeGenOpts));
1158   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1159 
1160   // Register all the basic analyses with the managers.
1161   PB.registerModuleAnalyses(MAM);
1162   PB.registerCGSCCAnalyses(CGAM);
1163   PB.registerFunctionAnalyses(FAM);
1164   PB.registerLoopAnalyses(LAM);
1165   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1166 
1167   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
1168 
1169   if (!CodeGenOpts.DisableLLVMPasses) {
1170     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
1171     bool IsLTO = CodeGenOpts.PrepareForLTO;
1172 
1173     if (CodeGenOpts.OptimizationLevel == 0) {
1174       // If we reached here with a non-empty index file name, then the index
1175       // file was empty and we are not performing ThinLTO backend compilation
1176       // (used in testing in a distributed build environment). Drop any the type
1177       // test assume sequences inserted for whole program vtables so that
1178       // codegen doesn't complain.
1179       if (!CodeGenOpts.ThinLTOIndexFile.empty())
1180         MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1181                                        /*ImportSummary=*/nullptr,
1182                                        /*DropTypeTests=*/true));
1183       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1184         MPM.addPass(GCOVProfilerPass(*Options));
1185       if (Optional<InstrProfOptions> Options =
1186               getInstrProfOptions(CodeGenOpts, LangOpts))
1187         MPM.addPass(InstrProfiling(*Options, false));
1188 
1189       // Build a minimal pipeline based on the semantics required by Clang,
1190       // which is just that always inlining occurs. Further, disable generating
1191       // lifetime intrinsics to avoid enabling further optimizations during
1192       // code generation.
1193       // However, we need to insert lifetime intrinsics to avoid invalid access
1194       // caused by multithreaded coroutines.
1195       MPM.addPass(
1196           AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/LangOpts.Coroutines));
1197 
1198       // At -O0, we can still do PGO. Add all the requested passes for
1199       // instrumentation PGO, if requested.
1200       if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1201                      PGOOpt->Action == PGOOptions::IRUse))
1202         PB.addPGOInstrPassesForO0(
1203             MPM, CodeGenOpts.DebugPassManager,
1204             /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1205             /* IsCS */ false, PGOOpt->ProfileFile,
1206             PGOOpt->ProfileRemappingFile);
1207 
1208       // At -O0 we directly run necessary sanitizer passes.
1209       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1210         MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1211 
1212       // Add UniqueInternalLinkageNames Pass which renames internal linkage
1213       // symbols with unique names.
1214       if (CodeGenOpts.UniqueInternalLinkageNames) {
1215         MPM.addPass(UniqueInternalLinkageNamesPass());
1216       }
1217 
1218       // Lastly, add semantically necessary passes for LTO.
1219       if (IsLTO || IsThinLTO) {
1220         MPM.addPass(CanonicalizeAliasesPass());
1221         MPM.addPass(NameAnonGlobalPass());
1222       }
1223     } else {
1224       // Map our optimization levels into one of the distinct levels used to
1225       // configure the pipeline.
1226       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1227 
1228       // If we reached here with a non-empty index file name, then the index
1229       // file was empty and we are not performing ThinLTO backend compilation
1230       // (used in testing in a distributed build environment). Drop any the type
1231       // test assume sequences inserted for whole program vtables so that
1232       // codegen doesn't complain.
1233       if (!CodeGenOpts.ThinLTOIndexFile.empty())
1234         PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1235           MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1236                                          /*ImportSummary=*/nullptr,
1237                                          /*DropTypeTests=*/true));
1238         });
1239 
1240       PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1241         MPM.addPass(createModuleToFunctionPassAdaptor(
1242             EntryExitInstrumenterPass(/*PostInlining=*/false)));
1243       });
1244 
1245       // Register callbacks to schedule sanitizer passes at the appropriate part of
1246       // the pipeline.
1247       // FIXME: either handle asan/the remaining sanitizers or error out
1248       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1249         PB.registerScalarOptimizerLateEPCallback(
1250             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1251               FPM.addPass(BoundsCheckingPass());
1252             });
1253       if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1254         int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1255         bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory);
1256         PB.registerPipelineStartEPCallback(
1257             [TrackOrigins, Recover](ModulePassManager &MPM) {
1258               MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
1259             });
1260         PB.registerOptimizerLastEPCallback(
1261             [TrackOrigins, Recover](FunctionPassManager &FPM,
1262                                     PassBuilder::OptimizationLevel Level) {
1263               FPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
1264             });
1265       }
1266       if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1267         PB.registerPipelineStartEPCallback(
1268             [](ModulePassManager &MPM) { MPM.addPass(ThreadSanitizerPass()); });
1269         PB.registerOptimizerLastEPCallback(
1270             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1271               FPM.addPass(ThreadSanitizerPass());
1272             });
1273       }
1274       if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1275         PB.registerPipelineStartEPCallback([&](ModulePassManager &MPM) {
1276           MPM.addPass(
1277               RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1278         });
1279         bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
1280         bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
1281         PB.registerOptimizerLastEPCallback(
1282             [Recover, UseAfterScope](FunctionPassManager &FPM,
1283                                      PassBuilder::OptimizationLevel Level) {
1284               FPM.addPass(AddressSanitizerPass(
1285                   /*CompileKernel=*/false, Recover, UseAfterScope));
1286             });
1287         bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1288         bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1289         PB.registerPipelineStartEPCallback(
1290             [Recover, ModuleUseAfterScope,
1291              UseOdrIndicator](ModulePassManager &MPM) {
1292               MPM.addPass(ModuleAddressSanitizerPass(
1293                   /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
1294                   UseOdrIndicator));
1295             });
1296       }
1297       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1298         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1299           MPM.addPass(GCOVProfilerPass(*Options));
1300         });
1301       if (Optional<InstrProfOptions> Options =
1302               getInstrProfOptions(CodeGenOpts, LangOpts))
1303         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1304           MPM.addPass(InstrProfiling(*Options, false));
1305         });
1306 
1307       // Add UniqueInternalLinkageNames Pass which renames internal linkage
1308       // symbols with unique names.
1309       if (CodeGenOpts.UniqueInternalLinkageNames) {
1310         MPM.addPass(UniqueInternalLinkageNamesPass());
1311       }
1312 
1313       if (IsThinLTO) {
1314         MPM = PB.buildThinLTOPreLinkDefaultPipeline(
1315             Level, CodeGenOpts.DebugPassManager);
1316         MPM.addPass(CanonicalizeAliasesPass());
1317         MPM.addPass(NameAnonGlobalPass());
1318       } else if (IsLTO) {
1319         MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
1320                                                 CodeGenOpts.DebugPassManager);
1321         MPM.addPass(CanonicalizeAliasesPass());
1322         MPM.addPass(NameAnonGlobalPass());
1323       } else {
1324         MPM = PB.buildPerModuleDefaultPipeline(Level,
1325                                                CodeGenOpts.DebugPassManager);
1326       }
1327     }
1328 
1329     if (CodeGenOpts.SanitizeCoverageType ||
1330         CodeGenOpts.SanitizeCoverageIndirectCalls ||
1331         CodeGenOpts.SanitizeCoverageTraceCmp) {
1332       auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1333       MPM.addPass(ModuleSanitizerCoveragePass(
1334           SancovOpts, CodeGenOpts.SanitizeCoverageWhitelistFiles,
1335           CodeGenOpts.SanitizeCoverageBlacklistFiles));
1336     }
1337 
1338     if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1339       bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1340       MPM.addPass(HWAddressSanitizerPass(
1341           /*CompileKernel=*/false, Recover));
1342     }
1343     if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1344       MPM.addPass(HWAddressSanitizerPass(
1345           /*CompileKernel=*/true, /*Recover=*/true));
1346     }
1347 
1348     if (CodeGenOpts.OptimizationLevel > 0 &&
1349         LangOpts.Sanitize.has(SanitizerKind::MemTag)) {
1350       MPM.addPass(StackSafetyGlobalAnnotatorPass());
1351     }
1352 
1353     if (CodeGenOpts.OptimizationLevel == 0) {
1354       addCoroutinePassesAtO0(MPM, LangOpts, CodeGenOpts);
1355       addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
1356     }
1357   }
1358 
1359   // FIXME: We still use the legacy pass manager to do code generation. We
1360   // create that pass manager here and use it as needed below.
1361   legacy::PassManager CodeGenPasses;
1362   bool NeedCodeGen = false;
1363   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1364 
1365   // Append any output we need to the pass manager.
1366   switch (Action) {
1367   case Backend_EmitNothing:
1368     break;
1369 
1370   case Backend_EmitBC:
1371     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1372       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1373         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1374         if (!ThinLinkOS)
1375           return;
1376       }
1377       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1378                                CodeGenOpts.EnableSplitLTOUnit);
1379       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1380                                                            : nullptr));
1381     } else {
1382       // Emit a module summary by default for Regular LTO except for ld64
1383       // targets
1384       bool EmitLTOSummary =
1385           (CodeGenOpts.PrepareForLTO &&
1386            !CodeGenOpts.DisableLLVMPasses &&
1387            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1388                llvm::Triple::Apple);
1389       if (EmitLTOSummary) {
1390         if (!TheModule->getModuleFlag("ThinLTO"))
1391           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1392         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1393                                  uint32_t(1));
1394       }
1395       MPM.addPass(
1396           BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1397     }
1398     break;
1399 
1400   case Backend_EmitLL:
1401     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1402     break;
1403 
1404   case Backend_EmitAssembly:
1405   case Backend_EmitMCNull:
1406   case Backend_EmitObj:
1407     NeedCodeGen = true;
1408     CodeGenPasses.add(
1409         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1410     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1411       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1412       if (!DwoOS)
1413         return;
1414     }
1415     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1416                        DwoOS ? &DwoOS->os() : nullptr))
1417       // FIXME: Should we handle this error differently?
1418       return;
1419     break;
1420   }
1421 
1422   // Before executing passes, print the final values of the LLVM options.
1423   cl::PrintOptionValues();
1424 
1425   // Now that we have all of the passes ready, run them.
1426   {
1427     PrettyStackTraceString CrashInfo("Optimizer");
1428     MPM.run(*TheModule, MAM);
1429   }
1430 
1431   // Now if needed, run the legacy PM for codegen.
1432   if (NeedCodeGen) {
1433     PrettyStackTraceString CrashInfo("Code generation");
1434     CodeGenPasses.run(*TheModule);
1435   }
1436 
1437   if (ThinLinkOS)
1438     ThinLinkOS->keep();
1439   if (DwoOS)
1440     DwoOS->keep();
1441 }
1442 
1443 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1444   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1445   if (!BMsOrErr)
1446     return BMsOrErr.takeError();
1447 
1448   // The bitcode file may contain multiple modules, we want the one that is
1449   // marked as being the ThinLTO module.
1450   if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1451     return *Bm;
1452 
1453   return make_error<StringError>("Could not find module summary",
1454                                  inconvertibleErrorCode());
1455 }
1456 
1457 BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1458   for (BitcodeModule &BM : BMs) {
1459     Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1460     if (LTOInfo && LTOInfo->IsThinLTO)
1461       return &BM;
1462   }
1463   return nullptr;
1464 }
1465 
1466 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
1467                               const HeaderSearchOptions &HeaderOpts,
1468                               const CodeGenOptions &CGOpts,
1469                               const clang::TargetOptions &TOpts,
1470                               const LangOptions &LOpts,
1471                               std::unique_ptr<raw_pwrite_stream> OS,
1472                               std::string SampleProfile,
1473                               std::string ProfileRemapping,
1474                               BackendAction Action) {
1475   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1476       ModuleToDefinedGVSummaries;
1477   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1478 
1479   setCommandLineOpts(CGOpts);
1480 
1481   // We can simply import the values mentioned in the combined index, since
1482   // we should only invoke this using the individual indexes written out
1483   // via a WriteIndexesThinBackend.
1484   FunctionImporter::ImportMapTy ImportList;
1485   for (auto &GlobalList : *CombinedIndex) {
1486     // Ignore entries for undefined references.
1487     if (GlobalList.second.SummaryList.empty())
1488       continue;
1489 
1490     auto GUID = GlobalList.first;
1491     for (auto &Summary : GlobalList.second.SummaryList) {
1492       // Skip the summaries for the importing module. These are included to
1493       // e.g. record required linkage changes.
1494       if (Summary->modulePath() == M->getModuleIdentifier())
1495         continue;
1496       // Add an entry to provoke importing by thinBackend.
1497       ImportList[Summary->modulePath()].insert(GUID);
1498     }
1499   }
1500 
1501   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1502   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1503 
1504   for (auto &I : ImportList) {
1505     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1506         llvm::MemoryBuffer::getFile(I.first());
1507     if (!MBOrErr) {
1508       errs() << "Error loading imported file '" << I.first()
1509              << "': " << MBOrErr.getError().message() << "\n";
1510       return;
1511     }
1512 
1513     Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1514     if (!BMOrErr) {
1515       handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1516         errs() << "Error loading imported file '" << I.first()
1517                << "': " << EIB.message() << '\n';
1518       });
1519       return;
1520     }
1521     ModuleMap.insert({I.first(), *BMOrErr});
1522 
1523     OwnedImports.push_back(std::move(*MBOrErr));
1524   }
1525   auto AddStream = [&](size_t Task) {
1526     return std::make_unique<lto::NativeObjectStream>(std::move(OS));
1527   };
1528   lto::Config Conf;
1529   if (CGOpts.SaveTempsFilePrefix != "") {
1530     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1531                                     /* UseInputModulePath */ false)) {
1532       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1533         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1534                << '\n';
1535       });
1536     }
1537   }
1538   Conf.CPU = TOpts.CPU;
1539   Conf.CodeModel = getCodeModel(CGOpts);
1540   Conf.MAttrs = TOpts.Features;
1541   Conf.RelocModel = CGOpts.RelocationModel;
1542   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1543   Conf.OptLevel = CGOpts.OptimizationLevel;
1544   initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1545   Conf.SampleProfile = std::move(SampleProfile);
1546   Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1547   // For historical reasons, loop interleaving is set to mirror setting for loop
1548   // unrolling.
1549   Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1550   Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1551   Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1552   Conf.PTO.CallGraphProfile = CGOpts.CallGraphProfile;
1553 
1554   // Context sensitive profile.
1555   if (CGOpts.hasProfileCSIRInstr()) {
1556     Conf.RunCSIRInstr = true;
1557     Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1558   } else if (CGOpts.hasProfileCSIRUse()) {
1559     Conf.RunCSIRInstr = false;
1560     Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1561   }
1562 
1563   Conf.ProfileRemapping = std::move(ProfileRemapping);
1564   Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1565   Conf.DebugPassManager = CGOpts.DebugPassManager;
1566   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1567   Conf.RemarksFilename = CGOpts.OptRecordFile;
1568   Conf.RemarksPasses = CGOpts.OptRecordPasses;
1569   Conf.RemarksFormat = CGOpts.OptRecordFormat;
1570   Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1571   Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1572   switch (Action) {
1573   case Backend_EmitNothing:
1574     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1575       return false;
1576     };
1577     break;
1578   case Backend_EmitLL:
1579     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1580       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1581       return false;
1582     };
1583     break;
1584   case Backend_EmitBC:
1585     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1586       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1587       return false;
1588     };
1589     break;
1590   default:
1591     Conf.CGFileType = getCodeGenFileType(Action);
1592     break;
1593   }
1594   if (Error E = thinBackend(
1595           Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1596           ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1597     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1598       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1599     });
1600   }
1601 }
1602 
1603 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1604                               const HeaderSearchOptions &HeaderOpts,
1605                               const CodeGenOptions &CGOpts,
1606                               const clang::TargetOptions &TOpts,
1607                               const LangOptions &LOpts,
1608                               const llvm::DataLayout &TDesc, Module *M,
1609                               BackendAction Action,
1610                               std::unique_ptr<raw_pwrite_stream> OS) {
1611 
1612   llvm::TimeTraceScope TimeScope("Backend");
1613 
1614   std::unique_ptr<llvm::Module> EmptyModule;
1615   if (!CGOpts.ThinLTOIndexFile.empty()) {
1616     // If we are performing a ThinLTO importing compile, load the function index
1617     // into memory and pass it into runThinLTOBackend, which will run the
1618     // function importer and invoke LTO passes.
1619     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1620         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1621                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1622     if (!IndexOrErr) {
1623       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1624                             "Error loading index file '" +
1625                             CGOpts.ThinLTOIndexFile + "': ");
1626       return;
1627     }
1628     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1629     // A null CombinedIndex means we should skip ThinLTO compilation
1630     // (LLVM will optionally ignore empty index files, returning null instead
1631     // of an error).
1632     if (CombinedIndex) {
1633       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1634         runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1635                           LOpts, std::move(OS), CGOpts.SampleProfileFile,
1636                           CGOpts.ProfileRemappingFile, Action);
1637         return;
1638       }
1639       // Distributed indexing detected that nothing from the module is needed
1640       // for the final linking. So we can skip the compilation. We sill need to
1641       // output an empty object file to make sure that a linker does not fail
1642       // trying to read it. Also for some features, like CFI, we must skip
1643       // the compilation as CombinedIndex does not contain all required
1644       // information.
1645       EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1646       EmptyModule->setTargetTriple(M->getTargetTriple());
1647       M = EmptyModule.get();
1648     }
1649   }
1650 
1651   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1652 
1653   if (CGOpts.ExperimentalNewPassManager)
1654     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1655   else
1656     AsmHelper.EmitAssembly(Action, std::move(OS));
1657 
1658   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1659   // DataLayout.
1660   if (AsmHelper.TM) {
1661     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1662     if (DLDesc != TDesc.getStringRepresentation()) {
1663       unsigned DiagID = Diags.getCustomDiagID(
1664           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1665                                     "expected target description '%1'");
1666       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1667     }
1668   }
1669 }
1670 
1671 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1672 // __LLVM,__bitcode section.
1673 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1674                          llvm::MemoryBufferRef Buf) {
1675   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1676     return;
1677   llvm::EmbedBitcodeInModule(
1678       *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1679       CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1680       &CGOpts.CmdArgs);
1681 }
1682