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/Analysis/TargetLibraryInfo.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/Bitcode/BitcodeWriterPass.h"
22 #include "llvm/CodeGen/RegAllocRegistry.h"
23 #include "llvm/CodeGen/SchedulerRegistry.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/FunctionInfo.h"
26 #include "llvm/IR/IRPrintingPasses.h"
27 #include "llvm/IR/LegacyPassManager.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Verifier.h"
30 #include "llvm/MC/SubtargetFeature.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/PrettyStackTrace.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/Timer.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
39 #include "llvm/Transforms/IPO.h"
40 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
41 #include "llvm/Transforms/Instrumentation.h"
42 #include "llvm/Transforms/ObjCARC.h"
43 #include "llvm/Transforms/Scalar.h"
44 #include "llvm/Transforms/Utils/SymbolRewriter.h"
45 #include <memory>
46 using namespace clang;
47 using namespace llvm;
48 
49 namespace {
50 
51 class EmitAssemblyHelper {
52   DiagnosticsEngine &Diags;
53   const CodeGenOptions &CodeGenOpts;
54   const clang::TargetOptions &TargetOpts;
55   const LangOptions &LangOpts;
56   Module *TheModule;
57   std::unique_ptr<FunctionInfoIndex> FunctionIndex;
58 
59   Timer CodeGenerationTime;
60 
61   mutable legacy::PassManager *CodeGenPasses;
62   mutable legacy::PassManager *PerModulePasses;
63   mutable legacy::FunctionPassManager *PerFunctionPasses;
64 
65 private:
getTargetIRAnalysis() const66   TargetIRAnalysis getTargetIRAnalysis() const {
67     if (TM)
68       return TM->getTargetIRAnalysis();
69 
70     return TargetIRAnalysis();
71   }
72 
getCodeGenPasses() const73   legacy::PassManager *getCodeGenPasses() const {
74     if (!CodeGenPasses) {
75       CodeGenPasses = new legacy::PassManager();
76       CodeGenPasses->add(
77           createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
78     }
79     return CodeGenPasses;
80   }
81 
getPerModulePasses() const82   legacy::PassManager *getPerModulePasses() const {
83     if (!PerModulePasses) {
84       PerModulePasses = new legacy::PassManager();
85       PerModulePasses->add(
86           createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
87     }
88     return PerModulePasses;
89   }
90 
getPerFunctionPasses() const91   legacy::FunctionPassManager *getPerFunctionPasses() const {
92     if (!PerFunctionPasses) {
93       PerFunctionPasses = new legacy::FunctionPassManager(TheModule);
94       PerFunctionPasses->add(
95           createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
96     }
97     return PerFunctionPasses;
98   }
99 
100   void CreatePasses();
101 
102   /// Generates the TargetMachine.
103   /// Returns Null if it is unable to create the target machine.
104   /// Some of our clang tests specify triples which are not built
105   /// into clang. This is okay because these tests check the generated
106   /// IR, and they require DataLayout which depends on the triple.
107   /// In this case, we allow this method to fail and not report an error.
108   /// When MustCreateTM is used, we print an error if we are unable to load
109   /// the requested target.
110   TargetMachine *CreateTargetMachine(bool MustCreateTM);
111 
112   /// Add passes necessary to emit assembly or LLVM IR.
113   ///
114   /// \return True on success.
115   bool AddEmitPasses(BackendAction Action, raw_pwrite_stream &OS);
116 
117 public:
EmitAssemblyHelper(DiagnosticsEngine & _Diags,const CodeGenOptions & CGOpts,const clang::TargetOptions & TOpts,const LangOptions & LOpts,Module * M,std::unique_ptr<FunctionInfoIndex> Index)118   EmitAssemblyHelper(DiagnosticsEngine &_Diags, const CodeGenOptions &CGOpts,
119                      const clang::TargetOptions &TOpts,
120                      const LangOptions &LOpts, Module *M,
121                      std::unique_ptr<FunctionInfoIndex> Index)
122       : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
123         TheModule(M), FunctionIndex(std::move(Index)),
124         CodeGenerationTime("Code Generation Time"), CodeGenPasses(nullptr),
125         PerModulePasses(nullptr), PerFunctionPasses(nullptr) {}
126 
~EmitAssemblyHelper()127   ~EmitAssemblyHelper() {
128     delete CodeGenPasses;
129     delete PerModulePasses;
130     delete PerFunctionPasses;
131     if (CodeGenOpts.DisableFree)
132       BuryPointer(std::move(TM));
133   }
134 
135   std::unique_ptr<TargetMachine> TM;
136 
137   void EmitAssembly(BackendAction Action, raw_pwrite_stream *OS);
138 };
139 
140 // We need this wrapper to access LangOpts and CGOpts from extension functions
141 // that we add to the PassManagerBuilder.
142 class PassManagerBuilderWrapper : public PassManagerBuilder {
143 public:
PassManagerBuilderWrapper(const CodeGenOptions & CGOpts,const LangOptions & LangOpts)144   PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
145                             const LangOptions &LangOpts)
146       : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
getCGOpts() const147   const CodeGenOptions &getCGOpts() const { return CGOpts; }
getLangOpts() const148   const LangOptions &getLangOpts() const { return LangOpts; }
149 private:
150   const CodeGenOptions &CGOpts;
151   const LangOptions &LangOpts;
152 };
153 
154 }
155 
addObjCARCAPElimPass(const PassManagerBuilder & Builder,PassManagerBase & PM)156 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
157   if (Builder.OptLevel > 0)
158     PM.add(createObjCARCAPElimPass());
159 }
160 
addObjCARCExpandPass(const PassManagerBuilder & Builder,PassManagerBase & PM)161 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
162   if (Builder.OptLevel > 0)
163     PM.add(createObjCARCExpandPass());
164 }
165 
addObjCARCOptPass(const PassManagerBuilder & Builder,PassManagerBase & PM)166 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
167   if (Builder.OptLevel > 0)
168     PM.add(createObjCARCOptPass());
169 }
170 
addAddDiscriminatorsPass(const PassManagerBuilder & Builder,legacy::PassManagerBase & PM)171 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
172                                      legacy::PassManagerBase &PM) {
173   PM.add(createAddDiscriminatorsPass());
174 }
175 
addBoundsCheckingPass(const PassManagerBuilder & Builder,legacy::PassManagerBase & PM)176 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
177                                     legacy::PassManagerBase &PM) {
178   PM.add(createBoundsCheckingPass());
179 }
180 
addSanitizerCoveragePass(const PassManagerBuilder & Builder,legacy::PassManagerBase & PM)181 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
182                                      legacy::PassManagerBase &PM) {
183   const PassManagerBuilderWrapper &BuilderWrapper =
184       static_cast<const PassManagerBuilderWrapper&>(Builder);
185   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
186   SanitizerCoverageOptions Opts;
187   Opts.CoverageType =
188       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
189   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
190   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
191   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
192   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
193   PM.add(createSanitizerCoverageModulePass(Opts));
194 }
195 
addAddressSanitizerPasses(const PassManagerBuilder & Builder,legacy::PassManagerBase & PM)196 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
197                                       legacy::PassManagerBase &PM) {
198   const PassManagerBuilderWrapper &BuilderWrapper =
199       static_cast<const PassManagerBuilderWrapper&>(Builder);
200   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
201   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
202   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/false, Recover));
203   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/false, Recover));
204 }
205 
addKernelAddressSanitizerPasses(const PassManagerBuilder & Builder,legacy::PassManagerBase & PM)206 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
207                                             legacy::PassManagerBase &PM) {
208   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/true,
209                                             /*Recover*/true));
210   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true,
211                                           /*Recover*/true));
212 }
213 
addMemorySanitizerPass(const PassManagerBuilder & Builder,legacy::PassManagerBase & PM)214 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
215                                    legacy::PassManagerBase &PM) {
216   const PassManagerBuilderWrapper &BuilderWrapper =
217       static_cast<const PassManagerBuilderWrapper&>(Builder);
218   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
219   PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins));
220 
221   // MemorySanitizer inserts complex instrumentation that mostly follows
222   // the logic of the original code, but operates on "shadow" values.
223   // It can benefit from re-running some general purpose optimization passes.
224   if (Builder.OptLevel > 0) {
225     PM.add(createEarlyCSEPass());
226     PM.add(createReassociatePass());
227     PM.add(createLICMPass());
228     PM.add(createGVNPass());
229     PM.add(createInstructionCombiningPass());
230     PM.add(createDeadStoreEliminationPass());
231   }
232 }
233 
addThreadSanitizerPass(const PassManagerBuilder & Builder,legacy::PassManagerBase & PM)234 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
235                                    legacy::PassManagerBase &PM) {
236   PM.add(createThreadSanitizerPass());
237 }
238 
addDataFlowSanitizerPass(const PassManagerBuilder & Builder,legacy::PassManagerBase & PM)239 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
240                                      legacy::PassManagerBase &PM) {
241   const PassManagerBuilderWrapper &BuilderWrapper =
242       static_cast<const PassManagerBuilderWrapper&>(Builder);
243   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
244   PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
245 }
246 
createTLII(llvm::Triple & TargetTriple,const CodeGenOptions & CodeGenOpts)247 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
248                                          const CodeGenOptions &CodeGenOpts) {
249   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
250   if (!CodeGenOpts.SimplifyLibCalls)
251     TLII->disableAllFunctions();
252 
253   switch (CodeGenOpts.getVecLib()) {
254   case CodeGenOptions::Accelerate:
255     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
256     break;
257   default:
258     break;
259   }
260   return TLII;
261 }
262 
addSymbolRewriterPass(const CodeGenOptions & Opts,legacy::PassManager * MPM)263 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
264                                   legacy::PassManager *MPM) {
265   llvm::SymbolRewriter::RewriteDescriptorList DL;
266 
267   llvm::SymbolRewriter::RewriteMapParser MapParser;
268   for (const auto &MapFile : Opts.RewriteMapFiles)
269     MapParser.parse(MapFile, &DL);
270 
271   MPM->add(createRewriteSymbolsPass(DL));
272 }
273 
CreatePasses()274 void EmitAssemblyHelper::CreatePasses() {
275   if (CodeGenOpts.DisableLLVMPasses)
276     return;
277 
278   unsigned OptLevel = CodeGenOpts.OptimizationLevel;
279   CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
280 
281   // Handle disabling of LLVM optimization, where we want to preserve the
282   // internal module before any optimization.
283   if (CodeGenOpts.DisableLLVMOpts) {
284     OptLevel = 0;
285     Inlining = CodeGenOpts.NoInlining;
286   }
287 
288   PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
289 
290   // Figure out TargetLibraryInfo.
291   Triple TargetTriple(TheModule->getTargetTriple());
292   PMBuilder.LibraryInfo = createTLII(TargetTriple, CodeGenOpts);
293 
294   switch (Inlining) {
295   case CodeGenOptions::NoInlining:
296     break;
297   case CodeGenOptions::NormalInlining: {
298     PMBuilder.Inliner =
299         createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize);
300     break;
301   }
302   case CodeGenOptions::OnlyAlwaysInlining:
303     // Respect always_inline.
304     if (OptLevel == 0)
305       // Do not insert lifetime intrinsics at -O0.
306       PMBuilder.Inliner = createAlwaysInlinerPass(false);
307     else
308       PMBuilder.Inliner = createAlwaysInlinerPass();
309     break;
310   }
311 
312   PMBuilder.OptLevel = OptLevel;
313   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
314   PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
315   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
316   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
317 
318   PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
319   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
320   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
321   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
322   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
323 
324   legacy::PassManager *MPM = getPerModulePasses();
325 
326   // If we are performing a ThinLTO importing compile, invoke the LTO
327   // pipeline and pass down the in-memory function index.
328   if (!CodeGenOpts.ThinLTOIndexFile.empty()) {
329     assert(FunctionIndex && "Expected non-empty function index");
330     PMBuilder.FunctionIndex = FunctionIndex.get();
331     PMBuilder.populateLTOPassManager(*MPM);
332     return;
333   }
334 
335   PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
336                          addAddDiscriminatorsPass);
337 
338   // In ObjC ARC mode, add the main ARC optimization passes.
339   if (LangOpts.ObjCAutoRefCount) {
340     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
341                            addObjCARCExpandPass);
342     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
343                            addObjCARCAPElimPass);
344     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
345                            addObjCARCOptPass);
346   }
347 
348   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
349     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
350                            addBoundsCheckingPass);
351     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
352                            addBoundsCheckingPass);
353   }
354 
355   if (CodeGenOpts.SanitizeCoverageType ||
356       CodeGenOpts.SanitizeCoverageIndirectCalls ||
357       CodeGenOpts.SanitizeCoverageTraceCmp) {
358     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
359                            addSanitizerCoveragePass);
360     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
361                            addSanitizerCoveragePass);
362   }
363 
364   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
365     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
366                            addAddressSanitizerPasses);
367     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
368                            addAddressSanitizerPasses);
369   }
370 
371   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
372     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
373                            addKernelAddressSanitizerPasses);
374     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
375                            addKernelAddressSanitizerPasses);
376   }
377 
378   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
379     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
380                            addMemorySanitizerPass);
381     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
382                            addMemorySanitizerPass);
383   }
384 
385   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
386     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
387                            addThreadSanitizerPass);
388     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
389                            addThreadSanitizerPass);
390   }
391 
392   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
393     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
394                            addDataFlowSanitizerPass);
395     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
396                            addDataFlowSanitizerPass);
397   }
398 
399   // Set up the per-function pass manager.
400   legacy::FunctionPassManager *FPM = getPerFunctionPasses();
401   if (CodeGenOpts.VerifyModule)
402     FPM->add(createVerifierPass());
403   PMBuilder.populateFunctionPassManager(*FPM);
404 
405   // Set up the per-module pass manager.
406   if (!CodeGenOpts.RewriteMapFiles.empty())
407     addSymbolRewriterPass(CodeGenOpts, MPM);
408 
409   if (!CodeGenOpts.DisableGCov &&
410       (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
411     // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
412     // LLVM's -default-gcov-version flag is set to something invalid.
413     GCOVOptions Options;
414     Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
415     Options.EmitData = CodeGenOpts.EmitGcovArcs;
416     memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
417     Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
418     Options.NoRedZone = CodeGenOpts.DisableRedZone;
419     Options.FunctionNamesInData =
420         !CodeGenOpts.CoverageNoFunctionNamesInData;
421     Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
422     MPM->add(createGCOVProfilerPass(Options));
423     if (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
424       MPM->add(createStripSymbolsPass(true));
425   }
426 
427   if (CodeGenOpts.ProfileInstrGenerate) {
428     InstrProfOptions Options;
429     Options.NoRedZone = CodeGenOpts.DisableRedZone;
430     Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
431     MPM->add(createInstrProfilingPass(Options));
432   }
433 
434   if (!CodeGenOpts.SampleProfileFile.empty())
435     MPM->add(createSampleProfileLoaderPass(CodeGenOpts.SampleProfileFile));
436 
437   PMBuilder.populateModulePassManager(*MPM);
438 }
439 
CreateTargetMachine(bool MustCreateTM)440 TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
441   // Create the TargetMachine for generating code.
442   std::string Error;
443   std::string Triple = TheModule->getTargetTriple();
444   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
445   if (!TheTarget) {
446     if (MustCreateTM)
447       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
448     return nullptr;
449   }
450 
451   unsigned CodeModel =
452     llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
453       .Case("small", llvm::CodeModel::Small)
454       .Case("kernel", llvm::CodeModel::Kernel)
455       .Case("medium", llvm::CodeModel::Medium)
456       .Case("large", llvm::CodeModel::Large)
457       .Case("default", llvm::CodeModel::Default)
458       .Default(~0u);
459   assert(CodeModel != ~0u && "invalid code model!");
460   llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
461 
462   SmallVector<const char *, 16> BackendArgs;
463   BackendArgs.push_back("clang"); // Fake program name.
464   if (!CodeGenOpts.DebugPass.empty()) {
465     BackendArgs.push_back("-debug-pass");
466     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
467   }
468   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
469     BackendArgs.push_back("-limit-float-precision");
470     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
471   }
472   for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
473     BackendArgs.push_back(BackendOption.c_str());
474   BackendArgs.push_back(nullptr);
475   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
476                                     BackendArgs.data());
477 
478   std::string FeaturesStr =
479       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
480 
481   // Keep this synced with the equivalent code in tools/driver/cc1as_main.cpp.
482   llvm::Reloc::Model RM = llvm::Reloc::Default;
483   if (CodeGenOpts.RelocationModel == "static") {
484     RM = llvm::Reloc::Static;
485   } else if (CodeGenOpts.RelocationModel == "pic") {
486     RM = llvm::Reloc::PIC_;
487   } else {
488     assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
489            "Invalid PIC model!");
490     RM = llvm::Reloc::DynamicNoPIC;
491   }
492 
493   CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
494   switch (CodeGenOpts.OptimizationLevel) {
495   default: break;
496   case 0: OptLevel = CodeGenOpt::None; break;
497   case 3: OptLevel = CodeGenOpt::Aggressive; break;
498   }
499 
500   llvm::TargetOptions Options;
501 
502   if (!TargetOpts.Reciprocals.empty())
503     Options.Reciprocals = TargetRecip(TargetOpts.Reciprocals);
504 
505   Options.ThreadModel =
506     llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
507       .Case("posix", llvm::ThreadModel::POSIX)
508       .Case("single", llvm::ThreadModel::Single);
509 
510   // Set float ABI type.
511   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
512           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
513          "Invalid Floating Point ABI!");
514   Options.FloatABIType =
515       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
516           .Case("soft", llvm::FloatABI::Soft)
517           .Case("softfp", llvm::FloatABI::Soft)
518           .Case("hard", llvm::FloatABI::Hard)
519           .Default(llvm::FloatABI::Default);
520 
521   // Set FP fusion mode.
522   switch (CodeGenOpts.getFPContractMode()) {
523   case CodeGenOptions::FPC_Off:
524     Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
525     break;
526   case CodeGenOptions::FPC_On:
527     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
528     break;
529   case CodeGenOptions::FPC_Fast:
530     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
531     break;
532   }
533 
534   Options.UseInitArray = CodeGenOpts.UseInitArray;
535   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
536   Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
537 
538   // Set EABI version.
539   Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(CodeGenOpts.EABIVersion)
540                             .Case("4", llvm::EABI::EABI4)
541                             .Case("5", llvm::EABI::EABI5)
542                             .Case("gnu", llvm::EABI::GNU)
543                             .Default(llvm::EABI::Default);
544 
545   Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
546   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
547   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
548   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
549   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
550   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
551   Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
552   Options.FunctionSections = CodeGenOpts.FunctionSections;
553   Options.DataSections = CodeGenOpts.DataSections;
554   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
555   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
556   switch (CodeGenOpts.getDebuggerTuning()) {
557   case CodeGenOptions::DebuggerKindGDB:
558     Options.DebuggerTuning = llvm::DebuggerKind::GDB;
559     break;
560   case CodeGenOptions::DebuggerKindLLDB:
561     Options.DebuggerTuning = llvm::DebuggerKind::LLDB;
562     break;
563   case CodeGenOptions::DebuggerKindSCE:
564     Options.DebuggerTuning = llvm::DebuggerKind::SCE;
565     break;
566   default:
567     break;
568   }
569 
570   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
571   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
572   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
573   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
574   Options.MCOptions.MCIncrementalLinkerCompatible =
575       CodeGenOpts.IncrementalLinkerCompatible;
576   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
577   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
578   Options.MCOptions.ABIName = TargetOpts.ABI;
579 
580   TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
581                                                      FeaturesStr, Options,
582                                                      RM, CM, OptLevel);
583 
584   return TM;
585 }
586 
AddEmitPasses(BackendAction Action,raw_pwrite_stream & OS)587 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
588                                        raw_pwrite_stream &OS) {
589 
590   // Create the code generator passes.
591   legacy::PassManager *PM = getCodeGenPasses();
592 
593   // Add LibraryInfo.
594   llvm::Triple TargetTriple(TheModule->getTargetTriple());
595   std::unique_ptr<TargetLibraryInfoImpl> TLII(
596       createTLII(TargetTriple, CodeGenOpts));
597   PM->add(new TargetLibraryInfoWrapperPass(*TLII));
598 
599   // Normal mode, emit a .s or .o file by running the code generator. Note,
600   // this also adds codegenerator level optimization passes.
601   TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
602   if (Action == Backend_EmitObj)
603     CGFT = TargetMachine::CGFT_ObjectFile;
604   else if (Action == Backend_EmitMCNull)
605     CGFT = TargetMachine::CGFT_Null;
606   else
607     assert(Action == Backend_EmitAssembly && "Invalid action!");
608 
609   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
610   // "codegen" passes so that it isn't run multiple times when there is
611   // inlining happening.
612   if (CodeGenOpts.OptimizationLevel > 0)
613     PM->add(createObjCARCContractPass());
614 
615   if (TM->addPassesToEmitFile(*PM, OS, CGFT,
616                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
617     Diags.Report(diag::err_fe_unable_to_interface_with_target);
618     return false;
619   }
620 
621   return true;
622 }
623 
EmitAssembly(BackendAction Action,raw_pwrite_stream * OS)624 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
625                                       raw_pwrite_stream *OS) {
626   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
627 
628   bool UsesCodeGen = (Action != Backend_EmitNothing &&
629                       Action != Backend_EmitBC &&
630                       Action != Backend_EmitLL);
631   if (!TM)
632     TM.reset(CreateTargetMachine(UsesCodeGen));
633 
634   if (UsesCodeGen && !TM)
635     return;
636   if (TM)
637     TheModule->setDataLayout(TM->createDataLayout());
638   CreatePasses();
639 
640   switch (Action) {
641   case Backend_EmitNothing:
642     break;
643 
644   case Backend_EmitBC:
645     getPerModulePasses()->add(createBitcodeWriterPass(
646         *OS, CodeGenOpts.EmitLLVMUseLists, CodeGenOpts.EmitFunctionSummary));
647     break;
648 
649   case Backend_EmitLL:
650     getPerModulePasses()->add(
651         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
652     break;
653 
654   default:
655     if (!AddEmitPasses(Action, *OS))
656       return;
657   }
658 
659   // Before executing passes, print the final values of the LLVM options.
660   cl::PrintOptionValues();
661 
662   // Run passes. For now we do all passes at once, but eventually we
663   // would like to have the option of streaming code generation.
664 
665   if (PerFunctionPasses) {
666     PrettyStackTraceString CrashInfo("Per-function optimization");
667 
668     PerFunctionPasses->doInitialization();
669     for (Function &F : *TheModule)
670       if (!F.isDeclaration())
671         PerFunctionPasses->run(F);
672     PerFunctionPasses->doFinalization();
673   }
674 
675   if (PerModulePasses) {
676     PrettyStackTraceString CrashInfo("Per-module optimization passes");
677     PerModulePasses->run(*TheModule);
678   }
679 
680   if (CodeGenPasses) {
681     PrettyStackTraceString CrashInfo("Code generation");
682     CodeGenPasses->run(*TheModule);
683   }
684 }
685 
EmitBackendOutput(DiagnosticsEngine & Diags,const CodeGenOptions & CGOpts,const clang::TargetOptions & TOpts,const LangOptions & LOpts,StringRef TDesc,Module * M,BackendAction Action,raw_pwrite_stream * OS,std::unique_ptr<FunctionInfoIndex> Index)686 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
687                               const CodeGenOptions &CGOpts,
688                               const clang::TargetOptions &TOpts,
689                               const LangOptions &LOpts, StringRef TDesc,
690                               Module *M, BackendAction Action,
691                               raw_pwrite_stream *OS,
692                               std::unique_ptr<FunctionInfoIndex> Index) {
693   EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M,
694                                std::move(Index));
695 
696   AsmHelper.EmitAssembly(Action, OS);
697 
698   // If an optional clang TargetInfo description string was passed in, use it to
699   // verify the LLVM TargetMachine's DataLayout.
700   if (AsmHelper.TM && !TDesc.empty()) {
701     std::string DLDesc = M->getDataLayout().getStringRepresentation();
702     if (DLDesc != TDesc) {
703       unsigned DiagID = Diags.getCustomDiagID(
704           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
705                                     "expected target description '%1'");
706       Diags.Report(DiagID) << DLDesc << TDesc;
707     }
708   }
709 }
710