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