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