Assembler.cpp 13 KB

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