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