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.CoroutinesTS)
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));
691   }
692   if (CodeGenOpts.hasProfileIRInstr()) {
693     PMBuilder.EnablePGOInstrGen = true;
694     if (!CodeGenOpts.InstrProfileOutput.empty())
695       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
696     else
697       PMBuilder.PGOInstrGen = DefaultProfileGenName;
698   }
699   if (CodeGenOpts.hasProfileIRUse())
700     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
701 
702   if (!CodeGenOpts.SampleProfileFile.empty())
703     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
704 
705   PMBuilder.populateFunctionPassManager(FPM);
706   PMBuilder.populateModulePassManager(MPM);
707 }
708 
709 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
710   SmallVector<const char *, 16> BackendArgs;
711   BackendArgs.push_back("clang"); // Fake program name.
712   if (!CodeGenOpts.DebugPass.empty()) {
713     BackendArgs.push_back("-debug-pass");
714     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
715   }
716   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
717     BackendArgs.push_back("-limit-float-precision");
718     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
719   }
720   BackendArgs.push_back(nullptr);
721   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
722                                     BackendArgs.data());
723 }
724 
725 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
726   // Create the TargetMachine for generating code.
727   std::string Error;
728   std::string Triple = TheModule->getTargetTriple();
729   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
730   if (!TheTarget) {
731     if (MustCreateTM)
732       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
733     return;
734   }
735 
736   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
737   std::string FeaturesStr =
738       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
739   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
740   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
741 
742   llvm::TargetOptions Options;
743   initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
744   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
745                                           Options, RM, CM, OptLevel));
746 }
747 
748 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
749                                        BackendAction Action,
750                                        raw_pwrite_stream &OS,
751                                        raw_pwrite_stream *DwoOS) {
752   // Add LibraryInfo.
753   llvm::Triple TargetTriple(TheModule->getTargetTriple());
754   std::unique_ptr<TargetLibraryInfoImpl> TLII(
755       createTLII(TargetTriple, CodeGenOpts));
756   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
757 
758   // Normal mode, emit a .s or .o file by running the code generator. Note,
759   // this also adds codegenerator level optimization passes.
760   TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
761 
762   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
763   // "codegen" passes so that it isn't run multiple times when there is
764   // inlining happening.
765   if (CodeGenOpts.OptimizationLevel > 0)
766     CodeGenPasses.add(createObjCARCContractPass());
767 
768   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
769                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
770     Diags.Report(diag::err_fe_unable_to_interface_with_target);
771     return false;
772   }
773 
774   return true;
775 }
776 
777 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
778                                       std::unique_ptr<raw_pwrite_stream> OS) {
779   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
780 
781   setCommandLineOpts(CodeGenOpts);
782 
783   bool UsesCodeGen = (Action != Backend_EmitNothing &&
784                       Action != Backend_EmitBC &&
785                       Action != Backend_EmitLL);
786   CreateTargetMachine(UsesCodeGen);
787 
788   if (UsesCodeGen && !TM)
789     return;
790   if (TM)
791     TheModule->setDataLayout(TM->createDataLayout());
792 
793   legacy::PassManager PerModulePasses;
794   PerModulePasses.add(
795       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
796 
797   legacy::FunctionPassManager PerFunctionPasses(TheModule);
798   PerFunctionPasses.add(
799       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
800 
801   CreatePasses(PerModulePasses, PerFunctionPasses);
802 
803   legacy::PassManager CodeGenPasses;
804   CodeGenPasses.add(
805       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
806 
807   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
808 
809   switch (Action) {
810   case Backend_EmitNothing:
811     break;
812 
813   case Backend_EmitBC:
814     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
815       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
816         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
817         if (!ThinLinkOS)
818           return;
819       }
820       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
821                                CodeGenOpts.EnableSplitLTOUnit);
822       PerModulePasses.add(createWriteThinLTOBitcodePass(
823           *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
824     } else {
825       // Emit a module summary by default for Regular LTO except for ld64
826       // targets
827       bool EmitLTOSummary =
828           (CodeGenOpts.PrepareForLTO &&
829            !CodeGenOpts.DisableLLVMPasses &&
830            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
831                llvm::Triple::Apple);
832       if (EmitLTOSummary) {
833         if (!TheModule->getModuleFlag("ThinLTO"))
834           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
835         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
836                                  CodeGenOpts.EnableSplitLTOUnit);
837       }
838 
839       PerModulePasses.add(createBitcodeWriterPass(
840           *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
841     }
842     break;
843 
844   case Backend_EmitLL:
845     PerModulePasses.add(
846         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
847     break;
848 
849   default:
850     if (!CodeGenOpts.SplitDwarfFile.empty() &&
851         (CodeGenOpts.getSplitDwarfMode() == CodeGenOptions::SplitFileFission)) {
852       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfFile);
853       if (!DwoOS)
854         return;
855     }
856     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
857                        DwoOS ? &DwoOS->os() : nullptr))
858       return;
859   }
860 
861   // Before executing passes, print the final values of the LLVM options.
862   cl::PrintOptionValues();
863 
864   // Run passes. For now we do all passes at once, but eventually we
865   // would like to have the option of streaming code generation.
866 
867   {
868     PrettyStackTraceString CrashInfo("Per-function optimization");
869 
870     PerFunctionPasses.doInitialization();
871     for (Function &F : *TheModule)
872       if (!F.isDeclaration())
873         PerFunctionPasses.run(F);
874     PerFunctionPasses.doFinalization();
875   }
876 
877   {
878     PrettyStackTraceString CrashInfo("Per-module optimization passes");
879     PerModulePasses.run(*TheModule);
880   }
881 
882   {
883     PrettyStackTraceString CrashInfo("Code generation");
884     CodeGenPasses.run(*TheModule);
885   }
886 
887   if (ThinLinkOS)
888     ThinLinkOS->keep();
889   if (DwoOS)
890     DwoOS->keep();
891 }
892 
893 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
894   switch (Opts.OptimizationLevel) {
895   default:
896     llvm_unreachable("Invalid optimization level!");
897 
898   case 1:
899     return PassBuilder::O1;
900 
901   case 2:
902     switch (Opts.OptimizeSize) {
903     default:
904       llvm_unreachable("Invalid optimization level for size!");
905 
906     case 0:
907       return PassBuilder::O2;
908 
909     case 1:
910       return PassBuilder::Os;
911 
912     case 2:
913       return PassBuilder::Oz;
914     }
915 
916   case 3:
917     return PassBuilder::O3;
918   }
919 }
920 
921 void addSanitizersAtO0(ModulePassManager &MPM, const Triple &TargetTriple,
922                        const LangOptions &LangOpts,
923                        const CodeGenOptions &CodeGenOpts) {
924   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
925     MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
926     bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
927     MPM.addPass(createModuleToFunctionPassAdaptor(
928         AddressSanitizerPass(/*CompileKernel=*/false, Recover,
929                              CodeGenOpts.SanitizeAddressUseAfterScope)));
930     bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
931     MPM.addPass(ModuleAddressSanitizerPass(
932         /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
933         CodeGenOpts.SanitizeAddressUseOdrIndicator));
934   }
935 }
936 
937 /// A clean version of `EmitAssembly` that uses the new pass manager.
938 ///
939 /// Not all features are currently supported in this system, but where
940 /// necessary it falls back to the legacy pass manager to at least provide
941 /// basic functionality.
942 ///
943 /// This API is planned to have its functionality finished and then to replace
944 /// `EmitAssembly` at some point in the future when the default switches.
945 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
946     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
947   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
948   setCommandLineOpts(CodeGenOpts);
949 
950   // The new pass manager always makes a target machine available to passes
951   // during construction.
952   CreateTargetMachine(/*MustCreateTM*/ true);
953   if (!TM)
954     // This will already be diagnosed, just bail.
955     return;
956   TheModule->setDataLayout(TM->createDataLayout());
957 
958   Optional<PGOOptions> PGOOpt;
959 
960   if (CodeGenOpts.hasProfileIRInstr())
961     // -fprofile-generate.
962     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
963                             ? DefaultProfileGenName
964                             : CodeGenOpts.InstrProfileOutput,
965                         "", "", "", true,
966                         CodeGenOpts.DebugInfoForProfiling);
967   else if (CodeGenOpts.hasProfileIRUse())
968     // -fprofile-use.
969     PGOOpt = PGOOptions("", CodeGenOpts.ProfileInstrumentUsePath, "",
970                         CodeGenOpts.ProfileRemappingFile, false,
971                         CodeGenOpts.DebugInfoForProfiling);
972   else if (!CodeGenOpts.SampleProfileFile.empty())
973     // -fprofile-sample-use
974     PGOOpt = PGOOptions("", "", CodeGenOpts.SampleProfileFile,
975                         CodeGenOpts.ProfileRemappingFile, false,
976                         CodeGenOpts.DebugInfoForProfiling);
977   else if (CodeGenOpts.DebugInfoForProfiling)
978     // -fdebug-info-for-profiling
979     PGOOpt = PGOOptions("", "", "", "", false, true);
980 
981   PassBuilder PB(TM.get(), PGOOpt);
982 
983   // Attempt to load pass plugins and register their callbacks with PB.
984   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
985     auto PassPlugin = PassPlugin::Load(PluginFN);
986     if (PassPlugin) {
987       PassPlugin->registerPassBuilderCallbacks(PB);
988     } else {
989       Diags.Report(diag::err_fe_unable_to_load_plugin)
990           << PluginFN << toString(PassPlugin.takeError());
991     }
992   }
993 
994   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
995   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
996   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
997   ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
998 
999   // Register the AA manager first so that our version is the one used.
1000   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1001 
1002   // Register the target library analysis directly and give it a customized
1003   // preset TLI.
1004   Triple TargetTriple(TheModule->getTargetTriple());
1005   std::unique_ptr<TargetLibraryInfoImpl> TLII(
1006       createTLII(TargetTriple, CodeGenOpts));
1007   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1008   MAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1009 
1010   // Register all the basic analyses with the managers.
1011   PB.registerModuleAnalyses(MAM);
1012   PB.registerCGSCCAnalyses(CGAM);
1013   PB.registerFunctionAnalyses(FAM);
1014   PB.registerLoopAnalyses(LAM);
1015   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1016 
1017   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
1018 
1019   if (!CodeGenOpts.DisableLLVMPasses) {
1020     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
1021     bool IsLTO = CodeGenOpts.PrepareForLTO;
1022 
1023     if (CodeGenOpts.OptimizationLevel == 0) {
1024       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1025         MPM.addPass(GCOVProfilerPass(*Options));
1026 
1027       // Build a minimal pipeline based on the semantics required by Clang,
1028       // which is just that always inlining occurs.
1029       MPM.addPass(AlwaysInlinerPass());
1030 
1031       // At -O0 we directly run necessary sanitizer passes.
1032       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1033         MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1034 
1035       // Lastly, add semantically necessary passes for LTO.
1036       if (IsLTO || IsThinLTO) {
1037         MPM.addPass(CanonicalizeAliasesPass());
1038         MPM.addPass(NameAnonGlobalPass());
1039       }
1040     } else {
1041       // Map our optimization levels into one of the distinct levels used to
1042       // configure the pipeline.
1043       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1044 
1045       // Register callbacks to schedule sanitizer passes at the appropriate part of
1046       // the pipeline.
1047       // FIXME: either handle asan/the remaining sanitizers or error out
1048       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1049         PB.registerScalarOptimizerLateEPCallback(
1050             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1051               FPM.addPass(BoundsCheckingPass());
1052             });
1053       if (LangOpts.Sanitize.has(SanitizerKind::Memory))
1054         PB.registerOptimizerLastEPCallback(
1055             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1056               FPM.addPass(MemorySanitizerPass({}));
1057             });
1058       if (LangOpts.Sanitize.has(SanitizerKind::Thread))
1059         PB.registerOptimizerLastEPCallback(
1060             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1061               FPM.addPass(ThreadSanitizerPass());
1062             });
1063       if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1064         PB.registerPipelineStartEPCallback([&](ModulePassManager &MPM) {
1065           MPM.addPass(
1066               RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1067         });
1068         bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
1069         bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
1070         PB.registerOptimizerLastEPCallback(
1071             [Recover, UseAfterScope](FunctionPassManager &FPM,
1072                                      PassBuilder::OptimizationLevel Level) {
1073               FPM.addPass(AddressSanitizerPass(
1074                   /*CompileKernel=*/false, Recover, UseAfterScope));
1075             });
1076         bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1077         bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1078         PB.registerPipelineStartEPCallback(
1079             [Recover, ModuleUseAfterScope,
1080              UseOdrIndicator](ModulePassManager &MPM) {
1081               MPM.addPass(ModuleAddressSanitizerPass(
1082                   /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
1083                   UseOdrIndicator));
1084             });
1085       }
1086       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1087         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1088           MPM.addPass(GCOVProfilerPass(*Options));
1089         });
1090 
1091       if (IsThinLTO) {
1092         MPM = PB.buildThinLTOPreLinkDefaultPipeline(
1093             Level, CodeGenOpts.DebugPassManager);
1094         MPM.addPass(CanonicalizeAliasesPass());
1095         MPM.addPass(NameAnonGlobalPass());
1096       } else if (IsLTO) {
1097         MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
1098                                                 CodeGenOpts.DebugPassManager);
1099         MPM.addPass(CanonicalizeAliasesPass());
1100         MPM.addPass(NameAnonGlobalPass());
1101       } else {
1102         MPM = PB.buildPerModuleDefaultPipeline(Level,
1103                                                CodeGenOpts.DebugPassManager);
1104       }
1105     }
1106 
1107     if (CodeGenOpts.OptimizationLevel == 0)
1108       addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
1109   }
1110 
1111   // FIXME: We still use the legacy pass manager to do code generation. We
1112   // create that pass manager here and use it as needed below.
1113   legacy::PassManager CodeGenPasses;
1114   bool NeedCodeGen = false;
1115   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1116 
1117   // Append any output we need to the pass manager.
1118   switch (Action) {
1119   case Backend_EmitNothing:
1120     break;
1121 
1122   case Backend_EmitBC:
1123     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1124       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1125         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1126         if (!ThinLinkOS)
1127           return;
1128       }
1129       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1130                                CodeGenOpts.EnableSplitLTOUnit);
1131       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1132                                                            : nullptr));
1133     } else {
1134       // Emit a module summary by default for Regular LTO except for ld64
1135       // targets
1136       bool EmitLTOSummary =
1137           (CodeGenOpts.PrepareForLTO &&
1138            !CodeGenOpts.DisableLLVMPasses &&
1139            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1140                llvm::Triple::Apple);
1141       if (EmitLTOSummary) {
1142         if (!TheModule->getModuleFlag("ThinLTO"))
1143           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1144         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1145                                  CodeGenOpts.EnableSplitLTOUnit);
1146       }
1147       MPM.addPass(
1148           BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1149     }
1150     break;
1151 
1152   case Backend_EmitLL:
1153     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1154     break;
1155 
1156   case Backend_EmitAssembly:
1157   case Backend_EmitMCNull:
1158   case Backend_EmitObj:
1159     NeedCodeGen = true;
1160     CodeGenPasses.add(
1161         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1162     if (!CodeGenOpts.SplitDwarfFile.empty()) {
1163       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfFile);
1164       if (!DwoOS)
1165         return;
1166     }
1167     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1168                        DwoOS ? &DwoOS->os() : nullptr))
1169       // FIXME: Should we handle this error differently?
1170       return;
1171     break;
1172   }
1173 
1174   // Before executing passes, print the final values of the LLVM options.
1175   cl::PrintOptionValues();
1176 
1177   // Now that we have all of the passes ready, run them.
1178   {
1179     PrettyStackTraceString CrashInfo("Optimizer");
1180     MPM.run(*TheModule, MAM);
1181   }
1182 
1183   // Now if needed, run the legacy PM for codegen.
1184   if (NeedCodeGen) {
1185     PrettyStackTraceString CrashInfo("Code generation");
1186     CodeGenPasses.run(*TheModule);
1187   }
1188 
1189   if (ThinLinkOS)
1190     ThinLinkOS->keep();
1191   if (DwoOS)
1192     DwoOS->keep();
1193 }
1194 
1195 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1196   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1197   if (!BMsOrErr)
1198     return BMsOrErr.takeError();
1199 
1200   // The bitcode file may contain multiple modules, we want the one that is
1201   // marked as being the ThinLTO module.
1202   if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1203     return *Bm;
1204 
1205   return make_error<StringError>("Could not find module summary",
1206                                  inconvertibleErrorCode());
1207 }
1208 
1209 BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1210   for (BitcodeModule &BM : BMs) {
1211     Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1212     if (LTOInfo && LTOInfo->IsThinLTO)
1213       return &BM;
1214   }
1215   return nullptr;
1216 }
1217 
1218 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
1219                               const HeaderSearchOptions &HeaderOpts,
1220                               const CodeGenOptions &CGOpts,
1221                               const clang::TargetOptions &TOpts,
1222                               const LangOptions &LOpts,
1223                               std::unique_ptr<raw_pwrite_stream> OS,
1224                               std::string SampleProfile,
1225                               std::string ProfileRemapping,
1226                               BackendAction Action) {
1227   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1228       ModuleToDefinedGVSummaries;
1229   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1230 
1231   setCommandLineOpts(CGOpts);
1232 
1233   // We can simply import the values mentioned in the combined index, since
1234   // we should only invoke this using the individual indexes written out
1235   // via a WriteIndexesThinBackend.
1236   FunctionImporter::ImportMapTy ImportList;
1237   for (auto &GlobalList : *CombinedIndex) {
1238     // Ignore entries for undefined references.
1239     if (GlobalList.second.SummaryList.empty())
1240       continue;
1241 
1242     auto GUID = GlobalList.first;
1243     for (auto &Summary : GlobalList.second.SummaryList) {
1244       // Skip the summaries for the importing module. These are included to
1245       // e.g. record required linkage changes.
1246       if (Summary->modulePath() == M->getModuleIdentifier())
1247         continue;
1248       // Add an entry to provoke importing by thinBackend.
1249       ImportList[Summary->modulePath()].insert(GUID);
1250     }
1251   }
1252 
1253   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1254   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1255 
1256   for (auto &I : ImportList) {
1257     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1258         llvm::MemoryBuffer::getFile(I.first());
1259     if (!MBOrErr) {
1260       errs() << "Error loading imported file '" << I.first()
1261              << "': " << MBOrErr.getError().message() << "\n";
1262       return;
1263     }
1264 
1265     Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1266     if (!BMOrErr) {
1267       handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1268         errs() << "Error loading imported file '" << I.first()
1269                << "': " << EIB.message() << '\n';
1270       });
1271       return;
1272     }
1273     ModuleMap.insert({I.first(), *BMOrErr});
1274 
1275     OwnedImports.push_back(std::move(*MBOrErr));
1276   }
1277   auto AddStream = [&](size_t Task) {
1278     return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
1279   };
1280   lto::Config Conf;
1281   if (CGOpts.SaveTempsFilePrefix != "") {
1282     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1283                                     /* UseInputModulePath */ false)) {
1284       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1285         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1286                << '\n';
1287       });
1288     }
1289   }
1290   Conf.CPU = TOpts.CPU;
1291   Conf.CodeModel = getCodeModel(CGOpts);
1292   Conf.MAttrs = TOpts.Features;
1293   Conf.RelocModel = CGOpts.RelocationModel;
1294   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1295   initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1296   Conf.SampleProfile = std::move(SampleProfile);
1297   Conf.ProfileRemapping = std::move(ProfileRemapping);
1298   Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1299   Conf.DebugPassManager = CGOpts.DebugPassManager;
1300   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1301   Conf.RemarksFilename = CGOpts.OptRecordFile;
1302   Conf.DwoPath = CGOpts.SplitDwarfFile;
1303   switch (Action) {
1304   case Backend_EmitNothing:
1305     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1306       return false;
1307     };
1308     break;
1309   case Backend_EmitLL:
1310     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1311       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1312       return false;
1313     };
1314     break;
1315   case Backend_EmitBC:
1316     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1317       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1318       return false;
1319     };
1320     break;
1321   default:
1322     Conf.CGFileType = getCodeGenFileType(Action);
1323     break;
1324   }
1325   if (Error E = thinBackend(
1326           Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1327           ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1328     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1329       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1330     });
1331   }
1332 }
1333 
1334 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1335                               const HeaderSearchOptions &HeaderOpts,
1336                               const CodeGenOptions &CGOpts,
1337                               const clang::TargetOptions &TOpts,
1338                               const LangOptions &LOpts,
1339                               const llvm::DataLayout &TDesc, Module *M,
1340                               BackendAction Action,
1341                               std::unique_ptr<raw_pwrite_stream> OS) {
1342   std::unique_ptr<llvm::Module> EmptyModule;
1343   if (!CGOpts.ThinLTOIndexFile.empty()) {
1344     // If we are performing a ThinLTO importing compile, load the function index
1345     // into memory and pass it into runThinLTOBackend, which will run the
1346     // function importer and invoke LTO passes.
1347     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1348         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1349                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1350     if (!IndexOrErr) {
1351       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1352                             "Error loading index file '" +
1353                             CGOpts.ThinLTOIndexFile + "': ");
1354       return;
1355     }
1356     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1357     // A null CombinedIndex means we should skip ThinLTO compilation
1358     // (LLVM will optionally ignore empty index files, returning null instead
1359     // of an error).
1360     if (CombinedIndex) {
1361       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1362         runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1363                           LOpts, std::move(OS), CGOpts.SampleProfileFile,
1364                           CGOpts.ProfileRemappingFile, Action);
1365         return;
1366       }
1367       // Distributed indexing detected that nothing from the module is needed
1368       // for the final linking. So we can skip the compilation. We sill need to
1369       // output an empty object file to make sure that a linker does not fail
1370       // trying to read it. Also for some features, like CFI, we must skip
1371       // the compilation as CombinedIndex does not contain all required
1372       // information.
1373       EmptyModule = llvm::make_unique<llvm::Module>("empty", M->getContext());
1374       EmptyModule->setTargetTriple(M->getTargetTriple());
1375       M = EmptyModule.get();
1376     }
1377   }
1378 
1379   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1380 
1381   if (CGOpts.ExperimentalNewPassManager)
1382     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1383   else
1384     AsmHelper.EmitAssembly(Action, std::move(OS));
1385 
1386   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1387   // DataLayout.
1388   if (AsmHelper.TM) {
1389     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1390     if (DLDesc != TDesc.getStringRepresentation()) {
1391       unsigned DiagID = Diags.getCustomDiagID(
1392           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1393                                     "expected target description '%1'");
1394       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1395     }
1396   }
1397 }
1398 
1399 static const char* getSectionNameForBitcode(const Triple &T) {
1400   switch (T.getObjectFormat()) {
1401   case Triple::MachO:
1402     return "__LLVM,__bitcode";
1403   case Triple::COFF:
1404   case Triple::ELF:
1405   case Triple::Wasm:
1406   case Triple::UnknownObjectFormat:
1407     return ".llvmbc";
1408   }
1409   llvm_unreachable("Unimplemented ObjectFormatType");
1410 }
1411 
1412 static const char* getSectionNameForCommandline(const Triple &T) {
1413   switch (T.getObjectFormat()) {
1414   case Triple::MachO:
1415     return "__LLVM,__cmdline";
1416   case Triple::COFF:
1417   case Triple::ELF:
1418   case Triple::Wasm:
1419   case Triple::UnknownObjectFormat:
1420     return ".llvmcmd";
1421   }
1422   llvm_unreachable("Unimplemented ObjectFormatType");
1423 }
1424 
1425 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1426 // __LLVM,__bitcode section.
1427 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1428                          llvm::MemoryBufferRef Buf) {
1429   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1430     return;
1431 
1432   // Save llvm.compiler.used and remote it.
1433   SmallVector<Constant*, 2> UsedArray;
1434   SmallPtrSet<GlobalValue*, 4> UsedGlobals;
1435   Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1436   GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1437   for (auto *GV : UsedGlobals) {
1438     if (GV->getName() != "llvm.embedded.module" &&
1439         GV->getName() != "llvm.cmdline")
1440       UsedArray.push_back(
1441           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1442   }
1443   if (Used)
1444     Used->eraseFromParent();
1445 
1446   // Embed the bitcode for the llvm module.
1447   std::string Data;
1448   ArrayRef<uint8_t> ModuleData;
1449   Triple T(M->getTargetTriple());
1450   // Create a constant that contains the bitcode.
1451   // In case of embedding a marker, ignore the input Buf and use the empty
1452   // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1453   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1454     if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1455                    (const unsigned char *)Buf.getBufferEnd())) {
1456       // If the input is LLVM Assembly, bitcode is produced by serializing
1457       // the module. Use-lists order need to be perserved in this case.
1458       llvm::raw_string_ostream OS(Data);
1459       llvm::WriteBitcodeToFile(*M, OS, /* ShouldPreserveUseListOrder */ true);
1460       ModuleData =
1461           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1462     } else
1463       // If the input is LLVM bitcode, write the input byte stream directly.
1464       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1465                                      Buf.getBufferSize());
1466   }
1467   llvm::Constant *ModuleConstant =
1468       llvm::ConstantDataArray::get(M->getContext(), ModuleData);
1469   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1470       *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
1471       ModuleConstant);
1472   GV->setSection(getSectionNameForBitcode(T));
1473   UsedArray.push_back(
1474       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1475   if (llvm::GlobalVariable *Old =
1476           M->getGlobalVariable("llvm.embedded.module", true)) {
1477     assert(Old->hasOneUse() &&
1478            "llvm.embedded.module can only be used once in llvm.compiler.used");
1479     GV->takeName(Old);
1480     Old->eraseFromParent();
1481   } else {
1482     GV->setName("llvm.embedded.module");
1483   }
1484 
1485   // Skip if only bitcode needs to be embedded.
1486   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1487     // Embed command-line options.
1488     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
1489                               CGOpts.CmdArgs.size());
1490     llvm::Constant *CmdConstant =
1491       llvm::ConstantDataArray::get(M->getContext(), CmdData);
1492     GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1493                                   llvm::GlobalValue::PrivateLinkage,
1494                                   CmdConstant);
1495     GV->setSection(getSectionNameForCommandline(T));
1496     UsedArray.push_back(
1497         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1498     if (llvm::GlobalVariable *Old =
1499             M->getGlobalVariable("llvm.cmdline", true)) {
1500       assert(Old->hasOneUse() &&
1501              "llvm.cmdline can only be used once in llvm.compiler.used");
1502       GV->takeName(Old);
1503       Old->eraseFromParent();
1504     } else {
1505       GV->setName("llvm.cmdline");
1506     }
1507   }
1508 
1509   if (UsedArray.empty())
1510     return;
1511 
1512   // Recreate llvm.compiler.used.
1513   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1514   auto *NewUsed = new GlobalVariable(
1515       *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1516       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1517   NewUsed->setSection("llvm.metadata");
1518 }
1519