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 "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Bitcode/BitcodeWriterPass.h"
23 #include "llvm/Bitcode/ReaderWriter.h"
24 #include "llvm/CodeGen/RegAllocRegistry.h"
25 #include "llvm/CodeGen/SchedulerRegistry.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/ModuleSummaryIndex.h"
28 #include "llvm/IR/IRPrintingPasses.h"
29 #include "llvm/IR/LegacyPassManager.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Verifier.h"
32 #include "llvm/MC/SubtargetFeature.h"
33 #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/PrettyStackTrace.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/Timer.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
42 #include "llvm/Transforms/IPO.h"
43 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
44 #include "llvm/Transforms/Instrumentation.h"
45 #include "llvm/Transforms/ObjCARC.h"
46 #include "llvm/Transforms/Scalar.h"
47 #include "llvm/Transforms/Scalar/GVN.h"
48 #include "llvm/Transforms/Utils/SymbolRewriter.h"
49 #include <memory>
50 using namespace clang;
51 using namespace llvm;
52 
53 namespace {
54 
55 class EmitAssemblyHelper {
56   DiagnosticsEngine &Diags;
57   const CodeGenOptions &CodeGenOpts;
58   const clang::TargetOptions &TargetOpts;
59   const LangOptions &LangOpts;
60   Module *TheModule;
61 
62   Timer CodeGenerationTime;
63 
64   mutable legacy::PassManager *CodeGenPasses;
65   mutable legacy::PassManager *PerModulePasses;
66   mutable legacy::FunctionPassManager *PerFunctionPasses;
67 
68 private:
69   TargetIRAnalysis getTargetIRAnalysis() const {
70     if (TM)
71       return TM->getTargetIRAnalysis();
72 
73     return TargetIRAnalysis();
74   }
75 
76   legacy::PassManager *getCodeGenPasses() const {
77     if (!CodeGenPasses) {
78       CodeGenPasses = new legacy::PassManager();
79       CodeGenPasses->add(
80           createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
81     }
82     return CodeGenPasses;
83   }
84 
85   legacy::PassManager *getPerModulePasses() const {
86     if (!PerModulePasses) {
87       PerModulePasses = new legacy::PassManager();
88       PerModulePasses->add(
89           createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
90     }
91     return PerModulePasses;
92   }
93 
94   legacy::FunctionPassManager *getPerFunctionPasses() const {
95     if (!PerFunctionPasses) {
96       PerFunctionPasses = new legacy::FunctionPassManager(TheModule);
97       PerFunctionPasses->add(
98           createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
99     }
100     return PerFunctionPasses;
101   }
102 
103   /// Set LLVM command line options passed through -backend-option.
104   void setCommandLineOpts();
105 
106   void CreatePasses(ModuleSummaryIndex *ModuleSummary);
107 
108   /// Generates the TargetMachine.
109   /// Returns Null if it is unable to create the target machine.
110   /// Some of our clang tests specify triples which are not built
111   /// into clang. This is okay because these tests check the generated
112   /// IR, and they require DataLayout which depends on the triple.
113   /// In this case, we allow this method to fail and not report an error.
114   /// When MustCreateTM is used, we print an error if we are unable to load
115   /// the requested target.
116   TargetMachine *CreateTargetMachine(bool MustCreateTM);
117 
118   /// Add passes necessary to emit assembly or LLVM IR.
119   ///
120   /// \return True on success.
121   bool AddEmitPasses(BackendAction Action, raw_pwrite_stream &OS);
122 
123 public:
124   EmitAssemblyHelper(DiagnosticsEngine &_Diags, const CodeGenOptions &CGOpts,
125                      const clang::TargetOptions &TOpts,
126                      const LangOptions &LOpts, Module *M)
127       : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
128         TheModule(M), CodeGenerationTime("Code Generation Time"),
129         CodeGenPasses(nullptr), PerModulePasses(nullptr),
130         PerFunctionPasses(nullptr) {}
131 
132   ~EmitAssemblyHelper() {
133     delete CodeGenPasses;
134     delete PerModulePasses;
135     delete PerFunctionPasses;
136     if (CodeGenOpts.DisableFree)
137       BuryPointer(std::move(TM));
138   }
139 
140   std::unique_ptr<TargetMachine> TM;
141 
142   void EmitAssembly(BackendAction Action, raw_pwrite_stream *OS);
143 };
144 
145 // We need this wrapper to access LangOpts and CGOpts from extension functions
146 // that we add to the PassManagerBuilder.
147 class PassManagerBuilderWrapper : public PassManagerBuilder {
148 public:
149   PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
150                             const LangOptions &LangOpts)
151       : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
152   const CodeGenOptions &getCGOpts() const { return CGOpts; }
153   const LangOptions &getLangOpts() const { return LangOpts; }
154 private:
155   const CodeGenOptions &CGOpts;
156   const LangOptions &LangOpts;
157 };
158 
159 }
160 
161 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
162   if (Builder.OptLevel > 0)
163     PM.add(createObjCARCAPElimPass());
164 }
165 
166 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
167   if (Builder.OptLevel > 0)
168     PM.add(createObjCARCExpandPass());
169 }
170 
171 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
172   if (Builder.OptLevel > 0)
173     PM.add(createObjCARCOptPass());
174 }
175 
176 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
177                                      legacy::PassManagerBase &PM) {
178   PM.add(createAddDiscriminatorsPass());
179 }
180 
181 static void addCleanupPassesForSampleProfiler(
182     const PassManagerBuilder &Builder, legacy::PassManagerBase &PM) {
183   // instcombine is needed before sample profile annotation because it converts
184   // certain function calls to be inlinable. simplifycfg and sroa are needed
185   // before instcombine for necessary preparation. E.g. load store is eliminated
186   // properly so that instcombine will not introduce unecessary liverange.
187   PM.add(createCFGSimplificationPass());
188   PM.add(createSROAPass());
189   PM.add(createInstructionCombiningPass());
190 }
191 
192 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
193                                   legacy::PassManagerBase &PM) {
194   PM.add(createBoundsCheckingPass());
195 }
196 
197 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
198                                      legacy::PassManagerBase &PM) {
199   const PassManagerBuilderWrapper &BuilderWrapper =
200       static_cast<const PassManagerBuilderWrapper&>(Builder);
201   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
202   SanitizerCoverageOptions Opts;
203   Opts.CoverageType =
204       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
205   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
206   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
207   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
208   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
209   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
210   PM.add(createSanitizerCoverageModulePass(Opts));
211 }
212 
213 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
214                                       legacy::PassManagerBase &PM) {
215   const PassManagerBuilderWrapper &BuilderWrapper =
216       static_cast<const PassManagerBuilderWrapper&>(Builder);
217   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
218   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
219   bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
220   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
221                                             UseAfterScope));
222   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/false, Recover));
223 }
224 
225 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
226                                             legacy::PassManagerBase &PM) {
227   PM.add(createAddressSanitizerFunctionPass(
228       /*CompileKernel*/ true,
229       /*Recover*/ true, /*UseAfterScope*/ false));
230   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true,
231                                           /*Recover*/true));
232 }
233 
234 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
235                                    legacy::PassManagerBase &PM) {
236   const PassManagerBuilderWrapper &BuilderWrapper =
237       static_cast<const PassManagerBuilderWrapper&>(Builder);
238   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
239   PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins));
240 
241   // MemorySanitizer inserts complex instrumentation that mostly follows
242   // the logic of the original code, but operates on "shadow" values.
243   // It can benefit from re-running some general purpose optimization passes.
244   if (Builder.OptLevel > 0) {
245     PM.add(createEarlyCSEPass());
246     PM.add(createReassociatePass());
247     PM.add(createLICMPass());
248     PM.add(createGVNPass());
249     PM.add(createInstructionCombiningPass());
250     PM.add(createDeadStoreEliminationPass());
251   }
252 }
253 
254 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
255                                    legacy::PassManagerBase &PM) {
256   PM.add(createThreadSanitizerPass());
257 }
258 
259 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
260                                      legacy::PassManagerBase &PM) {
261   const PassManagerBuilderWrapper &BuilderWrapper =
262       static_cast<const PassManagerBuilderWrapper&>(Builder);
263   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
264   PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
265 }
266 
267 static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
268                                        legacy::PassManagerBase &PM) {
269   const PassManagerBuilderWrapper &BuilderWrapper =
270       static_cast<const PassManagerBuilderWrapper&>(Builder);
271   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
272   EfficiencySanitizerOptions Opts;
273   if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
274     Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
275   else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet))
276     Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet;
277   PM.add(createEfficiencySanitizerPass(Opts));
278 }
279 
280 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
281                                          const CodeGenOptions &CodeGenOpts) {
282   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
283   if (!CodeGenOpts.SimplifyLibCalls)
284     TLII->disableAllFunctions();
285   else {
286     // Disable individual libc/libm calls in TargetLibraryInfo.
287     LibFunc::Func F;
288     for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
289       if (TLII->getLibFunc(FuncName, F))
290         TLII->setUnavailable(F);
291   }
292 
293   switch (CodeGenOpts.getVecLib()) {
294   case CodeGenOptions::Accelerate:
295     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
296     break;
297   default:
298     break;
299   }
300   return TLII;
301 }
302 
303 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
304                                   legacy::PassManager *MPM) {
305   llvm::SymbolRewriter::RewriteDescriptorList DL;
306 
307   llvm::SymbolRewriter::RewriteMapParser MapParser;
308   for (const auto &MapFile : Opts.RewriteMapFiles)
309     MapParser.parse(MapFile, &DL);
310 
311   MPM->add(createRewriteSymbolsPass(DL));
312 }
313 
314 void EmitAssemblyHelper::CreatePasses(ModuleSummaryIndex *ModuleSummary) {
315   if (CodeGenOpts.DisableLLVMPasses)
316     return;
317 
318   unsigned OptLevel = CodeGenOpts.OptimizationLevel;
319   CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
320 
321   // Handle disabling of LLVM optimization, where we want to preserve the
322   // internal module before any optimization.
323   if (CodeGenOpts.DisableLLVMOpts) {
324     OptLevel = 0;
325     Inlining = CodeGenOpts.NoInlining;
326   }
327 
328   PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
329 
330   // Figure out TargetLibraryInfo.
331   Triple TargetTriple(TheModule->getTargetTriple());
332   PMBuilder.LibraryInfo = createTLII(TargetTriple, CodeGenOpts);
333 
334   switch (Inlining) {
335   case CodeGenOptions::NoInlining:
336     break;
337   case CodeGenOptions::NormalInlining:
338   case CodeGenOptions::OnlyHintInlining: {
339     PMBuilder.Inliner =
340         createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize);
341     break;
342   }
343   case CodeGenOptions::OnlyAlwaysInlining:
344     // Respect always_inline.
345     if (OptLevel == 0)
346       // Do not insert lifetime intrinsics at -O0.
347       PMBuilder.Inliner = createAlwaysInlinerPass(false);
348     else
349       PMBuilder.Inliner = createAlwaysInlinerPass();
350     break;
351   }
352 
353   PMBuilder.OptLevel = OptLevel;
354   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
355   PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
356   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
357   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
358 
359   PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
360   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
361   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
362   PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
363   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
364   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
365 
366   legacy::PassManager *MPM = getPerModulePasses();
367 
368   // If we are performing a ThinLTO importing compile, invoke the LTO
369   // pipeline and pass down the in-memory module summary index.
370   if (ModuleSummary) {
371     PMBuilder.ModuleSummary = ModuleSummary;
372     PMBuilder.populateThinLTOPassManager(*MPM);
373     return;
374   }
375 
376   // Add target-specific passes that need to run as early as possible.
377   if (TM)
378     PMBuilder.addExtension(
379         PassManagerBuilder::EP_EarlyAsPossible,
380         [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {
381           TM->addEarlyAsPossiblePasses(PM);
382         });
383 
384   PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
385                          addAddDiscriminatorsPass);
386 
387   // In ObjC ARC mode, add the main ARC optimization passes.
388   if (LangOpts.ObjCAutoRefCount) {
389     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
390                            addObjCARCExpandPass);
391     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
392                            addObjCARCAPElimPass);
393     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
394                            addObjCARCOptPass);
395   }
396 
397   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
398     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
399                            addBoundsCheckingPass);
400     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
401                            addBoundsCheckingPass);
402   }
403 
404   if (CodeGenOpts.SanitizeCoverageType ||
405       CodeGenOpts.SanitizeCoverageIndirectCalls ||
406       CodeGenOpts.SanitizeCoverageTraceCmp) {
407     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
408                            addSanitizerCoveragePass);
409     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
410                            addSanitizerCoveragePass);
411   }
412 
413   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
414     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
415                            addAddressSanitizerPasses);
416     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
417                            addAddressSanitizerPasses);
418   }
419 
420   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
421     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
422                            addKernelAddressSanitizerPasses);
423     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
424                            addKernelAddressSanitizerPasses);
425   }
426 
427   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
428     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
429                            addMemorySanitizerPass);
430     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
431                            addMemorySanitizerPass);
432   }
433 
434   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
435     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
436                            addThreadSanitizerPass);
437     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
438                            addThreadSanitizerPass);
439   }
440 
441   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
442     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
443                            addDataFlowSanitizerPass);
444     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
445                            addDataFlowSanitizerPass);
446   }
447 
448   if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
449     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
450                            addEfficiencySanitizerPass);
451     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
452                            addEfficiencySanitizerPass);
453   }
454 
455   // Set up the per-function pass manager.
456   legacy::FunctionPassManager *FPM = getPerFunctionPasses();
457   if (CodeGenOpts.VerifyModule)
458     FPM->add(createVerifierPass());
459 
460   // Set up the per-module pass manager.
461   if (!CodeGenOpts.RewriteMapFiles.empty())
462     addSymbolRewriterPass(CodeGenOpts, MPM);
463 
464   if (!CodeGenOpts.DisableGCov &&
465       (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
466     // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
467     // LLVM's -default-gcov-version flag is set to something invalid.
468     GCOVOptions Options;
469     Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
470     Options.EmitData = CodeGenOpts.EmitGcovArcs;
471     memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
472     Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
473     Options.NoRedZone = CodeGenOpts.DisableRedZone;
474     Options.FunctionNamesInData =
475         !CodeGenOpts.CoverageNoFunctionNamesInData;
476     Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
477     MPM->add(createGCOVProfilerPass(Options));
478     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
479       MPM->add(createStripSymbolsPass(true));
480   }
481 
482   if (CodeGenOpts.hasProfileClangInstr()) {
483     InstrProfOptions Options;
484     Options.NoRedZone = CodeGenOpts.DisableRedZone;
485     Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
486     MPM->add(createInstrProfilingLegacyPass(Options));
487   }
488   if (CodeGenOpts.hasProfileIRInstr()) {
489     if (!CodeGenOpts.InstrProfileOutput.empty())
490       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
491     else
492       PMBuilder.PGOInstrGen = "default.profraw";
493   }
494   if (CodeGenOpts.hasProfileIRUse())
495     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
496 
497   if (!CodeGenOpts.SampleProfileFile.empty()) {
498     MPM->add(createPruneEHPass());
499     MPM->add(createSampleProfileLoaderPass(CodeGenOpts.SampleProfileFile));
500     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
501                            addCleanupPassesForSampleProfiler);
502   }
503 
504   PMBuilder.populateFunctionPassManager(*FPM);
505   PMBuilder.populateModulePassManager(*MPM);
506 }
507 
508 void EmitAssemblyHelper::setCommandLineOpts() {
509   SmallVector<const char *, 16> BackendArgs;
510   BackendArgs.push_back("clang"); // Fake program name.
511   if (!CodeGenOpts.DebugPass.empty()) {
512     BackendArgs.push_back("-debug-pass");
513     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
514   }
515   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
516     BackendArgs.push_back("-limit-float-precision");
517     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
518   }
519   for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
520     BackendArgs.push_back(BackendOption.c_str());
521   BackendArgs.push_back(nullptr);
522   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
523                                     BackendArgs.data());
524 }
525 
526 TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
527   // Create the TargetMachine for generating code.
528   std::string Error;
529   std::string Triple = TheModule->getTargetTriple();
530   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
531   if (!TheTarget) {
532     if (MustCreateTM)
533       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
534     return nullptr;
535   }
536 
537   unsigned CodeModel =
538     llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
539       .Case("small", llvm::CodeModel::Small)
540       .Case("kernel", llvm::CodeModel::Kernel)
541       .Case("medium", llvm::CodeModel::Medium)
542       .Case("large", llvm::CodeModel::Large)
543       .Case("default", llvm::CodeModel::Default)
544       .Default(~0u);
545   assert(CodeModel != ~0u && "invalid code model!");
546   llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
547 
548   std::string FeaturesStr =
549       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
550 
551   // Keep this synced with the equivalent code in tools/driver/cc1as_main.cpp.
552   llvm::Optional<llvm::Reloc::Model> RM;
553   if (CodeGenOpts.RelocationModel == "static") {
554     RM = llvm::Reloc::Static;
555   } else if (CodeGenOpts.RelocationModel == "pic") {
556     RM = llvm::Reloc::PIC_;
557   } else {
558     assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
559            "Invalid PIC model!");
560     RM = llvm::Reloc::DynamicNoPIC;
561   }
562 
563   CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
564   switch (CodeGenOpts.OptimizationLevel) {
565   default: break;
566   case 0: OptLevel = CodeGenOpt::None; break;
567   case 3: OptLevel = CodeGenOpt::Aggressive; break;
568   }
569 
570   llvm::TargetOptions Options;
571 
572   if (!TargetOpts.Reciprocals.empty())
573     Options.Reciprocals = TargetRecip(TargetOpts.Reciprocals);
574 
575   Options.ThreadModel =
576     llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
577       .Case("posix", llvm::ThreadModel::POSIX)
578       .Case("single", llvm::ThreadModel::Single);
579 
580   // Set float ABI type.
581   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
582           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
583          "Invalid Floating Point ABI!");
584   Options.FloatABIType =
585       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
586           .Case("soft", llvm::FloatABI::Soft)
587           .Case("softfp", llvm::FloatABI::Soft)
588           .Case("hard", llvm::FloatABI::Hard)
589           .Default(llvm::FloatABI::Default);
590 
591   // Set FP fusion mode.
592   switch (CodeGenOpts.getFPContractMode()) {
593   case CodeGenOptions::FPC_Off:
594     Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
595     break;
596   case CodeGenOptions::FPC_On:
597     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
598     break;
599   case CodeGenOptions::FPC_Fast:
600     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
601     break;
602   }
603 
604   Options.UseInitArray = CodeGenOpts.UseInitArray;
605   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
606   Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
607   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
608 
609   // Set EABI version.
610   Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion)
611                             .Case("4", llvm::EABI::EABI4)
612                             .Case("5", llvm::EABI::EABI5)
613                             .Case("gnu", llvm::EABI::GNU)
614                             .Default(llvm::EABI::Default);
615 
616   if (LangOpts.SjLjExceptions)
617     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
618 
619   Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
620   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
621   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
622   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
623   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
624   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
625   Options.FunctionSections = CodeGenOpts.FunctionSections;
626   Options.DataSections = CodeGenOpts.DataSections;
627   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
628   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
629   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
630 
631   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
632   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
633   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
634   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
635   Options.MCOptions.MCIncrementalLinkerCompatible =
636       CodeGenOpts.IncrementalLinkerCompatible;
637   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
638   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
639   Options.MCOptions.ABIName = TargetOpts.ABI;
640 
641   TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
642                                                      FeaturesStr, Options,
643                                                      RM, CM, OptLevel);
644 
645   return TM;
646 }
647 
648 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
649                                        raw_pwrite_stream &OS) {
650 
651   // Create the code generator passes.
652   legacy::PassManager *PM = getCodeGenPasses();
653 
654   // Add LibraryInfo.
655   llvm::Triple TargetTriple(TheModule->getTargetTriple());
656   std::unique_ptr<TargetLibraryInfoImpl> TLII(
657       createTLII(TargetTriple, CodeGenOpts));
658   PM->add(new TargetLibraryInfoWrapperPass(*TLII));
659 
660   // Normal mode, emit a .s or .o file by running the code generator. Note,
661   // this also adds codegenerator level optimization passes.
662   TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
663   if (Action == Backend_EmitObj)
664     CGFT = TargetMachine::CGFT_ObjectFile;
665   else if (Action == Backend_EmitMCNull)
666     CGFT = TargetMachine::CGFT_Null;
667   else
668     assert(Action == Backend_EmitAssembly && "Invalid action!");
669 
670   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
671   // "codegen" passes so that it isn't run multiple times when there is
672   // inlining happening.
673   if (CodeGenOpts.OptimizationLevel > 0)
674     PM->add(createObjCARCContractPass());
675 
676   if (TM->addPassesToEmitFile(*PM, OS, CGFT,
677                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
678     Diags.Report(diag::err_fe_unable_to_interface_with_target);
679     return false;
680   }
681 
682   return true;
683 }
684 
685 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
686                                       raw_pwrite_stream *OS) {
687   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
688 
689   setCommandLineOpts();
690 
691   bool UsesCodeGen = (Action != Backend_EmitNothing &&
692                       Action != Backend_EmitBC &&
693                       Action != Backend_EmitLL);
694   if (!TM)
695     TM.reset(CreateTargetMachine(UsesCodeGen));
696 
697   if (UsesCodeGen && !TM)
698     return;
699   if (TM)
700     TheModule->setDataLayout(TM->createDataLayout());
701 
702   // If we are performing a ThinLTO importing compile, load the function
703   // index into memory and pass it into CreatePasses, which will add it
704   // to the PassManagerBuilder and invoke LTO passes.
705   std::unique_ptr<ModuleSummaryIndex> ModuleSummary;
706   if (!CodeGenOpts.ThinLTOIndexFile.empty()) {
707     ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
708         llvm::getModuleSummaryIndexForFile(
709             CodeGenOpts.ThinLTOIndexFile, [&](const DiagnosticInfo &DI) {
710               TheModule->getContext().diagnose(DI);
711             });
712     if (std::error_code EC = IndexOrErr.getError()) {
713       std::string Error = EC.message();
714       errs() << "Error loading index file '" << CodeGenOpts.ThinLTOIndexFile
715              << "': " << Error << "\n";
716       return;
717     }
718     ModuleSummary = std::move(IndexOrErr.get());
719     assert(ModuleSummary && "Expected non-empty module summary index");
720   }
721 
722   CreatePasses(ModuleSummary.get());
723 
724   switch (Action) {
725   case Backend_EmitNothing:
726     break;
727 
728   case Backend_EmitBC:
729     getPerModulePasses()->add(createBitcodeWriterPass(
730         *OS, CodeGenOpts.EmitLLVMUseLists, CodeGenOpts.EmitSummaryIndex,
731         CodeGenOpts.EmitSummaryIndex));
732     break;
733 
734   case Backend_EmitLL:
735     getPerModulePasses()->add(
736         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
737     break;
738 
739   default:
740     if (!AddEmitPasses(Action, *OS))
741       return;
742   }
743 
744   // Before executing passes, print the final values of the LLVM options.
745   cl::PrintOptionValues();
746 
747   // Run passes. For now we do all passes at once, but eventually we
748   // would like to have the option of streaming code generation.
749 
750   if (PerFunctionPasses) {
751     PrettyStackTraceString CrashInfo("Per-function optimization");
752 
753     PerFunctionPasses->doInitialization();
754     for (Function &F : *TheModule)
755       if (!F.isDeclaration())
756         PerFunctionPasses->run(F);
757     PerFunctionPasses->doFinalization();
758   }
759 
760   if (PerModulePasses) {
761     PrettyStackTraceString CrashInfo("Per-module optimization passes");
762     PerModulePasses->run(*TheModule);
763   }
764 
765   if (CodeGenPasses) {
766     PrettyStackTraceString CrashInfo("Code generation");
767     CodeGenPasses->run(*TheModule);
768   }
769 }
770 
771 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
772                               const CodeGenOptions &CGOpts,
773                               const clang::TargetOptions &TOpts,
774                               const LangOptions &LOpts, const llvm::DataLayout &TDesc,
775                               Module *M, BackendAction Action,
776                               raw_pwrite_stream *OS) {
777   EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
778 
779   AsmHelper.EmitAssembly(Action, OS);
780 
781   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
782   // DataLayout.
783   if (AsmHelper.TM) {
784     std::string DLDesc = M->getDataLayout().getStringRepresentation();
785     if (DLDesc != TDesc.getStringRepresentation()) {
786       unsigned DiagID = Diags.getCustomDiagID(
787           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
788                                     "expected target description '%1'");
789       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
790     }
791   }
792 }
793 
794 static const char* getSectionNameForBitcode(const Triple &T) {
795   switch (T.getObjectFormat()) {
796   case Triple::MachO:
797     return "__LLVM,__bitcode";
798   case Triple::COFF:
799   case Triple::ELF:
800   case Triple::UnknownObjectFormat:
801     return ".llvmbc";
802   }
803   llvm_unreachable("Unimplemented ObjectFormatType");
804 }
805 
806 static const char* getSectionNameForCommandline(const Triple &T) {
807   switch (T.getObjectFormat()) {
808   case Triple::MachO:
809     return "__LLVM,__cmdline";
810   case Triple::COFF:
811   case Triple::ELF:
812   case Triple::UnknownObjectFormat:
813     return ".llvmcmd";
814   }
815   llvm_unreachable("Unimplemented ObjectFormatType");
816 }
817 
818 // With -fembed-bitcode, save a copy of the llvm IR as data in the
819 // __LLVM,__bitcode section.
820 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
821                          llvm::MemoryBufferRef Buf) {
822   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
823     return;
824 
825   // Save llvm.compiler.used and remote it.
826   SmallVector<Constant*, 2> UsedArray;
827   SmallSet<GlobalValue*, 4> UsedGlobals;
828   Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
829   GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
830   for (auto *GV : UsedGlobals) {
831     if (GV->getName() != "llvm.embedded.module" &&
832         GV->getName() != "llvm.cmdline")
833       UsedArray.push_back(
834           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
835   }
836   if (Used)
837     Used->eraseFromParent();
838 
839   // Embed the bitcode for the llvm module.
840   std::string Data;
841   ArrayRef<uint8_t> ModuleData;
842   Triple T(M->getTargetTriple());
843   // Create a constant that contains the bitcode.
844   // In case of embedding a marker, ignore the input Buf and use the empty
845   // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
846   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
847     if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
848                    (const unsigned char *)Buf.getBufferEnd())) {
849       // If the input is LLVM Assembly, bitcode is produced by serializing
850       // the module. Use-lists order need to be perserved in this case.
851       llvm::raw_string_ostream OS(Data);
852       llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
853       ModuleData =
854           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
855     } else
856       // If the input is LLVM bitcode, write the input byte stream directly.
857       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
858                                      Buf.getBufferSize());
859   }
860   llvm::Constant *ModuleConstant =
861       llvm::ConstantDataArray::get(M->getContext(), ModuleData);
862   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
863       *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
864       ModuleConstant);
865   GV->setSection(getSectionNameForBitcode(T));
866   UsedArray.push_back(
867       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
868   if (llvm::GlobalVariable *Old =
869           M->getGlobalVariable("llvm.embedded.module", true)) {
870     assert(Old->hasOneUse() &&
871            "llvm.embedded.module can only be used once in llvm.compiler.used");
872     GV->takeName(Old);
873     Old->eraseFromParent();
874   } else {
875     GV->setName("llvm.embedded.module");
876   }
877 
878   // Skip if only bitcode needs to be embedded.
879   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
880     // Embed command-line options.
881     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
882                               CGOpts.CmdArgs.size());
883     llvm::Constant *CmdConstant =
884       llvm::ConstantDataArray::get(M->getContext(), CmdData);
885     GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
886                                   llvm::GlobalValue::PrivateLinkage,
887                                   CmdConstant);
888     GV->setSection(getSectionNameForCommandline(T));
889     UsedArray.push_back(
890         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
891     if (llvm::GlobalVariable *Old =
892             M->getGlobalVariable("llvm.cmdline", true)) {
893       assert(Old->hasOneUse() &&
894              "llvm.cmdline can only be used once in llvm.compiler.used");
895       GV->takeName(Old);
896       Old->eraseFromParent();
897     } else {
898       GV->setName("llvm.cmdline");
899     }
900   }
901 
902   if (UsedArray.empty())
903     return;
904 
905   // Recreate llvm.compiler.used.
906   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
907   auto *NewUsed = new GlobalVariable(
908       *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
909       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
910   NewUsed->setSection("llvm.metadata");
911 }
912