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