Assembler.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. //===-- Assembler.cpp -------------------------------------------*- C++ -*-===//
  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. #include "Assembler.h"
  10. #include "Target.h"
  11. #include "llvm/CodeGen/GlobalISel/CallLowering.h"
  12. #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
  13. #include "llvm/CodeGen/MachineInstrBuilder.h"
  14. #include "llvm/CodeGen/MachineModuleInfo.h"
  15. #include "llvm/CodeGen/MachineRegisterInfo.h"
  16. #include "llvm/CodeGen/TargetInstrInfo.h"
  17. #include "llvm/CodeGen/TargetPassConfig.h"
  18. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  19. #include "llvm/ExecutionEngine/SectionMemoryManager.h"
  20. #include "llvm/IR/LegacyPassManager.h"
  21. #include "llvm/MC/MCInstrInfo.h"
  22. #include "llvm/Support/MemoryBuffer.h"
  23. namespace llvm {
  24. namespace exegesis {
  25. static constexpr const char ModuleID[] = "ExegesisInfoTest";
  26. static constexpr const char FunctionID[] = "foo";
  27. static std::vector<llvm::MCInst>
  28. generateSnippetSetupCode(const ExegesisTarget &ET,
  29. const llvm::MCSubtargetInfo *const MSI,
  30. const unsigned ScratchReg,
  31. llvm::ArrayRef<unsigned> ScratchRegisterCopies,
  32. llvm::ArrayRef<RegisterValue> RegisterInitialValues,
  33. bool &IsSnippetSetupComplete) {
  34. IsSnippetSetupComplete = true;
  35. std::vector<llvm::MCInst> Result;
  36. // Copy registers.
  37. for (const unsigned Reg : ScratchRegisterCopies) {
  38. assert(ScratchReg > 0 && "scratch reg copies but no scratch reg");
  39. const auto CopyRegisterCode = ET.copyReg(*MSI, Reg, ScratchReg);
  40. Result.insert(Result.end(), CopyRegisterCode.begin(), CopyRegisterCode.end());
  41. }
  42. // Load values in registers.
  43. for (const RegisterValue &RV : RegisterInitialValues) {
  44. // Load a constant in the register.
  45. const auto SetRegisterCode = ET.setRegTo(*MSI, RV.Register, RV.Value);
  46. if (SetRegisterCode.empty())
  47. IsSnippetSetupComplete = false;
  48. Result.insert(Result.end(), SetRegisterCode.begin(), SetRegisterCode.end());
  49. }
  50. return Result;
  51. }
  52. // Small utility function to add named passes.
  53. static bool addPass(llvm::PassManagerBase &PM, llvm::StringRef PassName,
  54. llvm::TargetPassConfig &TPC) {
  55. const llvm::PassRegistry *PR = llvm::PassRegistry::getPassRegistry();
  56. const llvm::PassInfo *PI = PR->getPassInfo(PassName);
  57. if (!PI) {
  58. llvm::errs() << " run-pass " << PassName << " is not registered.\n";
  59. return true;
  60. }
  61. if (!PI->getNormalCtor()) {
  62. llvm::errs() << " cannot create pass: " << PI->getPassName() << "\n";
  63. return true;
  64. }
  65. llvm::Pass *P = PI->getNormalCtor()();
  66. std::string Banner = std::string("After ") + std::string(P->getPassName());
  67. PM.add(P);
  68. TPC.printAndVerify(Banner);
  69. return false;
  70. }
  71. // Creates a void(int8*) MachineFunction.
  72. static llvm::MachineFunction &
  73. createVoidVoidPtrMachineFunction(llvm::StringRef FunctionID,
  74. llvm::Module *Module,
  75. llvm::MachineModuleInfo *MMI) {
  76. llvm::Type *const ReturnType = llvm::Type::getInt32Ty(Module->getContext());
  77. llvm::Type *const MemParamType = llvm::PointerType::get(
  78. llvm::Type::getInt8Ty(Module->getContext()), 0 /*default address space*/);
  79. llvm::FunctionType *FunctionType =
  80. llvm::FunctionType::get(ReturnType, {MemParamType}, false);
  81. llvm::Function *const F = llvm::Function::Create(
  82. FunctionType, llvm::GlobalValue::InternalLinkage, FunctionID, Module);
  83. // Making sure we can create a MachineFunction out of this Function even if it
  84. // contains no IR.
  85. F->setIsMaterializable(true);
  86. return MMI->getOrCreateMachineFunction(*F);
  87. }
  88. static void fillMachineFunction(llvm::MachineFunction &MF,
  89. llvm::ArrayRef<unsigned> LiveIns,
  90. llvm::ArrayRef<llvm::MCInst> Instructions) {
  91. llvm::MachineBasicBlock *MBB = MF.CreateMachineBasicBlock();
  92. MF.push_back(MBB);
  93. for (const unsigned Reg : LiveIns)
  94. MBB->addLiveIn(Reg);
  95. const llvm::MCInstrInfo *MCII = MF.getTarget().getMCInstrInfo();
  96. llvm::DebugLoc DL;
  97. for (const llvm::MCInst &Inst : Instructions) {
  98. const unsigned Opcode = Inst.getOpcode();
  99. const llvm::MCInstrDesc &MCID = MCII->get(Opcode);
  100. llvm::MachineInstrBuilder Builder = llvm::BuildMI(MBB, DL, MCID);
  101. for (unsigned OpIndex = 0, E = Inst.getNumOperands(); OpIndex < E;
  102. ++OpIndex) {
  103. const llvm::MCOperand &Op = Inst.getOperand(OpIndex);
  104. if (Op.isReg()) {
  105. const bool IsDef = OpIndex < MCID.getNumDefs();
  106. unsigned Flags = 0;
  107. const llvm::MCOperandInfo &OpInfo = MCID.operands().begin()[OpIndex];
  108. if (IsDef && !OpInfo.isOptionalDef())
  109. Flags |= llvm::RegState::Define;
  110. Builder.addReg(Op.getReg(), Flags);
  111. } else if (Op.isImm()) {
  112. Builder.addImm(Op.getImm());
  113. } else if (!Op.isValid()) {
  114. llvm_unreachable("Operand is not set");
  115. } else {
  116. llvm_unreachable("Not yet implemented");
  117. }
  118. }
  119. }
  120. // Insert the return code.
  121. const llvm::TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
  122. if (TII->getReturnOpcode() < TII->getNumOpcodes()) {
  123. llvm::BuildMI(MBB, DL, TII->get(TII->getReturnOpcode()));
  124. } else {
  125. llvm::MachineIRBuilder MIB(MF);
  126. MIB.setMBB(*MBB);
  127. MF.getSubtarget().getCallLowering()->lowerReturn(MIB, nullptr, {});
  128. }
  129. }
  130. static std::unique_ptr<llvm::Module>
  131. createModule(const std::unique_ptr<llvm::LLVMContext> &Context,
  132. const llvm::DataLayout DL) {
  133. auto Module = llvm::make_unique<llvm::Module>(ModuleID, *Context);
  134. Module->setDataLayout(DL);
  135. return Module;
  136. }
  137. llvm::BitVector getFunctionReservedRegs(const llvm::TargetMachine &TM) {
  138. std::unique_ptr<llvm::LLVMContext> Context =
  139. llvm::make_unique<llvm::LLVMContext>();
  140. std::unique_ptr<llvm::Module> Module =
  141. createModule(Context, TM.createDataLayout());
  142. // TODO: This only works for targets implementing LLVMTargetMachine.
  143. const LLVMTargetMachine &LLVMTM = static_cast<const LLVMTargetMachine&>(TM);
  144. std::unique_ptr<llvm::MachineModuleInfo> MMI =
  145. llvm::make_unique<llvm::MachineModuleInfo>(&LLVMTM);
  146. llvm::MachineFunction &MF =
  147. createVoidVoidPtrMachineFunction(FunctionID, Module.get(), MMI.get());
  148. // Saving reserved registers for client.
  149. return MF.getSubtarget().getRegisterInfo()->getReservedRegs(MF);
  150. }
  151. void assembleToStream(const ExegesisTarget &ET,
  152. std::unique_ptr<llvm::LLVMTargetMachine> TM,
  153. llvm::ArrayRef<unsigned> LiveIns,
  154. llvm::ArrayRef<unsigned> ScratchRegisterCopies,
  155. llvm::ArrayRef<RegisterValue> RegisterInitialValues,
  156. llvm::ArrayRef<llvm::MCInst> Instructions,
  157. llvm::raw_pwrite_stream &AsmStream) {
  158. std::unique_ptr<llvm::LLVMContext> Context =
  159. llvm::make_unique<llvm::LLVMContext>();
  160. std::unique_ptr<llvm::Module> Module =
  161. createModule(Context, TM->createDataLayout());
  162. std::unique_ptr<llvm::MachineModuleInfo> MMI =
  163. llvm::make_unique<llvm::MachineModuleInfo>(TM.get());
  164. llvm::MachineFunction &MF =
  165. createVoidVoidPtrMachineFunction(FunctionID, Module.get(), MMI.get());
  166. // We need to instruct the passes that we're done with SSA and virtual
  167. // registers.
  168. auto &Properties = MF.getProperties();
  169. Properties.set(llvm::MachineFunctionProperties::Property::NoVRegs);
  170. Properties.reset(llvm::MachineFunctionProperties::Property::IsSSA);
  171. for (const unsigned Reg : LiveIns)
  172. MF.getRegInfo().addLiveIn(Reg);
  173. bool IsSnippetSetupComplete;
  174. std::vector<llvm::MCInst> Code =
  175. generateSnippetSetupCode(ET, TM->getMCSubtargetInfo(), ET.getScratchMemoryRegister(TM->getTargetTriple()), ScratchRegisterCopies,
  176. RegisterInitialValues, IsSnippetSetupComplete);
  177. Code.insert(Code.end(), Instructions.begin(), Instructions.end());
  178. // If the snippet setup is not complete, we disable liveliness tracking. This
  179. // means that we won't know what values are in the registers.
  180. if (!IsSnippetSetupComplete)
  181. Properties.reset(llvm::MachineFunctionProperties::Property::TracksLiveness);
  182. // prologue/epilogue pass needs the reserved registers to be frozen, this
  183. // is usually done by the SelectionDAGISel pass.
  184. MF.getRegInfo().freezeReservedRegs(MF);
  185. // Fill the MachineFunction from the instructions.
  186. fillMachineFunction(MF, LiveIns, Code);
  187. // We create the pass manager, run the passes to populate AsmBuffer.
  188. llvm::MCContext &MCContext = MMI->getContext();
  189. llvm::legacy::PassManager PM;
  190. llvm::TargetLibraryInfoImpl TLII(Triple(Module->getTargetTriple()));
  191. PM.add(new llvm::TargetLibraryInfoWrapperPass(TLII));
  192. llvm::TargetPassConfig *TPC = TM->createPassConfig(PM);
  193. PM.add(TPC);
  194. PM.add(MMI.release());
  195. TPC->printAndVerify("MachineFunctionGenerator::assemble");
  196. // Add target-specific passes.
  197. ET.addTargetSpecificPasses(PM);
  198. TPC->printAndVerify("After ExegesisTarget::addTargetSpecificPasses");
  199. // Adding the following passes:
  200. // - machineverifier: checks that the MachineFunction is well formed.
  201. // - prologepilog: saves and restore callee saved registers.
  202. for (const char *PassName : {"machineverifier", "prologepilog"})
  203. if (addPass(PM, PassName, *TPC))
  204. llvm::report_fatal_error("Unable to add a mandatory pass");
  205. TPC->setInitialized();
  206. // AsmPrinter is responsible for generating the assembly into AsmBuffer.
  207. if (TM->addAsmPrinter(PM, AsmStream, nullptr,
  208. llvm::TargetMachine::CGFT_ObjectFile, MCContext))
  209. llvm::report_fatal_error("Cannot add AsmPrinter passes");
  210. PM.run(*Module); // Run all the passes
  211. }
  212. llvm::object::OwningBinary<llvm::object::ObjectFile>
  213. getObjectFromBuffer(llvm::StringRef InputData) {
  214. // Storing the generated assembly into a MemoryBuffer that owns the memory.
  215. std::unique_ptr<llvm::MemoryBuffer> Buffer =
  216. llvm::MemoryBuffer::getMemBufferCopy(InputData);
  217. // Create the ObjectFile from the MemoryBuffer.
  218. std::unique_ptr<llvm::object::ObjectFile> Obj = llvm::cantFail(
  219. llvm::object::ObjectFile::createObjectFile(Buffer->getMemBufferRef()));
  220. // Returning both the MemoryBuffer and the ObjectFile.
  221. return llvm::object::OwningBinary<llvm::object::ObjectFile>(
  222. std::move(Obj), std::move(Buffer));
  223. }
  224. llvm::object::OwningBinary<llvm::object::ObjectFile>
  225. getObjectFromFile(llvm::StringRef Filename) {
  226. return llvm::cantFail(llvm::object::ObjectFile::createObjectFile(Filename));
  227. }
  228. namespace {
  229. // Implementation of this class relies on the fact that a single object with a
  230. // single function will be loaded into memory.
  231. class TrackingSectionMemoryManager : public llvm::SectionMemoryManager {
  232. public:
  233. explicit TrackingSectionMemoryManager(uintptr_t *CodeSize)
  234. : CodeSize(CodeSize) {}
  235. uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
  236. unsigned SectionID,
  237. llvm::StringRef SectionName) override {
  238. *CodeSize = Size;
  239. return llvm::SectionMemoryManager::allocateCodeSection(
  240. Size, Alignment, SectionID, SectionName);
  241. }
  242. private:
  243. uintptr_t *const CodeSize = nullptr;
  244. };
  245. } // namespace
  246. ExecutableFunction::ExecutableFunction(
  247. std::unique_ptr<llvm::LLVMTargetMachine> TM,
  248. llvm::object::OwningBinary<llvm::object::ObjectFile> &&ObjectFileHolder)
  249. : Context(llvm::make_unique<llvm::LLVMContext>()) {
  250. assert(ObjectFileHolder.getBinary() && "cannot create object file");
  251. // Initializing the execution engine.
  252. // We need to use the JIT EngineKind to be able to add an object file.
  253. LLVMLinkInMCJIT();
  254. uintptr_t CodeSize = 0;
  255. std::string Error;
  256. ExecEngine.reset(
  257. llvm::EngineBuilder(createModule(Context, TM->createDataLayout()))
  258. .setErrorStr(&Error)
  259. .setMCPU(TM->getTargetCPU())
  260. .setEngineKind(llvm::EngineKind::JIT)
  261. .setMCJITMemoryManager(
  262. llvm::make_unique<TrackingSectionMemoryManager>(&CodeSize))
  263. .create(TM.release()));
  264. if (!ExecEngine)
  265. llvm::report_fatal_error(Error);
  266. // Adding the generated object file containing the assembled function.
  267. // The ExecutionEngine makes sure the object file is copied into an
  268. // executable page.
  269. ExecEngine->addObjectFile(std::move(ObjectFileHolder));
  270. // Fetching function bytes.
  271. FunctionBytes =
  272. llvm::StringRef(reinterpret_cast<const char *>(
  273. ExecEngine->getFunctionAddress(FunctionID)),
  274. CodeSize);
  275. }
  276. } // namespace exegesis
  277. } // namespace llvm