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     // We do not want to inline hot callsites for SamplePGO module-summary build
322     // because profile annotation will happen again in ThinLTO backend, and we
323     // want the IR of the hot path to match the profile.
324     PMBuilder.Inliner = createFunctionInliningPass(
325         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
326         (!CodeGenOpts.SampleProfileFile.empty() &&
327          CodeGenOpts.EmitSummaryIndex));
328   }
329 
330   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
331   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
332   PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
333   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
334   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
335 
336   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
337   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
338   PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
339   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
340   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
341 
342   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
343 
344   if (TM)
345     TM->adjustPassManager(PMBuilder);
346 
347   if (CodeGenOpts.DebugInfoForProfiling ||
348       !CodeGenOpts.SampleProfileFile.empty())
349     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
350                            addAddDiscriminatorsPass);
351 
352   // In ObjC ARC mode, add the main ARC optimization passes.
353   if (LangOpts.ObjCAutoRefCount) {
354     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
355                            addObjCARCExpandPass);
356     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
357                            addObjCARCAPElimPass);
358     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
359                            addObjCARCOptPass);
360   }
361 
362   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
363     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
364                            addBoundsCheckingPass);
365     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
366                            addBoundsCheckingPass);
367   }
368 
369   if (CodeGenOpts.SanitizeCoverageType ||
370       CodeGenOpts.SanitizeCoverageIndirectCalls ||
371       CodeGenOpts.SanitizeCoverageTraceCmp) {
372     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
373                            addSanitizerCoveragePass);
374     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
375                            addSanitizerCoveragePass);
376   }
377 
378   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
379     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
380                            addAddressSanitizerPasses);
381     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
382                            addAddressSanitizerPasses);
383   }
384 
385   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
386     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
387                            addKernelAddressSanitizerPasses);
388     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
389                            addKernelAddressSanitizerPasses);
390   }
391 
392   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
393     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
394                            addMemorySanitizerPass);
395     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
396                            addMemorySanitizerPass);
397   }
398 
399   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
400     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
401                            addThreadSanitizerPass);
402     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
403                            addThreadSanitizerPass);
404   }
405 
406   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
407     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
408                            addDataFlowSanitizerPass);
409     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
410                            addDataFlowSanitizerPass);
411   }
412 
413   if (LangOpts.CoroutinesTS)
414     addCoroutinePassesToExtensionPoints(PMBuilder);
415 
416   if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
417     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
418                            addEfficiencySanitizerPass);
419     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
420                            addEfficiencySanitizerPass);
421   }
422 
423   // Set up the per-function pass manager.
424   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
425   if (CodeGenOpts.VerifyModule)
426     FPM.add(createVerifierPass());
427 
428   // Set up the per-module pass manager.
429   if (!CodeGenOpts.RewriteMapFiles.empty())
430     addSymbolRewriterPass(CodeGenOpts, &MPM);
431 
432   if (!CodeGenOpts.DisableGCov &&
433       (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
434     // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
435     // LLVM's -default-gcov-version flag is set to something invalid.
436     GCOVOptions Options;
437     Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
438     Options.EmitData = CodeGenOpts.EmitGcovArcs;
439     memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
440     Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
441     Options.NoRedZone = CodeGenOpts.DisableRedZone;
442     Options.FunctionNamesInData =
443         !CodeGenOpts.CoverageNoFunctionNamesInData;
444     Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
445     MPM.add(createGCOVProfilerPass(Options));
446     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
447       MPM.add(createStripSymbolsPass(true));
448   }
449 
450   if (CodeGenOpts.hasProfileClangInstr()) {
451     InstrProfOptions Options;
452     Options.NoRedZone = CodeGenOpts.DisableRedZone;
453     Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
454     MPM.add(createInstrProfilingLegacyPass(Options));
455   }
456   if (CodeGenOpts.hasProfileIRInstr()) {
457     PMBuilder.EnablePGOInstrGen = true;
458     if (!CodeGenOpts.InstrProfileOutput.empty())
459       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
460     else
461       PMBuilder.PGOInstrGen = DefaultProfileGenName;
462   }
463   if (CodeGenOpts.hasProfileIRUse())
464     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
465 
466   if (!CodeGenOpts.SampleProfileFile.empty())
467     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
468 
469   PMBuilder.populateFunctionPassManager(FPM);
470   PMBuilder.populateModulePassManager(MPM);
471 }
472 
473 void EmitAssemblyHelper::setCommandLineOpts() {
474   SmallVector<const char *, 16> BackendArgs;
475   BackendArgs.push_back("clang"); // Fake program name.
476   if (!CodeGenOpts.DebugPass.empty()) {
477     BackendArgs.push_back("-debug-pass");
478     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
479   }
480   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
481     BackendArgs.push_back("-limit-float-precision");
482     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
483   }
484   for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
485     BackendArgs.push_back(BackendOption.c_str());
486   BackendArgs.push_back(nullptr);
487   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
488                                     BackendArgs.data());
489 }
490 
491 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
492   // Create the TargetMachine for generating code.
493   std::string Error;
494   std::string Triple = TheModule->getTargetTriple();
495   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
496   if (!TheTarget) {
497     if (MustCreateTM)
498       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
499     return;
500   }
501 
502   unsigned CodeModel =
503     llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
504       .Case("small", llvm::CodeModel::Small)
505       .Case("kernel", llvm::CodeModel::Kernel)
506       .Case("medium", llvm::CodeModel::Medium)
507       .Case("large", llvm::CodeModel::Large)
508       .Case("default", llvm::CodeModel::Default)
509       .Default(~0u);
510   assert(CodeModel != ~0u && "invalid code model!");
511   llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
512 
513   std::string FeaturesStr =
514       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
515 
516   // Keep this synced with the equivalent code in tools/driver/cc1as_main.cpp.
517   llvm::Optional<llvm::Reloc::Model> RM;
518   RM = llvm::StringSwitch<llvm::Reloc::Model>(CodeGenOpts.RelocationModel)
519            .Case("static", llvm::Reloc::Static)
520            .Case("pic", llvm::Reloc::PIC_)
521            .Case("ropi", llvm::Reloc::ROPI)
522            .Case("rwpi", llvm::Reloc::RWPI)
523            .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
524            .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC);
525   assert(RM.hasValue() && "invalid PIC model!");
526 
527   CodeGenOpt::Level OptLevel;
528   switch (CodeGenOpts.OptimizationLevel) {
529   default:
530     llvm_unreachable("Invalid optimization level!");
531   case 0:
532     OptLevel = CodeGenOpt::None;
533     break;
534   case 1:
535     OptLevel = CodeGenOpt::Less;
536     break;
537   case 2:
538     OptLevel = CodeGenOpt::Default;
539     break; // O2/Os/Oz
540   case 3:
541     OptLevel = CodeGenOpt::Aggressive;
542     break;
543   }
544 
545   llvm::TargetOptions Options;
546 
547   Options.ThreadModel =
548     llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
549       .Case("posix", llvm::ThreadModel::POSIX)
550       .Case("single", llvm::ThreadModel::Single);
551 
552   // Set float ABI type.
553   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
554           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
555          "Invalid Floating Point ABI!");
556   Options.FloatABIType =
557       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
558           .Case("soft", llvm::FloatABI::Soft)
559           .Case("softfp", llvm::FloatABI::Soft)
560           .Case("hard", llvm::FloatABI::Hard)
561           .Default(llvm::FloatABI::Default);
562 
563   // Set FP fusion mode.
564   switch (CodeGenOpts.getFPContractMode()) {
565   case CodeGenOptions::FPC_Off:
566     Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
567     break;
568   case CodeGenOptions::FPC_On:
569     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
570     break;
571   case CodeGenOptions::FPC_Fast:
572     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
573     break;
574   }
575 
576   Options.UseInitArray = CodeGenOpts.UseInitArray;
577   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
578   Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
579   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
580 
581   // Set EABI version.
582   Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion)
583                             .Case("4", llvm::EABI::EABI4)
584                             .Case("5", llvm::EABI::EABI5)
585                             .Case("gnu", llvm::EABI::GNU)
586                             .Default(llvm::EABI::Default);
587 
588   if (LangOpts.SjLjExceptions)
589     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
590 
591   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
592   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
593   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
594   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
595   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
596   Options.FunctionSections = CodeGenOpts.FunctionSections;
597   Options.DataSections = CodeGenOpts.DataSections;
598   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
599   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
600   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
601 
602   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
603   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
604   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
605   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
606   Options.MCOptions.MCIncrementalLinkerCompatible =
607       CodeGenOpts.IncrementalLinkerCompatible;
608   Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
609   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
610   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
611   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
612   Options.MCOptions.ABIName = TargetOpts.ABI;
613   for (const auto &Entry : HSOpts.UserEntries)
614     if (!Entry.IsFramework &&
615         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
616          Entry.Group == frontend::IncludeDirGroup::Angled ||
617          Entry.Group == frontend::IncludeDirGroup::System))
618       Options.MCOptions.IASSearchPaths.push_back(
619           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
620 
621   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
622                                           Options, RM, CM, OptLevel));
623 }
624 
625 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
626                                        BackendAction Action,
627                                        raw_pwrite_stream &OS) {
628   // Add LibraryInfo.
629   llvm::Triple TargetTriple(TheModule->getTargetTriple());
630   std::unique_ptr<TargetLibraryInfoImpl> TLII(
631       createTLII(TargetTriple, CodeGenOpts));
632   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
633 
634   // Normal mode, emit a .s or .o file by running the code generator. Note,
635   // this also adds codegenerator level optimization passes.
636   TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
637   if (Action == Backend_EmitObj)
638     CGFT = TargetMachine::CGFT_ObjectFile;
639   else if (Action == Backend_EmitMCNull)
640     CGFT = TargetMachine::CGFT_Null;
641   else
642     assert(Action == Backend_EmitAssembly && "Invalid action!");
643 
644   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
645   // "codegen" passes so that it isn't run multiple times when there is
646   // inlining happening.
647   if (CodeGenOpts.OptimizationLevel > 0)
648     CodeGenPasses.add(createObjCARCContractPass());
649 
650   if (TM->addPassesToEmitFile(CodeGenPasses, OS, CGFT,
651                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
652     Diags.Report(diag::err_fe_unable_to_interface_with_target);
653     return false;
654   }
655 
656   return true;
657 }
658 
659 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
660                                       std::unique_ptr<raw_pwrite_stream> OS) {
661   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
662 
663   setCommandLineOpts();
664 
665   bool UsesCodeGen = (Action != Backend_EmitNothing &&
666                       Action != Backend_EmitBC &&
667                       Action != Backend_EmitLL);
668   CreateTargetMachine(UsesCodeGen);
669 
670   if (UsesCodeGen && !TM)
671     return;
672   if (TM)
673     TheModule->setDataLayout(TM->createDataLayout());
674 
675   legacy::PassManager PerModulePasses;
676   PerModulePasses.add(
677       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
678 
679   legacy::FunctionPassManager PerFunctionPasses(TheModule);
680   PerFunctionPasses.add(
681       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
682 
683   CreatePasses(PerModulePasses, PerFunctionPasses);
684 
685   legacy::PassManager CodeGenPasses;
686   CodeGenPasses.add(
687       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
688 
689   std::unique_ptr<raw_fd_ostream> ThinLinkOS;
690 
691   switch (Action) {
692   case Backend_EmitNothing:
693     break;
694 
695   case Backend_EmitBC:
696     if (CodeGenOpts.EmitSummaryIndex) {
697       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
698         std::error_code EC;
699         ThinLinkOS.reset(new llvm::raw_fd_ostream(
700             CodeGenOpts.ThinLinkBitcodeFile, EC,
701             llvm::sys::fs::F_None));
702         if (EC) {
703           Diags.Report(diag::err_fe_unable_to_open_output) << CodeGenOpts.ThinLinkBitcodeFile
704                                                            << EC.message();
705           return;
706         }
707       }
708       PerModulePasses.add(
709           createWriteThinLTOBitcodePass(*OS, ThinLinkOS.get()));
710     }
711     else
712       PerModulePasses.add(
713           createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists));
714     break;
715 
716   case Backend_EmitLL:
717     PerModulePasses.add(
718         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
719     break;
720 
721   default:
722     if (!AddEmitPasses(CodeGenPasses, Action, *OS))
723       return;
724   }
725 
726   // Before executing passes, print the final values of the LLVM options.
727   cl::PrintOptionValues();
728 
729   // Run passes. For now we do all passes at once, but eventually we
730   // would like to have the option of streaming code generation.
731 
732   {
733     PrettyStackTraceString CrashInfo("Per-function optimization");
734 
735     PerFunctionPasses.doInitialization();
736     for (Function &F : *TheModule)
737       if (!F.isDeclaration())
738         PerFunctionPasses.run(F);
739     PerFunctionPasses.doFinalization();
740   }
741 
742   {
743     PrettyStackTraceString CrashInfo("Per-module optimization passes");
744     PerModulePasses.run(*TheModule);
745   }
746 
747   {
748     PrettyStackTraceString CrashInfo("Code generation");
749     CodeGenPasses.run(*TheModule);
750   }
751 }
752 
753 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
754   switch (Opts.OptimizationLevel) {
755   default:
756     llvm_unreachable("Invalid optimization level!");
757 
758   case 1:
759     return PassBuilder::O1;
760 
761   case 2:
762     switch (Opts.OptimizeSize) {
763     default:
764       llvm_unreachable("Invalide optimization level for size!");
765 
766     case 0:
767       return PassBuilder::O2;
768 
769     case 1:
770       return PassBuilder::Os;
771 
772     case 2:
773       return PassBuilder::Oz;
774     }
775 
776   case 3:
777     return PassBuilder::O3;
778   }
779 }
780 
781 /// A clean version of `EmitAssembly` that uses the new pass manager.
782 ///
783 /// Not all features are currently supported in this system, but where
784 /// necessary it falls back to the legacy pass manager to at least provide
785 /// basic functionality.
786 ///
787 /// This API is planned to have its functionality finished and then to replace
788 /// `EmitAssembly` at some point in the future when the default switches.
789 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
790     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
791   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
792   setCommandLineOpts();
793 
794   // The new pass manager always makes a target machine available to passes
795   // during construction.
796   CreateTargetMachine(/*MustCreateTM*/ true);
797   if (!TM)
798     // This will already be diagnosed, just bail.
799     return;
800   TheModule->setDataLayout(TM->createDataLayout());
801 
802   PGOOptions PGOOpt;
803 
804   // -fprofile-generate.
805   PGOOpt.RunProfileGen = CodeGenOpts.hasProfileIRInstr();
806   if (PGOOpt.RunProfileGen)
807     PGOOpt.ProfileGenFile = CodeGenOpts.InstrProfileOutput.empty() ?
808       DefaultProfileGenName : CodeGenOpts.InstrProfileOutput;
809 
810   // -fprofile-use.
811   if (CodeGenOpts.hasProfileIRUse())
812     PGOOpt.ProfileUseFile = CodeGenOpts.ProfileInstrumentUsePath;
813 
814   // Only pass a PGO options struct if -fprofile-generate or
815   // -fprofile-use were passed on the cmdline.
816   PassBuilder PB(TM.get(),
817     (PGOOpt.RunProfileGen ||
818       !PGOOpt.ProfileUseFile.empty()) ?
819         Optional<PGOOptions>(PGOOpt) : None);
820 
821   LoopAnalysisManager LAM;
822   FunctionAnalysisManager FAM;
823   CGSCCAnalysisManager CGAM;
824   ModuleAnalysisManager MAM;
825 
826   // Register the AA manager first so that our version is the one used.
827   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
828 
829   // Register all the basic analyses with the managers.
830   PB.registerModuleAnalyses(MAM);
831   PB.registerCGSCCAnalyses(CGAM);
832   PB.registerFunctionAnalyses(FAM);
833   PB.registerLoopAnalyses(LAM);
834   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
835 
836   ModulePassManager MPM;
837 
838   if (!CodeGenOpts.DisableLLVMPasses) {
839     if (CodeGenOpts.OptimizationLevel == 0) {
840       // Build a minimal pipeline based on the semantics required by Clang,
841       // which is just that always inlining occurs.
842       MPM.addPass(AlwaysInlinerPass());
843     } else {
844       // Otherwise, use the default pass pipeline. We also have to map our
845       // optimization levels into one of the distinct levels used to configure
846       // the pipeline.
847       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
848 
849       MPM = PB.buildPerModuleDefaultPipeline(Level);
850     }
851   }
852 
853   // FIXME: We still use the legacy pass manager to do code generation. We
854   // create that pass manager here and use it as needed below.
855   legacy::PassManager CodeGenPasses;
856   bool NeedCodeGen = false;
857 
858   // Append any output we need to the pass manager.
859   switch (Action) {
860   case Backend_EmitNothing:
861     break;
862 
863   case Backend_EmitBC:
864     MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
865                                   CodeGenOpts.EmitSummaryIndex,
866                                   CodeGenOpts.EmitSummaryIndex));
867     break;
868 
869   case Backend_EmitLL:
870     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
871     break;
872 
873   case Backend_EmitAssembly:
874   case Backend_EmitMCNull:
875   case Backend_EmitObj:
876     NeedCodeGen = true;
877     CodeGenPasses.add(
878         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
879     if (!AddEmitPasses(CodeGenPasses, Action, *OS))
880       // FIXME: Should we handle this error differently?
881       return;
882     break;
883   }
884 
885   // Before executing passes, print the final values of the LLVM options.
886   cl::PrintOptionValues();
887 
888   // Now that we have all of the passes ready, run them.
889   {
890     PrettyStackTraceString CrashInfo("Optimizer");
891     MPM.run(*TheModule, MAM);
892   }
893 
894   // Now if needed, run the legacy PM for codegen.
895   if (NeedCodeGen) {
896     PrettyStackTraceString CrashInfo("Code generation");
897     CodeGenPasses.run(*TheModule);
898   }
899 }
900 
901 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
902   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
903   if (!BMsOrErr)
904     return BMsOrErr.takeError();
905 
906   // The bitcode file may contain multiple modules, we want the one with a
907   // summary.
908   for (BitcodeModule &BM : *BMsOrErr) {
909     Expected<bool> HasSummary = BM.hasSummary();
910     if (HasSummary && *HasSummary)
911       return BM;
912   }
913 
914   return make_error<StringError>("Could not find module summary",
915                                  inconvertibleErrorCode());
916 }
917 
918 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
919                               std::unique_ptr<raw_pwrite_stream> OS,
920                               std::string SampleProfile) {
921   StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
922       ModuleToDefinedGVSummaries;
923   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
924 
925   // We can simply import the values mentioned in the combined index, since
926   // we should only invoke this using the individual indexes written out
927   // via a WriteIndexesThinBackend.
928   FunctionImporter::ImportMapTy ImportList;
929   for (auto &GlobalList : *CombinedIndex) {
930     auto GUID = GlobalList.first;
931     assert(GlobalList.second.size() == 1 &&
932            "Expected individual combined index to have one summary per GUID");
933     auto &Summary = GlobalList.second[0];
934     // Skip the summaries for the importing module. These are included to
935     // e.g. record required linkage changes.
936     if (Summary->modulePath() == M->getModuleIdentifier())
937       continue;
938     // Doesn't matter what value we plug in to the map, just needs an entry
939     // to provoke importing by thinBackend.
940     ImportList[Summary->modulePath()][GUID] = 1;
941   }
942 
943   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
944   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
945 
946   for (auto &I : ImportList) {
947     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
948         llvm::MemoryBuffer::getFile(I.first());
949     if (!MBOrErr) {
950       errs() << "Error loading imported file '" << I.first()
951              << "': " << MBOrErr.getError().message() << "\n";
952       return;
953     }
954 
955     Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
956     if (!BMOrErr) {
957       handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
958         errs() << "Error loading imported file '" << I.first()
959                << "': " << EIB.message() << '\n';
960       });
961       return;
962     }
963     ModuleMap.insert({I.first(), *BMOrErr});
964 
965     OwnedImports.push_back(std::move(*MBOrErr));
966   }
967   auto AddStream = [&](size_t Task) {
968     return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
969   };
970   lto::Config Conf;
971   Conf.SampleProfile = std::move(SampleProfile);
972   if (Error E = thinBackend(
973           Conf, 0, AddStream, *M, *CombinedIndex, ImportList,
974           ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
975     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
976       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
977     });
978   }
979 }
980 
981 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
982                               const HeaderSearchOptions &HeaderOpts,
983                               const CodeGenOptions &CGOpts,
984                               const clang::TargetOptions &TOpts,
985                               const LangOptions &LOpts,
986                               const llvm::DataLayout &TDesc, Module *M,
987                               BackendAction Action,
988                               std::unique_ptr<raw_pwrite_stream> OS) {
989   if (!CGOpts.ThinLTOIndexFile.empty()) {
990     // If we are performing a ThinLTO importing compile, load the function index
991     // into memory and pass it into runThinLTOBackend, which will run the
992     // function importer and invoke LTO passes.
993     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
994         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile);
995     if (!IndexOrErr) {
996       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
997                             "Error loading index file '" +
998                             CGOpts.ThinLTOIndexFile + "': ");
999       return;
1000     }
1001     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1002     // A null CombinedIndex means we should skip ThinLTO compilation
1003     // (LLVM will optionally ignore empty index files, returning null instead
1004     // of an error).
1005     bool DoThinLTOBackend = CombinedIndex != nullptr;
1006     if (DoThinLTOBackend) {
1007       runThinLTOBackend(CombinedIndex.get(), M, std::move(OS),
1008                         CGOpts.SampleProfileFile);
1009       return;
1010     }
1011   }
1012 
1013   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1014 
1015   if (CGOpts.ExperimentalNewPassManager)
1016     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1017   else
1018     AsmHelper.EmitAssembly(Action, std::move(OS));
1019 
1020   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1021   // DataLayout.
1022   if (AsmHelper.TM) {
1023     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1024     if (DLDesc != TDesc.getStringRepresentation()) {
1025       unsigned DiagID = Diags.getCustomDiagID(
1026           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1027                                     "expected target description '%1'");
1028       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1029     }
1030   }
1031 }
1032 
1033 static const char* getSectionNameForBitcode(const Triple &T) {
1034   switch (T.getObjectFormat()) {
1035   case Triple::MachO:
1036     return "__LLVM,__bitcode";
1037   case Triple::COFF:
1038   case Triple::ELF:
1039   case Triple::Wasm:
1040   case Triple::UnknownObjectFormat:
1041     return ".llvmbc";
1042   }
1043   llvm_unreachable("Unimplemented ObjectFormatType");
1044 }
1045 
1046 static const char* getSectionNameForCommandline(const Triple &T) {
1047   switch (T.getObjectFormat()) {
1048   case Triple::MachO:
1049     return "__LLVM,__cmdline";
1050   case Triple::COFF:
1051   case Triple::ELF:
1052   case Triple::Wasm:
1053   case Triple::UnknownObjectFormat:
1054     return ".llvmcmd";
1055   }
1056   llvm_unreachable("Unimplemented ObjectFormatType");
1057 }
1058 
1059 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1060 // __LLVM,__bitcode section.
1061 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1062                          llvm::MemoryBufferRef Buf) {
1063   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1064     return;
1065 
1066   // Save llvm.compiler.used and remote it.
1067   SmallVector<Constant*, 2> UsedArray;
1068   SmallSet<GlobalValue*, 4> UsedGlobals;
1069   Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1070   GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1071   for (auto *GV : UsedGlobals) {
1072     if (GV->getName() != "llvm.embedded.module" &&
1073         GV->getName() != "llvm.cmdline")
1074       UsedArray.push_back(
1075           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1076   }
1077   if (Used)
1078     Used->eraseFromParent();
1079 
1080   // Embed the bitcode for the llvm module.
1081   std::string Data;
1082   ArrayRef<uint8_t> ModuleData;
1083   Triple T(M->getTargetTriple());
1084   // Create a constant that contains the bitcode.
1085   // In case of embedding a marker, ignore the input Buf and use the empty
1086   // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1087   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1088     if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1089                    (const unsigned char *)Buf.getBufferEnd())) {
1090       // If the input is LLVM Assembly, bitcode is produced by serializing
1091       // the module. Use-lists order need to be perserved in this case.
1092       llvm::raw_string_ostream OS(Data);
1093       llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
1094       ModuleData =
1095           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1096     } else
1097       // If the input is LLVM bitcode, write the input byte stream directly.
1098       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1099                                      Buf.getBufferSize());
1100   }
1101   llvm::Constant *ModuleConstant =
1102       llvm::ConstantDataArray::get(M->getContext(), ModuleData);
1103   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1104       *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
1105       ModuleConstant);
1106   GV->setSection(getSectionNameForBitcode(T));
1107   UsedArray.push_back(
1108       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1109   if (llvm::GlobalVariable *Old =
1110           M->getGlobalVariable("llvm.embedded.module", true)) {
1111     assert(Old->hasOneUse() &&
1112            "llvm.embedded.module can only be used once in llvm.compiler.used");
1113     GV->takeName(Old);
1114     Old->eraseFromParent();
1115   } else {
1116     GV->setName("llvm.embedded.module");
1117   }
1118 
1119   // Skip if only bitcode needs to be embedded.
1120   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1121     // Embed command-line options.
1122     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
1123                               CGOpts.CmdArgs.size());
1124     llvm::Constant *CmdConstant =
1125       llvm::ConstantDataArray::get(M->getContext(), CmdData);
1126     GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1127                                   llvm::GlobalValue::PrivateLinkage,
1128                                   CmdConstant);
1129     GV->setSection(getSectionNameForCommandline(T));
1130     UsedArray.push_back(
1131         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1132     if (llvm::GlobalVariable *Old =
1133             M->getGlobalVariable("llvm.cmdline", true)) {
1134       assert(Old->hasOneUse() &&
1135              "llvm.cmdline can only be used once in llvm.compiler.used");
1136       GV->takeName(Old);
1137       Old->eraseFromParent();
1138     } else {
1139       GV->setName("llvm.cmdline");
1140     }
1141   }
1142 
1143   if (UsedArray.empty())
1144     return;
1145 
1146   // Recreate llvm.compiler.used.
1147   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1148   auto *NewUsed = new GlobalVariable(
1149       *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1150       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1151   NewUsed->setSection("llvm.metadata");
1152 }
1153