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