LLVMTargetMachine.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. //===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the LLVMTargetMachine class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Analysis/Passes.h"
  13. #include "llvm/CodeGen/AsmPrinter.h"
  14. #include "llvm/CodeGen/BasicTTIImpl.h"
  15. #include "llvm/CodeGen/MachineModuleInfo.h"
  16. #include "llvm/CodeGen/Passes.h"
  17. #include "llvm/CodeGen/TargetPassConfig.h"
  18. #include "llvm/IR/LegacyPassManager.h"
  19. #include "llvm/MC/MCAsmBackend.h"
  20. #include "llvm/MC/MCAsmInfo.h"
  21. #include "llvm/MC/MCCodeEmitter.h"
  22. #include "llvm/MC/MCContext.h"
  23. #include "llvm/MC/MCInstrInfo.h"
  24. #include "llvm/MC/MCObjectWriter.h"
  25. #include "llvm/MC/MCStreamer.h"
  26. #include "llvm/MC/MCSubtargetInfo.h"
  27. #include "llvm/Support/CommandLine.h"
  28. #include "llvm/Support/ErrorHandling.h"
  29. #include "llvm/Support/FormattedStream.h"
  30. #include "llvm/Support/TargetRegistry.h"
  31. #include "llvm/Target/TargetLoweringObjectFile.h"
  32. #include "llvm/Target/TargetMachine.h"
  33. #include "llvm/Target/TargetOptions.h"
  34. using namespace llvm;
  35. static cl::opt<bool> EnableTrapUnreachable("trap-unreachable",
  36. cl::Hidden, cl::ZeroOrMore, cl::init(false),
  37. cl::desc("Enable generating trap for unreachable"));
  38. void LLVMTargetMachine::initAsmInfo() {
  39. MRI.reset(TheTarget.createMCRegInfo(getTargetTriple().str()));
  40. assert(MRI && "Unable to create reg info");
  41. MII.reset(TheTarget.createMCInstrInfo());
  42. assert(MII && "Unable to create instruction info");
  43. // FIXME: Having an MCSubtargetInfo on the target machine is a hack due
  44. // to some backends having subtarget feature dependent module level
  45. // code generation. This is similar to the hack in the AsmPrinter for
  46. // module level assembly etc.
  47. STI.reset(TheTarget.createMCSubtargetInfo(
  48. getTargetTriple().str(), getTargetCPU(), getTargetFeatureString()));
  49. assert(STI && "Unable to create subtarget info");
  50. MCAsmInfo *TmpAsmInfo = TheTarget.createMCAsmInfo(
  51. *MRI, getTargetTriple().str(), Options.MCOptions);
  52. // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
  53. // and if the old one gets included then MCAsmInfo will be NULL and
  54. // we'll crash later.
  55. // Provide the user with a useful error message about what's wrong.
  56. assert(TmpAsmInfo && "MCAsmInfo not initialized. "
  57. "Make sure you include the correct TargetSelect.h"
  58. "and that InitializeAllTargetMCs() is being invoked!");
  59. if (Options.BinutilsVersion.first > 0)
  60. TmpAsmInfo->setBinutilsVersion(Options.BinutilsVersion);
  61. if (Options.DisableIntegratedAS)
  62. TmpAsmInfo->setUseIntegratedAssembler(false);
  63. TmpAsmInfo->setPreserveAsmComments(Options.MCOptions.PreserveAsmComments);
  64. TmpAsmInfo->setCompressDebugSections(Options.CompressDebugSections);
  65. TmpAsmInfo->setRelaxELFRelocations(Options.RelaxELFRelocations);
  66. if (Options.ExceptionModel != ExceptionHandling::None)
  67. TmpAsmInfo->setExceptionsType(Options.ExceptionModel);
  68. AsmInfo.reset(TmpAsmInfo);
  69. }
  70. LLVMTargetMachine::LLVMTargetMachine(const Target &T,
  71. StringRef DataLayoutString,
  72. const Triple &TT, StringRef CPU,
  73. StringRef FS, const TargetOptions &Options,
  74. Reloc::Model RM, CodeModel::Model CM,
  75. CodeGenOpt::Level OL)
  76. : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) {
  77. this->RM = RM;
  78. this->CMModel = CM;
  79. this->OptLevel = OL;
  80. if (EnableTrapUnreachable)
  81. this->Options.TrapUnreachable = true;
  82. }
  83. TargetTransformInfo
  84. LLVMTargetMachine::getTargetTransformInfo(const Function &F) {
  85. return TargetTransformInfo(BasicTTIImpl(this, F));
  86. }
  87. /// addPassesToX helper drives creation and initialization of TargetPassConfig.
  88. static TargetPassConfig *
  89. addPassesToGenerateCode(LLVMTargetMachine &TM, PassManagerBase &PM,
  90. bool DisableVerify,
  91. MachineModuleInfoWrapperPass &MMIWP) {
  92. // Targets may override createPassConfig to provide a target-specific
  93. // subclass.
  94. TargetPassConfig *PassConfig = TM.createPassConfig(PM);
  95. // Set PassConfig options provided by TargetMachine.
  96. PassConfig->setDisableVerify(DisableVerify);
  97. PM.add(PassConfig);
  98. PM.add(&MMIWP);
  99. if (PassConfig->addISelPasses())
  100. return nullptr;
  101. PassConfig->addMachinePasses();
  102. PassConfig->setInitialized();
  103. return PassConfig;
  104. }
  105. bool LLVMTargetMachine::addAsmPrinter(PassManagerBase &PM,
  106. raw_pwrite_stream &Out,
  107. raw_pwrite_stream *DwoOut,
  108. CodeGenFileType FileType,
  109. MCContext &Context) {
  110. Expected<std::unique_ptr<MCStreamer>> MCStreamerOrErr =
  111. createMCStreamer(Out, DwoOut, FileType, Context);
  112. if (auto Err = MCStreamerOrErr.takeError())
  113. return true;
  114. // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
  115. FunctionPass *Printer =
  116. getTarget().createAsmPrinter(*this, std::move(*MCStreamerOrErr));
  117. if (!Printer)
  118. return true;
  119. PM.add(Printer);
  120. return false;
  121. }
  122. Expected<std::unique_ptr<MCStreamer>> LLVMTargetMachine::createMCStreamer(
  123. raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
  124. MCContext &Context) {
  125. if (Options.MCOptions.MCSaveTempLabels)
  126. Context.setAllowTemporaryLabels(false);
  127. const MCSubtargetInfo &STI = *getMCSubtargetInfo();
  128. const MCAsmInfo &MAI = *getMCAsmInfo();
  129. const MCRegisterInfo &MRI = *getMCRegisterInfo();
  130. const MCInstrInfo &MII = *getMCInstrInfo();
  131. std::unique_ptr<MCStreamer> AsmStreamer;
  132. switch (FileType) {
  133. case CGFT_AssemblyFile: {
  134. MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(
  135. getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI);
  136. // Create a code emitter if asked to show the encoding.
  137. std::unique_ptr<MCCodeEmitter> MCE;
  138. if (Options.MCOptions.ShowMCEncoding)
  139. MCE.reset(getTarget().createMCCodeEmitter(MII, MRI, Context));
  140. std::unique_ptr<MCAsmBackend> MAB(
  141. getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions));
  142. auto FOut = std::make_unique<formatted_raw_ostream>(Out);
  143. MCStreamer *S = getTarget().createAsmStreamer(
  144. Context, std::move(FOut), Options.MCOptions.AsmVerbose,
  145. Options.MCOptions.MCUseDwarfDirectory, InstPrinter, std::move(MCE),
  146. std::move(MAB), Options.MCOptions.ShowMCInst);
  147. AsmStreamer.reset(S);
  148. break;
  149. }
  150. case CGFT_ObjectFile: {
  151. // Create the code emitter for the target if it exists. If not, .o file
  152. // emission fails.
  153. MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, Context);
  154. if (!MCE)
  155. return make_error<StringError>("createMCCodeEmitter failed",
  156. inconvertibleErrorCode());
  157. MCAsmBackend *MAB =
  158. getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions);
  159. if (!MAB)
  160. return make_error<StringError>("createMCAsmBackend failed",
  161. inconvertibleErrorCode());
  162. Triple T(getTargetTriple().str());
  163. AsmStreamer.reset(getTarget().createMCObjectStreamer(
  164. T, Context, std::unique_ptr<MCAsmBackend>(MAB),
  165. DwoOut ? MAB->createDwoObjectWriter(Out, *DwoOut)
  166. : MAB->createObjectWriter(Out),
  167. std::unique_ptr<MCCodeEmitter>(MCE), STI, Options.MCOptions.MCRelaxAll,
  168. Options.MCOptions.MCIncrementalLinkerCompatible,
  169. /*DWARFMustBeAtTheEnd*/ true));
  170. break;
  171. }
  172. case CGFT_Null:
  173. // The Null output is intended for use for performance analysis and testing,
  174. // not real users.
  175. AsmStreamer.reset(getTarget().createNullStreamer(Context));
  176. break;
  177. }
  178. return std::move(AsmStreamer);
  179. }
  180. bool LLVMTargetMachine::addPassesToEmitFile(
  181. PassManagerBase &PM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut,
  182. CodeGenFileType FileType, bool DisableVerify,
  183. MachineModuleInfoWrapperPass *MMIWP) {
  184. // Add common CodeGen passes.
  185. if (!MMIWP)
  186. MMIWP = new MachineModuleInfoWrapperPass(this);
  187. TargetPassConfig *PassConfig =
  188. addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP);
  189. if (!PassConfig)
  190. return true;
  191. if (TargetPassConfig::willCompleteCodeGenPipeline()) {
  192. if (addAsmPrinter(PM, Out, DwoOut, FileType, MMIWP->getMMI().getContext()))
  193. return true;
  194. } else {
  195. // MIR printing is redundant with -filetype=null.
  196. if (FileType != CGFT_Null)
  197. PM.add(createPrintMIRPass(Out));
  198. }
  199. PM.add(createFreeMachineFunctionPass());
  200. return false;
  201. }
  202. /// addPassesToEmitMC - Add passes to the specified pass manager to get
  203. /// machine code emitted with the MCJIT. This method returns true if machine
  204. /// code is not supported. It fills the MCContext Ctx pointer which can be
  205. /// used to build custom MCStreamer.
  206. ///
  207. bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
  208. raw_pwrite_stream &Out,
  209. bool DisableVerify) {
  210. // Add common CodeGen passes.
  211. MachineModuleInfoWrapperPass *MMIWP = new MachineModuleInfoWrapperPass(this);
  212. TargetPassConfig *PassConfig =
  213. addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP);
  214. if (!PassConfig)
  215. return true;
  216. assert(TargetPassConfig::willCompleteCodeGenPipeline() &&
  217. "Cannot emit MC with limited codegen pipeline");
  218. Ctx = &MMIWP->getMMI().getContext();
  219. if (Options.MCOptions.MCSaveTempLabels)
  220. Ctx->setAllowTemporaryLabels(false);
  221. // Create the code emitter for the target if it exists. If not, .o file
  222. // emission fails.
  223. const MCSubtargetInfo &STI = *getMCSubtargetInfo();
  224. const MCRegisterInfo &MRI = *getMCRegisterInfo();
  225. MCCodeEmitter *MCE =
  226. getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx);
  227. MCAsmBackend *MAB =
  228. getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions);
  229. if (!MCE || !MAB)
  230. return true;
  231. const Triple &T = getTargetTriple();
  232. std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
  233. T, *Ctx, std::unique_ptr<MCAsmBackend>(MAB), MAB->createObjectWriter(Out),
  234. std::unique_ptr<MCCodeEmitter>(MCE), STI, Options.MCOptions.MCRelaxAll,
  235. Options.MCOptions.MCIncrementalLinkerCompatible,
  236. /*DWARFMustBeAtTheEnd*/ true));
  237. // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
  238. FunctionPass *Printer =
  239. getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
  240. if (!Printer)
  241. return true;
  242. PM.add(Printer);
  243. PM.add(createFreeMachineFunctionPass());
  244. return false; // success!
  245. }