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