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