LLVM API Documentation

LLVMTargetMachine.cpp
Go to the documentation of this file.
00001 //===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the LLVMTargetMachine class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Target/TargetMachine.h"
00015 #include "llvm/ADT/OwningPtr.h"
00016 #include "llvm/Assembly/PrintModulePass.h"
00017 #include "llvm/CodeGen/AsmPrinter.h"
00018 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
00019 #include "llvm/CodeGen/MachineModuleInfo.h"
00020 #include "llvm/CodeGen/Passes.h"
00021 #include "llvm/MC/MCAsmInfo.h"
00022 #include "llvm/MC/MCContext.h"
00023 #include "llvm/MC/MCInstrInfo.h"
00024 #include "llvm/MC/MCStreamer.h"
00025 #include "llvm/MC/MCSubtargetInfo.h"
00026 #include "llvm/PassManager.h"
00027 #include "llvm/Support/CommandLine.h"
00028 #include "llvm/Support/ErrorHandling.h"
00029 #include "llvm/Support/FormattedStream.h"
00030 #include "llvm/Support/TargetRegistry.h"
00031 #include "llvm/Target/TargetInstrInfo.h"
00032 #include "llvm/Target/TargetLowering.h"
00033 #include "llvm/Target/TargetLoweringObjectFile.h"
00034 #include "llvm/Target/TargetOptions.h"
00035 #include "llvm/Target/TargetRegisterInfo.h"
00036 #include "llvm/Target/TargetSubtargetInfo.h"
00037 #include "llvm/Transforms/Scalar.h"
00038 using namespace llvm;
00039 
00040 // Enable or disable FastISel. Both options are needed, because
00041 // FastISel is enabled by default with -fast, and we wish to be
00042 // able to enable or disable fast-isel independently from -O0.
00043 static cl::opt<cl::boolOrDefault>
00044 EnableFastISelOption("fast-isel", cl::Hidden,
00045   cl::desc("Enable the \"fast\" instruction selector"));
00046 
00047 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
00048     cl::desc("Show encoding in .s output"));
00049 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
00050     cl::desc("Show instruction structure in .s output"));
00051 
00052 static cl::opt<cl::boolOrDefault>
00053 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
00054            cl::init(cl::BOU_UNSET));
00055 
00056 static bool getVerboseAsm() {
00057   switch (AsmVerbose) {
00058   case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
00059   case cl::BOU_TRUE:  return true;
00060   case cl::BOU_FALSE: return false;
00061   }
00062   llvm_unreachable("Invalid verbose asm state");
00063 }
00064 
00065 void LLVMTargetMachine::initAsmInfo() {
00066   AsmInfo = TheTarget.createMCAsmInfo(*getRegisterInfo(), TargetTriple);
00067   // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
00068   // and if the old one gets included then MCAsmInfo will be NULL and
00069   // we'll crash later.
00070   // Provide the user with a useful error message about what's wrong.
00071   assert(AsmInfo && "MCAsmInfo not initialized."
00072          "Make sure you include the correct TargetSelect.h"
00073          "and that InitializeAllTargetMCs() is being invoked!");
00074 }
00075 
00076 LLVMTargetMachine::LLVMTargetMachine(const Target &T, StringRef Triple,
00077                                      StringRef CPU, StringRef FS,
00078                                      TargetOptions Options,
00079                                      Reloc::Model RM, CodeModel::Model CM,
00080                                      CodeGenOpt::Level OL)
00081   : TargetMachine(T, Triple, CPU, FS, Options) {
00082   CodeGenInfo = T.createMCCodeGenInfo(Triple, RM, CM, OL);
00083 }
00084 
00085 void LLVMTargetMachine::addAnalysisPasses(PassManagerBase &PM) {
00086   PM.add(createBasicTargetTransformInfoPass(getTargetLowering()));
00087 }
00088 
00089 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
00090 static MCContext *addPassesToGenerateCode(LLVMTargetMachine *TM,
00091                                           PassManagerBase &PM,
00092                                           bool DisableVerify,
00093                                           AnalysisID StartAfter,
00094                                           AnalysisID StopAfter) {
00095   // Targets may override createPassConfig to provide a target-specific sublass.
00096   TargetPassConfig *PassConfig = TM->createPassConfig(PM);
00097   PassConfig->setStartStopPasses(StartAfter, StopAfter);
00098 
00099   // Set PassConfig options provided by TargetMachine.
00100   PassConfig->setDisableVerify(DisableVerify);
00101 
00102   PM.add(PassConfig);
00103 
00104   PassConfig->addIRPasses();
00105 
00106   PassConfig->addCodeGenPrepare();
00107 
00108   PassConfig->addPassesToHandleExceptions();
00109 
00110   PassConfig->addISelPrepare();
00111 
00112   // Install a MachineModuleInfo class, which is an immutable pass that holds
00113   // all the per-module stuff we're generating, including MCContext.
00114   MachineModuleInfo *MMI =
00115     new MachineModuleInfo(*TM->getMCAsmInfo(), *TM->getRegisterInfo(),
00116                           &TM->getTargetLowering()->getObjFileLowering());
00117   PM.add(MMI);
00118   MCContext *Context = &MMI->getContext(); // Return the MCContext by-ref.
00119 
00120   // Set up a MachineFunction for the rest of CodeGen to work on.
00121   PM.add(new MachineFunctionAnalysis(*TM));
00122 
00123   // Enable FastISel with -fast, but allow that to be overridden.
00124   if (EnableFastISelOption == cl::BOU_TRUE ||
00125       (TM->getOptLevel() == CodeGenOpt::None &&
00126        EnableFastISelOption != cl::BOU_FALSE))
00127     TM->setFastISel(true);
00128 
00129   // Ask the target for an isel.
00130   if (PassConfig->addInstSelector())
00131     return NULL;
00132 
00133   PassConfig->addMachinePasses();
00134 
00135   PassConfig->setInitialized();
00136 
00137   return Context;
00138 }
00139 
00140 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
00141                                             formatted_raw_ostream &Out,
00142                                             CodeGenFileType FileType,
00143                                             bool DisableVerify,
00144                                             AnalysisID StartAfter,
00145                                             AnalysisID StopAfter) {
00146   // Add common CodeGen passes.
00147   MCContext *Context = addPassesToGenerateCode(this, PM, DisableVerify,
00148                                                StartAfter, StopAfter);
00149   if (!Context)
00150     return true;
00151 
00152   if (StopAfter) {
00153     // FIXME: The intent is that this should eventually write out a YAML file,
00154     // containing the LLVM IR, the machine-level IR (when stopping after a
00155     // machine-level pass), and whatever other information is needed to
00156     // deserialize the code and resume compilation.  For now, just write the
00157     // LLVM IR.
00158     PM.add(createPrintModulePass(&Out));
00159     return false;
00160   }
00161 
00162   if (hasMCSaveTempLabels())
00163     Context->setAllowTemporaryLabels(false);
00164 
00165   const MCAsmInfo &MAI = *getMCAsmInfo();
00166   const MCRegisterInfo &MRI = *getRegisterInfo();
00167   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
00168   OwningPtr<MCStreamer> AsmStreamer;
00169 
00170   switch (FileType) {
00171   case CGFT_AssemblyFile: {
00172     MCInstPrinter *InstPrinter =
00173       getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI,
00174                                       *getInstrInfo(),
00175                                       Context->getRegisterInfo(), STI);
00176 
00177     // Create a code emitter if asked to show the encoding.
00178     MCCodeEmitter *MCE = 0;
00179     MCAsmBackend *MAB = 0;
00180     if (ShowMCEncoding) {
00181       const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
00182       MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), MRI, STI,
00183                                             *Context);
00184       MAB = getTarget().createMCAsmBackend(getTargetTriple(), TargetCPU);
00185     }
00186 
00187     MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
00188                                                   getVerboseAsm(),
00189                                                   hasMCUseLoc(),
00190                                                   hasMCUseCFI(),
00191                                                   hasMCUseDwarfDirectory(),
00192                                                   InstPrinter,
00193                                                   MCE, MAB,
00194                                                   ShowMCInst);
00195     AsmStreamer.reset(S);
00196     break;
00197   }
00198   case CGFT_ObjectFile: {
00199     // Create the code emitter for the target if it exists.  If not, .o file
00200     // emission fails.
00201     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), MRI,
00202                                                          STI, *Context);
00203     MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple(),
00204                                                        TargetCPU);
00205     if (MCE == 0 || MAB == 0)
00206       return true;
00207 
00208     AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(),
00209                                                          *Context, *MAB, Out,
00210                                                          MCE, hasMCRelaxAll(),
00211                                                          hasMCNoExecStack()));
00212     AsmStreamer.get()->setAutoInitSections(true);
00213     break;
00214   }
00215   case CGFT_Null:
00216     // The Null output is intended for use for performance analysis and testing,
00217     // not real users.
00218     AsmStreamer.reset(createNullStreamer(*Context));
00219     break;
00220   }
00221 
00222   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
00223   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
00224   if (Printer == 0)
00225     return true;
00226 
00227   // If successful, createAsmPrinter took ownership of AsmStreamer.
00228   AsmStreamer.take();
00229 
00230   PM.add(Printer);
00231 
00232   return false;
00233 }
00234 
00235 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
00236 /// get machine code emitted.  This uses a JITCodeEmitter object to handle
00237 /// actually outputting the machine code and resolving things like the address
00238 /// of functions.  This method should returns true if machine code emission is
00239 /// not supported.
00240 ///
00241 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
00242                                                    JITCodeEmitter &JCE,
00243                                                    bool DisableVerify) {
00244   // Add common CodeGen passes.
00245   MCContext *Context = addPassesToGenerateCode(this, PM, DisableVerify, 0, 0);
00246   if (!Context)
00247     return true;
00248 
00249   addCodeEmitter(PM, JCE);
00250 
00251   return false; // success!
00252 }
00253 
00254 /// addPassesToEmitMC - Add passes to the specified pass manager to get
00255 /// machine code emitted with the MCJIT. This method returns true if machine
00256 /// code is not supported. It fills the MCContext Ctx pointer which can be
00257 /// used to build custom MCStreamer.
00258 ///
00259 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
00260                                           MCContext *&Ctx,
00261                                           raw_ostream &Out,
00262                                           bool DisableVerify) {
00263   // Add common CodeGen passes.
00264   Ctx = addPassesToGenerateCode(this, PM, DisableVerify, 0, 0);
00265   if (!Ctx)
00266     return true;
00267 
00268   if (hasMCSaveTempLabels())
00269     Ctx->setAllowTemporaryLabels(false);
00270 
00271   // Create the code emitter for the target if it exists.  If not, .o file
00272   // emission fails.
00273   const MCRegisterInfo &MRI = *getRegisterInfo();
00274   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
00275   MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), MRI,
00276                                                        STI, *Ctx);
00277   MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple(), TargetCPU);
00278   if (MCE == 0 || MAB == 0)
00279     return true;
00280 
00281   OwningPtr<MCStreamer> AsmStreamer;
00282   AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), *Ctx,
00283                                                        *MAB, Out, MCE,
00284                                                        hasMCRelaxAll(),
00285                                                        hasMCNoExecStack()));
00286   AsmStreamer.get()->InitSections();
00287 
00288   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
00289   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
00290   if (Printer == 0)
00291     return true;
00292 
00293   // If successful, createAsmPrinter took ownership of AsmStreamer.
00294   AsmStreamer.take();
00295 
00296   PM.add(Printer);
00297 
00298   return false; // success!
00299 }