1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/CodeGen/BackendUtil.h"
11 #include "clang/Basic/Diagnostic.h"
12 #include "clang/Basic/LangOptions.h"
13 #include "clang/Basic/TargetOptions.h"
14 #include "clang/Frontend/CodeGenOptions.h"
15 #include "clang/Frontend/FrontendDiagnostic.h"
16 #include "clang/Frontend/Utils.h"
17 #include "clang/Lex/HeaderSearchOptions.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Analysis/TargetLibraryInfo.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/Bitcode/BitcodeReader.h"
25 #include "llvm/Bitcode/BitcodeWriter.h"
26 #include "llvm/Bitcode/BitcodeWriterPass.h"
27 #include "llvm/CodeGen/RegAllocRegistry.h"
28 #include "llvm/CodeGen/SchedulerRegistry.h"
29 #include "llvm/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/Object/ModuleSummaryIndexObjectFile.h"
39 #include "llvm/Passes/PassBuilder.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/Support/PrettyStackTrace.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/Timer.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include "llvm/Target/TargetSubtargetInfo.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/Instrumentation.h"
54 #include "llvm/Transforms/ObjCARC.h"
55 #include "llvm/Transforms/Scalar.h"
56 #include "llvm/Transforms/Scalar/GVN.h"
57 #include "llvm/Transforms/Utils/SymbolRewriter.h"
58 #include <memory>
59 using namespace clang;
60 using namespace llvm;
61 
62 namespace {
63 
64 class EmitAssemblyHelper {
65   DiagnosticsEngine &Diags;
66   const HeaderSearchOptions &HSOpts;
67   const CodeGenOptions &CodeGenOpts;
68   const clang::TargetOptions &TargetOpts;
69   const LangOptions &LangOpts;
70   Module *TheModule;
71 
72   Timer CodeGenerationTime;
73 
74   std::unique_ptr<raw_pwrite_stream> OS;
75 
76 private:
77   TargetIRAnalysis getTargetIRAnalysis() const {
78     if (TM)
79       return TM->getTargetIRAnalysis();
80 
81     return TargetIRAnalysis();
82   }
83 
84   /// Set LLVM command line options passed through -backend-option.
85   void setCommandLineOpts();
86 
87   void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
88 
89   /// Generates the TargetMachine.
90   /// Leaves TM unchanged if it is unable to create the target machine.
91   /// Some of our clang tests specify triples which are not built
92   /// into clang. This is okay because these tests check the generated
93   /// IR, and they require DataLayout which depends on the triple.
94   /// In this case, we allow this method to fail and not report an error.
95   /// When MustCreateTM is used, we print an error if we are unable to load
96   /// the requested target.
97   void CreateTargetMachine(bool MustCreateTM);
98 
99   /// Add passes necessary to emit assembly or LLVM IR.
100   ///
101   /// \return True on success.
102   bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
103                      raw_pwrite_stream &OS);
104 
105 public:
106   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
107                      const HeaderSearchOptions &HeaderSearchOpts,
108                      const CodeGenOptions &CGOpts,
109                      const clang::TargetOptions &TOpts,
110                      const LangOptions &LOpts, Module *M)
111       : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
112         TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
113         CodeGenerationTime("codegen", "Code Generation Time") {}
114 
115   ~EmitAssemblyHelper() {
116     if (CodeGenOpts.DisableFree)
117       BuryPointer(std::move(TM));
118   }
119 
120   std::unique_ptr<TargetMachine> TM;
121 
122   void EmitAssembly(BackendAction Action,
123                     std::unique_ptr<raw_pwrite_stream> OS);
124 
125   void EmitAssemblyWithNewPassManager(BackendAction Action,
126                                       std::unique_ptr<raw_pwrite_stream> OS);
127 };
128 
129 // We need this wrapper to access LangOpts and CGOpts from extension functions
130 // that we add to the PassManagerBuilder.
131 class PassManagerBuilderWrapper : public PassManagerBuilder {
132 public:
133   PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
134                             const LangOptions &LangOpts)
135       : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
136   const CodeGenOptions &getCGOpts() const { return CGOpts; }
137   const LangOptions &getLangOpts() const { return LangOpts; }
138 private:
139   const CodeGenOptions &CGOpts;
140   const LangOptions &LangOpts;
141 };
142 
143 }
144 
145 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
146   if (Builder.OptLevel > 0)
147     PM.add(createObjCARCAPElimPass());
148 }
149 
150 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
151   if (Builder.OptLevel > 0)
152     PM.add(createObjCARCExpandPass());
153 }
154 
155 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
156   if (Builder.OptLevel > 0)
157     PM.add(createObjCARCOptPass());
158 }
159 
160 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
161                                      legacy::PassManagerBase &PM) {
162   PM.add(createAddDiscriminatorsPass());
163 }
164 
165 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
166                                   legacy::PassManagerBase &PM) {
167   PM.add(createBoundsCheckingPass());
168 }
169 
170 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
171                                      legacy::PassManagerBase &PM) {
172   const PassManagerBuilderWrapper &BuilderWrapper =
173       static_cast<const PassManagerBuilderWrapper&>(Builder);
174   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
175   SanitizerCoverageOptions Opts;
176   Opts.CoverageType =
177       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
178   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
179   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
180   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
181   Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
182   Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
183   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
184   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
185   Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
186   PM.add(createSanitizerCoverageModulePass(Opts));
187 }
188 
189 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
190                                       legacy::PassManagerBase &PM) {
191   const PassManagerBuilderWrapper &BuilderWrapper =
192       static_cast<const PassManagerBuilderWrapper&>(Builder);
193   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
194   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
195   bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
196   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
197                                             UseAfterScope));
198   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/false, Recover));
199 }
200 
201 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
202                                             legacy::PassManagerBase &PM) {
203   PM.add(createAddressSanitizerFunctionPass(
204       /*CompileKernel*/ true,
205       /*Recover*/ true, /*UseAfterScope*/ false));
206   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true,
207                                           /*Recover*/true));
208 }
209 
210 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
211                                    legacy::PassManagerBase &PM) {
212   const PassManagerBuilderWrapper &BuilderWrapper =
213       static_cast<const PassManagerBuilderWrapper&>(Builder);
214   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
215   int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
216   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
217   PM.add(createMemorySanitizerPass(TrackOrigins, Recover));
218 
219   // MemorySanitizer inserts complex instrumentation that mostly follows
220   // the logic of the original code, but operates on "shadow" values.
221   // It can benefit from re-running some general purpose optimization passes.
222   if (Builder.OptLevel > 0) {
223     PM.add(createEarlyCSEPass());
224     PM.add(createReassociatePass());
225     PM.add(createLICMPass());
226     PM.add(createGVNPass());
227     PM.add(createInstructionCombiningPass());
228     PM.add(createDeadStoreEliminationPass());
229   }
230 }
231 
232 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
233                                    legacy::PassManagerBase &PM) {
234   PM.add(createThreadSanitizerPass());
235 }
236 
237 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
238                                      legacy::PassManagerBase &PM) {
239   const PassManagerBuilderWrapper &BuilderWrapper =
240       static_cast<const PassManagerBuilderWrapper&>(Builder);
241   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
242   PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
243 }
244 
245 static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
246                                        legacy::PassManagerBase &PM) {
247   const PassManagerBuilderWrapper &BuilderWrapper =
248       static_cast<const PassManagerBuilderWrapper&>(Builder);
249   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
250   EfficiencySanitizerOptions Opts;
251   if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
252     Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
253   else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet))
254     Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet;
255   PM.add(createEfficiencySanitizerPass(Opts));
256 }
257 
258 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
259                                          const CodeGenOptions &CodeGenOpts) {
260   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
261   if (!CodeGenOpts.SimplifyLibCalls)
262     TLII->disableAllFunctions();
263   else {
264     // Disable individual libc/libm calls in TargetLibraryInfo.
265     LibFunc::Func F;
266     for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
267       if (TLII->getLibFunc(FuncName, F))
268         TLII->setUnavailable(F);
269   }
270 
271   switch (CodeGenOpts.getVecLib()) {
272   case CodeGenOptions::Accelerate:
273     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
274     break;
275   case CodeGenOptions::SVML:
276     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
277     break;
278   default:
279     break;
280   }
281   return TLII;
282 }
283 
284 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
285                                   legacy::PassManager *MPM) {
286   llvm::SymbolRewriter::RewriteDescriptorList DL;
287 
288   llvm::SymbolRewriter::RewriteMapParser MapParser;
289   for (const auto &MapFile : Opts.RewriteMapFiles)
290     MapParser.parse(MapFile, &DL);
291 
292   MPM->add(createRewriteSymbolsPass(DL));
293 }
294 
295 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
296                                       legacy::FunctionPassManager &FPM) {
297   // Handle disabling of all LLVM passes, where we want to preserve the
298   // internal module before any optimization.
299   if (CodeGenOpts.DisableLLVMPasses)
300     return;
301 
302   PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
303 
304   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
305   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
306   // are inserted before PMBuilder ones - they'd get the default-constructed
307   // TLI with an unknown target otherwise.
308   Triple TargetTriple(TheModule->getTargetTriple());
309   std::unique_ptr<TargetLibraryInfoImpl> TLII(
310       createTLII(TargetTriple, CodeGenOpts));
311 
312   // At O0 and O1 we only run the always inliner which is more efficient. At
313   // higher optimization levels we run the normal inliner.
314   if (CodeGenOpts.OptimizationLevel <= 1) {
315     bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
316                                      !CodeGenOpts.DisableLifetimeMarkers);
317     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
318   } else {
319     PMBuilder.Inliner = createFunctionInliningPass(
320         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize);
321   }
322 
323   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
324   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
325   PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
326   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
327   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
328 
329   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
330   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
331   PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
332   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
333   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
334 
335   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
336 
337   // Add target-specific passes that need to run as early as possible.
338   if (TM)
339     PMBuilder.addExtension(
340         PassManagerBuilder::EP_EarlyAsPossible,
341         [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {
342           TM->addEarlyAsPossiblePasses(PM);
343         });
344 
345   PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
346                          addAddDiscriminatorsPass);
347 
348   // In ObjC ARC mode, add the main ARC optimization passes.
349   if (LangOpts.ObjCAutoRefCount) {
350     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
351                            addObjCARCExpandPass);
352     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
353                            addObjCARCAPElimPass);
354     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
355                            addObjCARCOptPass);
356   }
357 
358   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
359     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
360                            addBoundsCheckingPass);
361     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
362                            addBoundsCheckingPass);
363   }
364 
365   if (CodeGenOpts.SanitizeCoverageType ||
366       CodeGenOpts.SanitizeCoverageIndirectCalls ||
367       CodeGenOpts.SanitizeCoverageTraceCmp) {
368     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
369                            addSanitizerCoveragePass);
370     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
371                            addSanitizerCoveragePass);
372   }
373 
374   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
375     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
376                            addAddressSanitizerPasses);
377     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
378                            addAddressSanitizerPasses);
379   }
380 
381   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
382     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
383                            addKernelAddressSanitizerPasses);
384     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
385                            addKernelAddressSanitizerPasses);
386   }
387 
388   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
389     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
390                            addMemorySanitizerPass);
391     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
392                            addMemorySanitizerPass);
393   }
394 
395   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
396     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
397                            addThreadSanitizerPass);
398     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
399                            addThreadSanitizerPass);
400   }
401 
402   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
403     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
404                            addDataFlowSanitizerPass);
405     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
406                            addDataFlowSanitizerPass);
407   }
408 
409   if (LangOpts.CoroutinesTS)
410     addCoroutinePassesToExtensionPoints(PMBuilder);
411 
412   if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
413     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
414                            addEfficiencySanitizerPass);
415     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
416                            addEfficiencySanitizerPass);
417   }
418 
419   // Set up the per-function pass manager.
420   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
421   if (CodeGenOpts.VerifyModule)
422     FPM.add(createVerifierPass());
423 
424   // Set up the per-module pass manager.
425   if (!CodeGenOpts.RewriteMapFiles.empty())
426     addSymbolRewriterPass(CodeGenOpts, &MPM);
427 
428   if (!CodeGenOpts.DisableGCov &&
429       (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
430     // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
431     // LLVM's -default-gcov-version flag is set to something invalid.
432     GCOVOptions Options;
433     Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
434     Options.EmitData = CodeGenOpts.EmitGcovArcs;
435     memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
436     Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
437     Options.NoRedZone = CodeGenOpts.DisableRedZone;
438     Options.FunctionNamesInData =
439         !CodeGenOpts.CoverageNoFunctionNamesInData;
440     Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
441     MPM.add(createGCOVProfilerPass(Options));
442     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
443       MPM.add(createStripSymbolsPass(true));
444   }
445 
446   if (CodeGenOpts.hasProfileClangInstr()) {
447     InstrProfOptions Options;
448     Options.NoRedZone = CodeGenOpts.DisableRedZone;
449     Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
450     MPM.add(createInstrProfilingLegacyPass(Options));
451   }
452   if (CodeGenOpts.hasProfileIRInstr()) {
453     PMBuilder.EnablePGOInstrGen = true;
454     if (!CodeGenOpts.InstrProfileOutput.empty())
455       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
456     else
457       PMBuilder.PGOInstrGen = "default_%m.profraw";
458   }
459   if (CodeGenOpts.hasProfileIRUse())
460     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
461 
462   if (!CodeGenOpts.SampleProfileFile.empty())
463     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
464 
465   PMBuilder.populateFunctionPassManager(FPM);
466   PMBuilder.populateModulePassManager(MPM);
467 }
468 
469 void EmitAssemblyHelper::setCommandLineOpts() {
470   SmallVector<const char *, 16> BackendArgs;
471   BackendArgs.push_back("clang"); // Fake program name.
472   if (!CodeGenOpts.DebugPass.empty()) {
473     BackendArgs.push_back("-debug-pass");
474     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
475   }
476   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
477     BackendArgs.push_back("-limit-float-precision");
478     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
479   }
480   for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
481     BackendArgs.push_back(BackendOption.c_str());
482   BackendArgs.push_back(nullptr);
483   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
484                                     BackendArgs.data());
485 }
486 
487 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
488   // Create the TargetMachine for generating code.
489   std::string Error;
490   std::string Triple = TheModule->getTargetTriple();
491   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
492   if (!TheTarget) {
493     if (MustCreateTM)
494       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
495     return;
496   }
497 
498   unsigned CodeModel =
499     llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
500       .Case("small", llvm::CodeModel::Small)
501       .Case("kernel", llvm::CodeModel::Kernel)
502       .Case("medium", llvm::CodeModel::Medium)
503       .Case("large", llvm::CodeModel::Large)
504       .Case("default", llvm::CodeModel::Default)
505       .Default(~0u);
506   assert(CodeModel != ~0u && "invalid code model!");
507   llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
508 
509   std::string FeaturesStr =
510       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
511 
512   // Keep this synced with the equivalent code in tools/driver/cc1as_main.cpp.
513   llvm::Optional<llvm::Reloc::Model> RM;
514   RM = llvm::StringSwitch<llvm::Reloc::Model>(CodeGenOpts.RelocationModel)
515            .Case("static", llvm::Reloc::Static)
516            .Case("pic", llvm::Reloc::PIC_)
517            .Case("ropi", llvm::Reloc::ROPI)
518            .Case("rwpi", llvm::Reloc::RWPI)
519            .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
520            .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC);
521   assert(RM.hasValue() && "invalid PIC model!");
522 
523   CodeGenOpt::Level OptLevel;
524   switch (CodeGenOpts.OptimizationLevel) {
525   default:
526     llvm_unreachable("Invalid optimization level!");
527   case 0:
528     OptLevel = CodeGenOpt::None;
529     break;
530   case 1:
531     OptLevel = CodeGenOpt::Less;
532     break;
533   case 2:
534     OptLevel = CodeGenOpt::Default;
535     break; // O2/Os/Oz
536   case 3:
537     OptLevel = CodeGenOpt::Aggressive;
538     break;
539   }
540 
541   llvm::TargetOptions Options;
542 
543   Options.ThreadModel =
544     llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
545       .Case("posix", llvm::ThreadModel::POSIX)
546       .Case("single", llvm::ThreadModel::Single);
547 
548   // Set float ABI type.
549   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
550           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
551          "Invalid Floating Point ABI!");
552   Options.FloatABIType =
553       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
554           .Case("soft", llvm::FloatABI::Soft)
555           .Case("softfp", llvm::FloatABI::Soft)
556           .Case("hard", llvm::FloatABI::Hard)
557           .Default(llvm::FloatABI::Default);
558 
559   // Set FP fusion mode.
560   switch (CodeGenOpts.getFPContractMode()) {
561   case CodeGenOptions::FPC_Off:
562     Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
563     break;
564   case CodeGenOptions::FPC_On:
565     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
566     break;
567   case CodeGenOptions::FPC_Fast:
568     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
569     break;
570   }
571 
572   Options.UseInitArray = CodeGenOpts.UseInitArray;
573   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
574   Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
575   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
576   Options.DebugInfoForProfiling = CodeGenOpts.DebugInfoForProfiling;
577 
578   // Set EABI version.
579   Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion)
580                             .Case("4", llvm::EABI::EABI4)
581                             .Case("5", llvm::EABI::EABI5)
582                             .Case("gnu", llvm::EABI::GNU)
583                             .Default(llvm::EABI::Default);
584 
585   if (LangOpts.SjLjExceptions)
586     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
587 
588   Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
589   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
590   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
591   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
592   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
593   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
594   Options.FunctionSections = CodeGenOpts.FunctionSections;
595   Options.DataSections = CodeGenOpts.DataSections;
596   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
597   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
598   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
599 
600   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
601   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
602   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
603   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
604   Options.MCOptions.MCIncrementalLinkerCompatible =
605       CodeGenOpts.IncrementalLinkerCompatible;
606   Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
607   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
608   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
609   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
610   Options.MCOptions.ABIName = TargetOpts.ABI;
611   for (const auto &Entry : HSOpts.UserEntries)
612     if (!Entry.IsFramework &&
613         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
614          Entry.Group == frontend::IncludeDirGroup::Angled ||
615          Entry.Group == frontend::IncludeDirGroup::System))
616       Options.MCOptions.IASSearchPaths.push_back(
617           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
618 
619   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
620                                           Options, RM, CM, OptLevel));
621 }
622 
623 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
624                                        BackendAction Action,
625                                        raw_pwrite_stream &OS) {
626   // Add LibraryInfo.
627   llvm::Triple TargetTriple(TheModule->getTargetTriple());
628   std::unique_ptr<TargetLibraryInfoImpl> TLII(
629       createTLII(TargetTriple, CodeGenOpts));
630   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
631 
632   // Normal mode, emit a .s or .o file by running the code generator. Note,
633   // this also adds codegenerator level optimization passes.
634   TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
635   if (Action == Backend_EmitObj)
636     CGFT = TargetMachine::CGFT_ObjectFile;
637   else if (Action == Backend_EmitMCNull)
638     CGFT = TargetMachine::CGFT_Null;
639   else
640     assert(Action == Backend_EmitAssembly && "Invalid action!");
641 
642   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
643   // "codegen" passes so that it isn't run multiple times when there is
644   // inlining happening.
645   if (CodeGenOpts.OptimizationLevel > 0)
646     CodeGenPasses.add(createObjCARCContractPass());
647 
648   if (TM->addPassesToEmitFile(CodeGenPasses, OS, CGFT,
649                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
650     Diags.Report(diag::err_fe_unable_to_interface_with_target);
651     return false;
652   }
653 
654   return true;
655 }
656 
657 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
658                                       std::unique_ptr<raw_pwrite_stream> OS) {
659   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
660 
661   setCommandLineOpts();
662 
663   bool UsesCodeGen = (Action != Backend_EmitNothing &&
664                       Action != Backend_EmitBC &&
665                       Action != Backend_EmitLL);
666   CreateTargetMachine(UsesCodeGen);
667 
668   if (UsesCodeGen && !TM)
669     return;
670   if (TM)
671     TheModule->setDataLayout(TM->createDataLayout());
672 
673   legacy::PassManager PerModulePasses;
674   PerModulePasses.add(
675       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
676 
677   legacy::FunctionPassManager PerFunctionPasses(TheModule);
678   PerFunctionPasses.add(
679       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
680 
681   CreatePasses(PerModulePasses, PerFunctionPasses);
682 
683   legacy::PassManager CodeGenPasses;
684   CodeGenPasses.add(
685       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
686 
687   switch (Action) {
688   case Backend_EmitNothing:
689     break;
690 
691   case Backend_EmitBC:
692     PerModulePasses.add(createBitcodeWriterPass(
693         *OS, CodeGenOpts.EmitLLVMUseLists, CodeGenOpts.EmitSummaryIndex,
694         CodeGenOpts.EmitSummaryIndex));
695     break;
696 
697   case Backend_EmitLL:
698     PerModulePasses.add(
699         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
700     break;
701 
702   default:
703     if (!AddEmitPasses(CodeGenPasses, Action, *OS))
704       return;
705   }
706 
707   // Before executing passes, print the final values of the LLVM options.
708   cl::PrintOptionValues();
709 
710   // Run passes. For now we do all passes at once, but eventually we
711   // would like to have the option of streaming code generation.
712 
713   {
714     PrettyStackTraceString CrashInfo("Per-function optimization");
715 
716     PerFunctionPasses.doInitialization();
717     for (Function &F : *TheModule)
718       if (!F.isDeclaration())
719         PerFunctionPasses.run(F);
720     PerFunctionPasses.doFinalization();
721   }
722 
723   {
724     PrettyStackTraceString CrashInfo("Per-module optimization passes");
725     PerModulePasses.run(*TheModule);
726   }
727 
728   {
729     PrettyStackTraceString CrashInfo("Code generation");
730     CodeGenPasses.run(*TheModule);
731   }
732 }
733 
734 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
735   switch (Opts.OptimizationLevel) {
736   default:
737     llvm_unreachable("Invalid optimization level!");
738 
739   case 1:
740     return PassBuilder::O1;
741 
742   case 2:
743     switch (Opts.OptimizeSize) {
744     default:
745       llvm_unreachable("Invalide optimization level for size!");
746 
747     case 0:
748       return PassBuilder::O2;
749 
750     case 1:
751       return PassBuilder::Os;
752 
753     case 2:
754       return PassBuilder::Oz;
755     }
756 
757   case 3:
758     return PassBuilder::O3;
759   }
760 }
761 
762 /// A clean version of `EmitAssembly` that uses the new pass manager.
763 ///
764 /// Not all features are currently supported in this system, but where
765 /// necessary it falls back to the legacy pass manager to at least provide
766 /// basic functionality.
767 ///
768 /// This API is planned to have its functionality finished and then to replace
769 /// `EmitAssembly` at some point in the future when the default switches.
770 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
771     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
772   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
773   setCommandLineOpts();
774 
775   // The new pass manager always makes a target machine available to passes
776   // during construction.
777   CreateTargetMachine(/*MustCreateTM*/ true);
778   if (!TM)
779     // This will already be diagnosed, just bail.
780     return;
781   TheModule->setDataLayout(TM->createDataLayout());
782 
783   PassBuilder PB(TM.get());
784 
785   LoopAnalysisManager LAM;
786   FunctionAnalysisManager FAM;
787   CGSCCAnalysisManager CGAM;
788   ModuleAnalysisManager MAM;
789 
790   // Register the AA manager first so that our version is the one used.
791   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
792 
793   // Register all the basic analyses with the managers.
794   PB.registerModuleAnalyses(MAM);
795   PB.registerCGSCCAnalyses(CGAM);
796   PB.registerFunctionAnalyses(FAM);
797   PB.registerLoopAnalyses(LAM);
798   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
799 
800   ModulePassManager MPM;
801 
802   if (!CodeGenOpts.DisableLLVMPasses) {
803     if (CodeGenOpts.OptimizationLevel == 0) {
804       // Build a minimal pipeline based on the semantics required by Clang,
805       // which is just that always inlining occurs.
806       MPM.addPass(AlwaysInlinerPass());
807     } else {
808       // Otherwise, use the default pass pipeline. We also have to map our
809       // optimization levels into one of the distinct levels used to configure
810       // the pipeline.
811       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
812 
813       MPM = PB.buildPerModuleDefaultPipeline(Level);
814     }
815   }
816 
817   // FIXME: We still use the legacy pass manager to do code generation. We
818   // create that pass manager here and use it as needed below.
819   legacy::PassManager CodeGenPasses;
820   bool NeedCodeGen = false;
821 
822   // Append any output we need to the pass manager.
823   switch (Action) {
824   case Backend_EmitNothing:
825     break;
826 
827   case Backend_EmitBC:
828     MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
829                                   CodeGenOpts.EmitSummaryIndex,
830                                   CodeGenOpts.EmitSummaryIndex));
831     break;
832 
833   case Backend_EmitLL:
834     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
835     break;
836 
837   case Backend_EmitAssembly:
838   case Backend_EmitMCNull:
839   case Backend_EmitObj:
840     NeedCodeGen = true;
841     CodeGenPasses.add(
842         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
843     if (!AddEmitPasses(CodeGenPasses, Action, *OS))
844       // FIXME: Should we handle this error differently?
845       return;
846     break;
847   }
848 
849   // Before executing passes, print the final values of the LLVM options.
850   cl::PrintOptionValues();
851 
852   // Now that we have all of the passes ready, run them.
853   {
854     PrettyStackTraceString CrashInfo("Optimizer");
855     MPM.run(*TheModule, MAM);
856   }
857 
858   // Now if needed, run the legacy PM for codegen.
859   if (NeedCodeGen) {
860     PrettyStackTraceString CrashInfo("Code generation");
861     CodeGenPasses.run(*TheModule);
862   }
863 }
864 
865 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
866                               std::unique_ptr<raw_pwrite_stream> OS,
867                               std::string SampleProfile) {
868   StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
869       ModuleToDefinedGVSummaries;
870   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
871 
872   // We can simply import the values mentioned in the combined index, since
873   // we should only invoke this using the individual indexes written out
874   // via a WriteIndexesThinBackend.
875   FunctionImporter::ImportMapTy ImportList;
876   for (auto &GlobalList : *CombinedIndex) {
877     auto GUID = GlobalList.first;
878     assert(GlobalList.second.size() == 1 &&
879            "Expected individual combined index to have one summary per GUID");
880     auto &Summary = GlobalList.second[0];
881     // Skip the summaries for the importing module. These are included to
882     // e.g. record required linkage changes.
883     if (Summary->modulePath() == M->getModuleIdentifier())
884       continue;
885     // Doesn't matter what value we plug in to the map, just needs an entry
886     // to provoke importing by thinBackend.
887     ImportList[Summary->modulePath()][GUID] = 1;
888   }
889 
890   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
891   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
892 
893   for (auto &I : ImportList) {
894     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
895         llvm::MemoryBuffer::getFile(I.first());
896     if (!MBOrErr) {
897       errs() << "Error loading imported file '" << I.first()
898              << "': " << MBOrErr.getError().message() << "\n";
899       return;
900     }
901 
902     Expected<std::vector<BitcodeModule>> BMsOrErr =
903         getBitcodeModuleList(**MBOrErr);
904     if (!BMsOrErr) {
905       handleAllErrors(BMsOrErr.takeError(), [&](ErrorInfoBase &EIB) {
906         errs() << "Error loading imported file '" << I.first()
907                << "': " << EIB.message() << '\n';
908       });
909       return;
910     }
911 
912     // The bitcode file may contain multiple modules, we want the one with a
913     // summary.
914     bool FoundModule = false;
915     for (BitcodeModule &BM : *BMsOrErr) {
916       Expected<bool> HasSummary = BM.hasSummary();
917       if (HasSummary && *HasSummary) {
918         ModuleMap.insert({I.first(), BM});
919         FoundModule = true;
920         break;
921       }
922     }
923     if (!FoundModule) {
924       errs() << "Error loading imported file '" << I.first()
925              << "': Could not find module summary\n";
926       return;
927     }
928 
929     OwnedImports.push_back(std::move(*MBOrErr));
930   }
931   auto AddStream = [&](size_t Task) {
932     return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
933   };
934   lto::Config Conf;
935   Conf.SampleProfile = SampleProfile;
936   if (Error E = thinBackend(
937           Conf, 0, AddStream, *M, *CombinedIndex, ImportList,
938           ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
939     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
940       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
941     });
942   }
943 }
944 
945 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
946                               const HeaderSearchOptions &HeaderOpts,
947                               const CodeGenOptions &CGOpts,
948                               const clang::TargetOptions &TOpts,
949                               const LangOptions &LOpts,
950                               const llvm::DataLayout &TDesc, Module *M,
951                               BackendAction Action,
952                               std::unique_ptr<raw_pwrite_stream> OS) {
953   if (!CGOpts.ThinLTOIndexFile.empty()) {
954     // If we are performing a ThinLTO importing compile, load the function index
955     // into memory and pass it into runThinLTOBackend, which will run the
956     // function importer and invoke LTO passes.
957     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
958         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile);
959     if (!IndexOrErr) {
960       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
961                             "Error loading index file '" +
962                             CGOpts.ThinLTOIndexFile + "': ");
963       return;
964     }
965     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
966     // A null CombinedIndex means we should skip ThinLTO compilation
967     // (LLVM will optionally ignore empty index files, returning null instead
968     // of an error).
969     bool DoThinLTOBackend = CombinedIndex != nullptr;
970     if (DoThinLTOBackend) {
971       runThinLTOBackend(CombinedIndex.get(), M, std::move(OS),
972                         CGOpts.SampleProfileFile);
973       return;
974     }
975   }
976 
977   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
978 
979   if (CGOpts.ExperimentalNewPassManager)
980     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
981   else
982     AsmHelper.EmitAssembly(Action, std::move(OS));
983 
984   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
985   // DataLayout.
986   if (AsmHelper.TM) {
987     std::string DLDesc = M->getDataLayout().getStringRepresentation();
988     if (DLDesc != TDesc.getStringRepresentation()) {
989       unsigned DiagID = Diags.getCustomDiagID(
990           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
991                                     "expected target description '%1'");
992       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
993     }
994   }
995 }
996 
997 static const char* getSectionNameForBitcode(const Triple &T) {
998   switch (T.getObjectFormat()) {
999   case Triple::MachO:
1000     return "__LLVM,__bitcode";
1001   case Triple::COFF:
1002   case Triple::ELF:
1003   case Triple::Wasm:
1004   case Triple::UnknownObjectFormat:
1005     return ".llvmbc";
1006   }
1007   llvm_unreachable("Unimplemented ObjectFormatType");
1008 }
1009 
1010 static const char* getSectionNameForCommandline(const Triple &T) {
1011   switch (T.getObjectFormat()) {
1012   case Triple::MachO:
1013     return "__LLVM,__cmdline";
1014   case Triple::COFF:
1015   case Triple::ELF:
1016   case Triple::Wasm:
1017   case Triple::UnknownObjectFormat:
1018     return ".llvmcmd";
1019   }
1020   llvm_unreachable("Unimplemented ObjectFormatType");
1021 }
1022 
1023 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1024 // __LLVM,__bitcode section.
1025 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1026                          llvm::MemoryBufferRef Buf) {
1027   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1028     return;
1029 
1030   // Save llvm.compiler.used and remote it.
1031   SmallVector<Constant*, 2> UsedArray;
1032   SmallSet<GlobalValue*, 4> UsedGlobals;
1033   Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1034   GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1035   for (auto *GV : UsedGlobals) {
1036     if (GV->getName() != "llvm.embedded.module" &&
1037         GV->getName() != "llvm.cmdline")
1038       UsedArray.push_back(
1039           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1040   }
1041   if (Used)
1042     Used->eraseFromParent();
1043 
1044   // Embed the bitcode for the llvm module.
1045   std::string Data;
1046   ArrayRef<uint8_t> ModuleData;
1047   Triple T(M->getTargetTriple());
1048   // Create a constant that contains the bitcode.
1049   // In case of embedding a marker, ignore the input Buf and use the empty
1050   // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1051   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1052     if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1053                    (const unsigned char *)Buf.getBufferEnd())) {
1054       // If the input is LLVM Assembly, bitcode is produced by serializing
1055       // the module. Use-lists order need to be perserved in this case.
1056       llvm::raw_string_ostream OS(Data);
1057       llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
1058       ModuleData =
1059           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1060     } else
1061       // If the input is LLVM bitcode, write the input byte stream directly.
1062       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1063                                      Buf.getBufferSize());
1064   }
1065   llvm::Constant *ModuleConstant =
1066       llvm::ConstantDataArray::get(M->getContext(), ModuleData);
1067   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1068       *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
1069       ModuleConstant);
1070   GV->setSection(getSectionNameForBitcode(T));
1071   UsedArray.push_back(
1072       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1073   if (llvm::GlobalVariable *Old =
1074           M->getGlobalVariable("llvm.embedded.module", true)) {
1075     assert(Old->hasOneUse() &&
1076            "llvm.embedded.module can only be used once in llvm.compiler.used");
1077     GV->takeName(Old);
1078     Old->eraseFromParent();
1079   } else {
1080     GV->setName("llvm.embedded.module");
1081   }
1082 
1083   // Skip if only bitcode needs to be embedded.
1084   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1085     // Embed command-line options.
1086     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
1087                               CGOpts.CmdArgs.size());
1088     llvm::Constant *CmdConstant =
1089       llvm::ConstantDataArray::get(M->getContext(), CmdData);
1090     GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1091                                   llvm::GlobalValue::PrivateLinkage,
1092                                   CmdConstant);
1093     GV->setSection(getSectionNameForCommandline(T));
1094     UsedArray.push_back(
1095         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1096     if (llvm::GlobalVariable *Old =
1097             M->getGlobalVariable("llvm.cmdline", true)) {
1098       assert(Old->hasOneUse() &&
1099              "llvm.cmdline can only be used once in llvm.compiler.used");
1100       GV->takeName(Old);
1101       Old->eraseFromParent();
1102     } else {
1103       GV->setName("llvm.cmdline");
1104     }
1105   }
1106 
1107   if (UsedArray.empty())
1108     return;
1109 
1110   // Recreate llvm.compiler.used.
1111   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1112   auto *NewUsed = new GlobalVariable(
1113       *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1114       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1115   NewUsed->setSection("llvm.metadata");
1116 }
1117