LLVMTargetMachine.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. //===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
  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. // This file implements the LLVMTargetMachine class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Target/TargetMachine.h"
  14. #include "llvm/Analysis/Passes.h"
  15. #include "llvm/CodeGen/AsmPrinter.h"
  16. #include "llvm/CodeGen/BasicTTIImpl.h"
  17. #include "llvm/CodeGen/MachineFunctionAnalysis.h"
  18. #include "llvm/CodeGen/MachineModuleInfo.h"
  19. #include "llvm/CodeGen/Passes.h"
  20. #include "llvm/IR/IRPrintingPasses.h"
  21. #include "llvm/IR/LegacyPassManager.h"
  22. #include "llvm/IR/Verifier.h"
  23. #include "llvm/MC/MCAsmInfo.h"
  24. #include "llvm/MC/MCContext.h"
  25. #include "llvm/MC/MCInstrInfo.h"
  26. #include "llvm/MC/MCStreamer.h"
  27. #include "llvm/MC/MCSubtargetInfo.h"
  28. #include "llvm/Support/CommandLine.h"
  29. #include "llvm/Support/ErrorHandling.h"
  30. #include "llvm/Support/FormattedStream.h"
  31. #include "llvm/Support/TargetRegistry.h"
  32. #include "llvm/Target/TargetLoweringObjectFile.h"
  33. #include "llvm/Target/TargetOptions.h"
  34. #include "llvm/Transforms/Scalar.h"
  35. using namespace llvm;
  36. // Enable or disable FastISel. Both options are needed, because
  37. // FastISel is enabled by default with -fast, and we wish to be
  38. // able to enable or disable fast-isel independently from -O0.
  39. static cl::opt<cl::boolOrDefault>
  40. EnableFastISelOption("fast-isel", cl::Hidden,
  41. cl::desc("Enable the \"fast\" instruction selector"));
  42. void LLVMTargetMachine::initAsmInfo() {
  43. MRI = TheTarget.createMCRegInfo(getTargetTriple().str());
  44. MII = TheTarget.createMCInstrInfo();
  45. // FIXME: Having an MCSubtargetInfo on the target machine is a hack due
  46. // to some backends having subtarget feature dependent module level
  47. // code generation. This is similar to the hack in the AsmPrinter for
  48. // module level assembly etc.
  49. STI = TheTarget.createMCSubtargetInfo(getTargetTriple().str(), getTargetCPU(),
  50. getTargetFeatureString());
  51. MCAsmInfo *TmpAsmInfo =
  52. TheTarget.createMCAsmInfo(*MRI, getTargetTriple().str());
  53. // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
  54. // and if the old one gets included then MCAsmInfo will be NULL and
  55. // we'll crash later.
  56. // Provide the user with a useful error message about what's wrong.
  57. assert(TmpAsmInfo && "MCAsmInfo not initialized. "
  58. "Make sure you include the correct TargetSelect.h"
  59. "and that InitializeAllTargetMCs() is being invoked!");
  60. if (Options.DisableIntegratedAS)
  61. TmpAsmInfo->setUseIntegratedAssembler(false);
  62. if (Options.CompressDebugSections)
  63. TmpAsmInfo->setCompressDebugSections(true);
  64. AsmInfo = TmpAsmInfo;
  65. }
  66. LLVMTargetMachine::LLVMTargetMachine(const Target &T,
  67. StringRef DataLayoutString,
  68. const Triple &TT, StringRef CPU,
  69. StringRef FS, TargetOptions Options,
  70. Reloc::Model RM, CodeModel::Model CM,
  71. CodeGenOpt::Level OL)
  72. : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) {
  73. CodeGenInfo = T.createMCCodeGenInfo(TT.str(), RM, CM, OL);
  74. }
  75. TargetIRAnalysis LLVMTargetMachine::getTargetIRAnalysis() {
  76. return TargetIRAnalysis([this](Function &F) {
  77. return TargetTransformInfo(BasicTTIImpl(this, F));
  78. });
  79. }
  80. /// addPassesToX helper drives creation and initialization of TargetPassConfig.
  81. static MCContext *
  82. addPassesToGenerateCode(LLVMTargetMachine *TM, PassManagerBase &PM,
  83. bool DisableVerify, AnalysisID StartBefore,
  84. AnalysisID StartAfter, AnalysisID StopAfter,
  85. MachineFunctionInitializer *MFInitializer = nullptr) {
  86. // Add internal analysis passes from the target machine.
  87. PM.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
  88. // Targets may override createPassConfig to provide a target-specific
  89. // subclass.
  90. TargetPassConfig *PassConfig = TM->createPassConfig(PM);
  91. PassConfig->setStartStopPasses(StartBefore, StartAfter, StopAfter);
  92. // Set PassConfig options provided by TargetMachine.
  93. PassConfig->setDisableVerify(DisableVerify);
  94. PM.add(PassConfig);
  95. PassConfig->addIRPasses();
  96. PassConfig->addCodeGenPrepare();
  97. PassConfig->addPassesToHandleExceptions();
  98. PassConfig->addISelPrepare();
  99. // Install a MachineModuleInfo class, which is an immutable pass that holds
  100. // all the per-module stuff we're generating, including MCContext.
  101. MachineModuleInfo *MMI = new MachineModuleInfo(
  102. *TM->getMCAsmInfo(), *TM->getMCRegisterInfo(), TM->getObjFileLowering());
  103. PM.add(MMI);
  104. // Set up a MachineFunction for the rest of CodeGen to work on.
  105. PM.add(new MachineFunctionAnalysis(*TM, MFInitializer));
  106. // Enable FastISel with -fast, but allow that to be overridden.
  107. if (EnableFastISelOption == cl::BOU_TRUE ||
  108. (TM->getOptLevel() == CodeGenOpt::None &&
  109. EnableFastISelOption != cl::BOU_FALSE))
  110. TM->setFastISel(true);
  111. // Ask the target for an isel.
  112. if (PassConfig->addInstSelector())
  113. return nullptr;
  114. PassConfig->addMachinePasses();
  115. PassConfig->setInitialized();
  116. return &MMI->getContext();
  117. }
  118. bool LLVMTargetMachine::addPassesToEmitFile(
  119. PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileType,
  120. bool DisableVerify, AnalysisID StartBefore, AnalysisID StartAfter,
  121. AnalysisID StopAfter, MachineFunctionInitializer *MFInitializer) {
  122. // Add common CodeGen passes.
  123. MCContext *Context =
  124. addPassesToGenerateCode(this, PM, DisableVerify, StartBefore, StartAfter,
  125. StopAfter, MFInitializer);
  126. if (!Context)
  127. return true;
  128. if (StopAfter) {
  129. PM.add(createPrintMIRPass(outs()));
  130. return false;
  131. }
  132. if (Options.MCOptions.MCSaveTempLabels)
  133. Context->setAllowTemporaryLabels(false);
  134. const MCSubtargetInfo &STI = *getMCSubtargetInfo();
  135. const MCAsmInfo &MAI = *getMCAsmInfo();
  136. const MCRegisterInfo &MRI = *getMCRegisterInfo();
  137. const MCInstrInfo &MII = *getMCInstrInfo();
  138. std::unique_ptr<MCStreamer> AsmStreamer;
  139. switch (FileType) {
  140. case CGFT_AssemblyFile: {
  141. MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(
  142. getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI);
  143. // Create a code emitter if asked to show the encoding.
  144. MCCodeEmitter *MCE = nullptr;
  145. if (Options.MCOptions.ShowMCEncoding)
  146. MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
  147. MCAsmBackend *MAB =
  148. getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU);
  149. auto FOut = llvm::make_unique<formatted_raw_ostream>(Out);
  150. MCStreamer *S = getTarget().createAsmStreamer(
  151. *Context, std::move(FOut), Options.MCOptions.AsmVerbose,
  152. Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB,
  153. Options.MCOptions.ShowMCInst);
  154. AsmStreamer.reset(S);
  155. break;
  156. }
  157. case CGFT_ObjectFile: {
  158. // Create the code emitter for the target if it exists. If not, .o file
  159. // emission fails.
  160. MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
  161. MCAsmBackend *MAB =
  162. getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU);
  163. if (!MCE || !MAB)
  164. return true;
  165. // Don't waste memory on names of temp labels.
  166. Context->setUseNamesOnTempLabels(false);
  167. Triple T(getTargetTriple().str());
  168. AsmStreamer.reset(getTarget().createMCObjectStreamer(
  169. T, *Context, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
  170. /*DWARFMustBeAtTheEnd*/ true));
  171. break;
  172. }
  173. case CGFT_Null:
  174. // The Null output is intended for use for performance analysis and testing,
  175. // not real users.
  176. AsmStreamer.reset(getTarget().createNullStreamer(*Context));
  177. break;
  178. }
  179. // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
  180. FunctionPass *Printer =
  181. getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
  182. if (!Printer)
  183. return true;
  184. PM.add(Printer);
  185. return false;
  186. }
  187. /// addPassesToEmitMC - Add passes to the specified pass manager to get
  188. /// machine code emitted with the MCJIT. This method returns true if machine
  189. /// code is not supported. It fills the MCContext Ctx pointer which can be
  190. /// used to build custom MCStreamer.
  191. ///
  192. bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
  193. raw_pwrite_stream &Out,
  194. bool DisableVerify) {
  195. // Add common CodeGen passes.
  196. Ctx = addPassesToGenerateCode(this, PM, DisableVerify, nullptr, nullptr,
  197. nullptr);
  198. if (!Ctx)
  199. return true;
  200. if (Options.MCOptions.MCSaveTempLabels)
  201. Ctx->setAllowTemporaryLabels(false);
  202. // Create the code emitter for the target if it exists. If not, .o file
  203. // emission fails.
  204. const MCRegisterInfo &MRI = *getMCRegisterInfo();
  205. MCCodeEmitter *MCE =
  206. getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx);
  207. MCAsmBackend *MAB =
  208. getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU);
  209. if (!MCE || !MAB)
  210. return true;
  211. const Triple &T = getTargetTriple();
  212. const MCSubtargetInfo &STI = *getMCSubtargetInfo();
  213. std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
  214. T, *Ctx, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
  215. /*DWARFMustBeAtTheEnd*/ true));
  216. // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
  217. FunctionPass *Printer =
  218. getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
  219. if (!Printer)
  220. return true;
  221. PM.add(Printer);
  222. return false; // success!
  223. }