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