IndirectionUtils.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. //===---- IndirectionUtils.cpp - Utilities for call indirection in Orc ----===//
  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 "llvm/ExecutionEngine/Orc/IndirectionUtils.h"
  9. #include "llvm/ADT/STLExtras.h"
  10. #include "llvm/ADT/Triple.h"
  11. #include "llvm/ExecutionEngine/JITLink/x86_64.h"
  12. #include "llvm/ExecutionEngine/Orc/OrcABISupport.h"
  13. #include "llvm/IR/IRBuilder.h"
  14. #include "llvm/MC/MCDisassembler/MCDisassembler.h"
  15. #include "llvm/MC/MCInstrAnalysis.h"
  16. #include "llvm/Support/Format.h"
  17. #include "llvm/Transforms/Utils/Cloning.h"
  18. #include <sstream>
  19. #define DEBUG_TYPE "orc"
  20. using namespace llvm;
  21. using namespace llvm::orc;
  22. namespace {
  23. class CompileCallbackMaterializationUnit : public orc::MaterializationUnit {
  24. public:
  25. using CompileFunction = JITCompileCallbackManager::CompileFunction;
  26. CompileCallbackMaterializationUnit(SymbolStringPtr Name,
  27. CompileFunction Compile)
  28. : MaterializationUnit(Interface(
  29. SymbolFlagsMap({{Name, JITSymbolFlags::Exported}}), nullptr)),
  30. Name(std::move(Name)), Compile(std::move(Compile)) {}
  31. StringRef getName() const override { return "<Compile Callbacks>"; }
  32. private:
  33. void materialize(std::unique_ptr<MaterializationResponsibility> R) override {
  34. SymbolMap Result;
  35. Result[Name] = JITEvaluatedSymbol(Compile(), JITSymbolFlags::Exported);
  36. // No dependencies, so these calls cannot fail.
  37. cantFail(R->notifyResolved(Result));
  38. cantFail(R->notifyEmitted());
  39. }
  40. void discard(const JITDylib &JD, const SymbolStringPtr &Name) override {
  41. llvm_unreachable("Discard should never occur on a LMU?");
  42. }
  43. SymbolStringPtr Name;
  44. CompileFunction Compile;
  45. };
  46. } // namespace
  47. namespace llvm {
  48. namespace orc {
  49. TrampolinePool::~TrampolinePool() {}
  50. void IndirectStubsManager::anchor() {}
  51. Expected<JITTargetAddress>
  52. JITCompileCallbackManager::getCompileCallback(CompileFunction Compile) {
  53. if (auto TrampolineAddr = TP->getTrampoline()) {
  54. auto CallbackName =
  55. ES.intern(std::string("cc") + std::to_string(++NextCallbackId));
  56. std::lock_guard<std::mutex> Lock(CCMgrMutex);
  57. AddrToSymbol[*TrampolineAddr] = CallbackName;
  58. cantFail(
  59. CallbacksJD.define(std::make_unique<CompileCallbackMaterializationUnit>(
  60. std::move(CallbackName), std::move(Compile))));
  61. return *TrampolineAddr;
  62. } else
  63. return TrampolineAddr.takeError();
  64. }
  65. JITTargetAddress JITCompileCallbackManager::executeCompileCallback(
  66. JITTargetAddress TrampolineAddr) {
  67. SymbolStringPtr Name;
  68. {
  69. std::unique_lock<std::mutex> Lock(CCMgrMutex);
  70. auto I = AddrToSymbol.find(TrampolineAddr);
  71. // If this address is not associated with a compile callback then report an
  72. // error to the execution session and return ErrorHandlerAddress to the
  73. // callee.
  74. if (I == AddrToSymbol.end()) {
  75. Lock.unlock();
  76. std::string ErrMsg;
  77. {
  78. raw_string_ostream ErrMsgStream(ErrMsg);
  79. ErrMsgStream << "No compile callback for trampoline at "
  80. << format("0x%016" PRIx64, TrampolineAddr);
  81. }
  82. ES.reportError(
  83. make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode()));
  84. return ErrorHandlerAddress;
  85. } else
  86. Name = I->second;
  87. }
  88. if (auto Sym =
  89. ES.lookup(makeJITDylibSearchOrder(
  90. &CallbacksJD, JITDylibLookupFlags::MatchAllSymbols),
  91. Name))
  92. return Sym->getAddress();
  93. else {
  94. llvm::dbgs() << "Didn't find callback.\n";
  95. // If anything goes wrong materializing Sym then report it to the session
  96. // and return the ErrorHandlerAddress;
  97. ES.reportError(Sym.takeError());
  98. return ErrorHandlerAddress;
  99. }
  100. }
  101. Expected<std::unique_ptr<JITCompileCallbackManager>>
  102. createLocalCompileCallbackManager(const Triple &T, ExecutionSession &ES,
  103. JITTargetAddress ErrorHandlerAddress) {
  104. switch (T.getArch()) {
  105. default:
  106. return make_error<StringError>(
  107. std::string("No callback manager available for ") + T.str(),
  108. inconvertibleErrorCode());
  109. case Triple::aarch64:
  110. case Triple::aarch64_32: {
  111. typedef orc::LocalJITCompileCallbackManager<orc::OrcAArch64> CCMgrT;
  112. return CCMgrT::Create(ES, ErrorHandlerAddress);
  113. }
  114. case Triple::x86: {
  115. typedef orc::LocalJITCompileCallbackManager<orc::OrcI386> CCMgrT;
  116. return CCMgrT::Create(ES, ErrorHandlerAddress);
  117. }
  118. case Triple::mips: {
  119. typedef orc::LocalJITCompileCallbackManager<orc::OrcMips32Be> CCMgrT;
  120. return CCMgrT::Create(ES, ErrorHandlerAddress);
  121. }
  122. case Triple::mipsel: {
  123. typedef orc::LocalJITCompileCallbackManager<orc::OrcMips32Le> CCMgrT;
  124. return CCMgrT::Create(ES, ErrorHandlerAddress);
  125. }
  126. case Triple::mips64:
  127. case Triple::mips64el: {
  128. typedef orc::LocalJITCompileCallbackManager<orc::OrcMips64> CCMgrT;
  129. return CCMgrT::Create(ES, ErrorHandlerAddress);
  130. }
  131. case Triple::x86_64: {
  132. if (T.getOS() == Triple::OSType::Win32) {
  133. typedef orc::LocalJITCompileCallbackManager<orc::OrcX86_64_Win32> CCMgrT;
  134. return CCMgrT::Create(ES, ErrorHandlerAddress);
  135. } else {
  136. typedef orc::LocalJITCompileCallbackManager<orc::OrcX86_64_SysV> CCMgrT;
  137. return CCMgrT::Create(ES, ErrorHandlerAddress);
  138. }
  139. }
  140. }
  141. }
  142. std::function<std::unique_ptr<IndirectStubsManager>()>
  143. createLocalIndirectStubsManagerBuilder(const Triple &T) {
  144. switch (T.getArch()) {
  145. default:
  146. return [](){
  147. return std::make_unique<
  148. orc::LocalIndirectStubsManager<orc::OrcGenericABI>>();
  149. };
  150. case Triple::aarch64:
  151. case Triple::aarch64_32:
  152. return [](){
  153. return std::make_unique<
  154. orc::LocalIndirectStubsManager<orc::OrcAArch64>>();
  155. };
  156. case Triple::x86:
  157. return [](){
  158. return std::make_unique<
  159. orc::LocalIndirectStubsManager<orc::OrcI386>>();
  160. };
  161. case Triple::mips:
  162. return [](){
  163. return std::make_unique<
  164. orc::LocalIndirectStubsManager<orc::OrcMips32Be>>();
  165. };
  166. case Triple::mipsel:
  167. return [](){
  168. return std::make_unique<
  169. orc::LocalIndirectStubsManager<orc::OrcMips32Le>>();
  170. };
  171. case Triple::mips64:
  172. case Triple::mips64el:
  173. return [](){
  174. return std::make_unique<
  175. orc::LocalIndirectStubsManager<orc::OrcMips64>>();
  176. };
  177. case Triple::x86_64:
  178. if (T.getOS() == Triple::OSType::Win32) {
  179. return [](){
  180. return std::make_unique<
  181. orc::LocalIndirectStubsManager<orc::OrcX86_64_Win32>>();
  182. };
  183. } else {
  184. return [](){
  185. return std::make_unique<
  186. orc::LocalIndirectStubsManager<orc::OrcX86_64_SysV>>();
  187. };
  188. }
  189. }
  190. }
  191. Constant* createIRTypedAddress(FunctionType &FT, JITTargetAddress Addr) {
  192. Constant *AddrIntVal =
  193. ConstantInt::get(Type::getInt64Ty(FT.getContext()), Addr);
  194. Constant *AddrPtrVal =
  195. ConstantExpr::getCast(Instruction::IntToPtr, AddrIntVal,
  196. PointerType::get(&FT, 0));
  197. return AddrPtrVal;
  198. }
  199. GlobalVariable* createImplPointer(PointerType &PT, Module &M,
  200. const Twine &Name, Constant *Initializer) {
  201. auto IP = new GlobalVariable(M, &PT, false, GlobalValue::ExternalLinkage,
  202. Initializer, Name, nullptr,
  203. GlobalValue::NotThreadLocal, 0, true);
  204. IP->setVisibility(GlobalValue::HiddenVisibility);
  205. return IP;
  206. }
  207. void makeStub(Function &F, Value &ImplPointer) {
  208. assert(F.isDeclaration() && "Can't turn a definition into a stub.");
  209. assert(F.getParent() && "Function isn't in a module.");
  210. Module &M = *F.getParent();
  211. BasicBlock *EntryBlock = BasicBlock::Create(M.getContext(), "entry", &F);
  212. IRBuilder<> Builder(EntryBlock);
  213. LoadInst *ImplAddr = Builder.CreateLoad(F.getType(), &ImplPointer);
  214. std::vector<Value*> CallArgs;
  215. for (auto &A : F.args())
  216. CallArgs.push_back(&A);
  217. CallInst *Call = Builder.CreateCall(F.getFunctionType(), ImplAddr, CallArgs);
  218. Call->setTailCall();
  219. Call->setAttributes(F.getAttributes());
  220. if (F.getReturnType()->isVoidTy())
  221. Builder.CreateRetVoid();
  222. else
  223. Builder.CreateRet(Call);
  224. }
  225. std::vector<GlobalValue *> SymbolLinkagePromoter::operator()(Module &M) {
  226. std::vector<GlobalValue *> PromotedGlobals;
  227. for (auto &GV : M.global_values()) {
  228. bool Promoted = true;
  229. // Rename if necessary.
  230. if (!GV.hasName())
  231. GV.setName("__orc_anon." + Twine(NextId++));
  232. else if (GV.getName().startswith("\01L"))
  233. GV.setName("__" + GV.getName().substr(1) + "." + Twine(NextId++));
  234. else if (GV.hasLocalLinkage())
  235. GV.setName("__orc_lcl." + GV.getName() + "." + Twine(NextId++));
  236. else
  237. Promoted = false;
  238. if (GV.hasLocalLinkage()) {
  239. GV.setLinkage(GlobalValue::ExternalLinkage);
  240. GV.setVisibility(GlobalValue::HiddenVisibility);
  241. Promoted = true;
  242. }
  243. GV.setUnnamedAddr(GlobalValue::UnnamedAddr::None);
  244. if (Promoted)
  245. PromotedGlobals.push_back(&GV);
  246. }
  247. return PromotedGlobals;
  248. }
  249. Function* cloneFunctionDecl(Module &Dst, const Function &F,
  250. ValueToValueMapTy *VMap) {
  251. Function *NewF =
  252. Function::Create(cast<FunctionType>(F.getValueType()),
  253. F.getLinkage(), F.getName(), &Dst);
  254. NewF->copyAttributesFrom(&F);
  255. if (VMap) {
  256. (*VMap)[&F] = NewF;
  257. auto NewArgI = NewF->arg_begin();
  258. for (auto ArgI = F.arg_begin(), ArgE = F.arg_end(); ArgI != ArgE;
  259. ++ArgI, ++NewArgI)
  260. (*VMap)[&*ArgI] = &*NewArgI;
  261. }
  262. return NewF;
  263. }
  264. void moveFunctionBody(Function &OrigF, ValueToValueMapTy &VMap,
  265. ValueMaterializer *Materializer,
  266. Function *NewF) {
  267. assert(!OrigF.isDeclaration() && "Nothing to move");
  268. if (!NewF)
  269. NewF = cast<Function>(VMap[&OrigF]);
  270. else
  271. assert(VMap[&OrigF] == NewF && "Incorrect function mapping in VMap.");
  272. assert(NewF && "Function mapping missing from VMap.");
  273. assert(NewF->getParent() != OrigF.getParent() &&
  274. "moveFunctionBody should only be used to move bodies between "
  275. "modules.");
  276. SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
  277. CloneFunctionInto(NewF, &OrigF, VMap,
  278. CloneFunctionChangeType::DifferentModule, Returns, "",
  279. nullptr, nullptr, Materializer);
  280. OrigF.deleteBody();
  281. }
  282. GlobalVariable* cloneGlobalVariableDecl(Module &Dst, const GlobalVariable &GV,
  283. ValueToValueMapTy *VMap) {
  284. GlobalVariable *NewGV = new GlobalVariable(
  285. Dst, GV.getValueType(), GV.isConstant(),
  286. GV.getLinkage(), nullptr, GV.getName(), nullptr,
  287. GV.getThreadLocalMode(), GV.getType()->getAddressSpace());
  288. NewGV->copyAttributesFrom(&GV);
  289. if (VMap)
  290. (*VMap)[&GV] = NewGV;
  291. return NewGV;
  292. }
  293. void moveGlobalVariableInitializer(GlobalVariable &OrigGV,
  294. ValueToValueMapTy &VMap,
  295. ValueMaterializer *Materializer,
  296. GlobalVariable *NewGV) {
  297. assert(OrigGV.hasInitializer() && "Nothing to move");
  298. if (!NewGV)
  299. NewGV = cast<GlobalVariable>(VMap[&OrigGV]);
  300. else
  301. assert(VMap[&OrigGV] == NewGV &&
  302. "Incorrect global variable mapping in VMap.");
  303. assert(NewGV->getParent() != OrigGV.getParent() &&
  304. "moveGlobalVariableInitializer should only be used to move "
  305. "initializers between modules");
  306. NewGV->setInitializer(MapValue(OrigGV.getInitializer(), VMap, RF_None,
  307. nullptr, Materializer));
  308. }
  309. GlobalAlias* cloneGlobalAliasDecl(Module &Dst, const GlobalAlias &OrigA,
  310. ValueToValueMapTy &VMap) {
  311. assert(OrigA.getAliasee() && "Original alias doesn't have an aliasee?");
  312. auto *NewA = GlobalAlias::create(OrigA.getValueType(),
  313. OrigA.getType()->getPointerAddressSpace(),
  314. OrigA.getLinkage(), OrigA.getName(), &Dst);
  315. NewA->copyAttributesFrom(&OrigA);
  316. VMap[&OrigA] = NewA;
  317. return NewA;
  318. }
  319. void cloneModuleFlagsMetadata(Module &Dst, const Module &Src,
  320. ValueToValueMapTy &VMap) {
  321. auto *MFs = Src.getModuleFlagsMetadata();
  322. if (!MFs)
  323. return;
  324. for (auto *MF : MFs->operands())
  325. Dst.addModuleFlag(MapMetadata(MF, VMap));
  326. }
  327. Error addFunctionPointerRelocationsToCurrentSymbol(jitlink::Symbol &Sym,
  328. jitlink::LinkGraph &G,
  329. MCDisassembler &Disassembler,
  330. MCInstrAnalysis &MIA) {
  331. // AArch64 appears to already come with the necessary relocations. Among other
  332. // architectures, only x86_64 is currently implemented here.
  333. if (G.getTargetTriple().getArch() != Triple::x86_64)
  334. return Error::success();
  335. raw_null_ostream CommentStream;
  336. auto &STI = Disassembler.getSubtargetInfo();
  337. // Determine the function bounds
  338. auto &B = Sym.getBlock();
  339. assert(!B.isZeroFill() && "expected content block");
  340. auto SymAddress = Sym.getAddress();
  341. auto SymStartInBlock =
  342. (const uint8_t *)B.getContent().data() + Sym.getOffset();
  343. auto SymSize = Sym.getSize() ? Sym.getSize() : B.getSize() - Sym.getOffset();
  344. auto Content = makeArrayRef(SymStartInBlock, SymSize);
  345. LLVM_DEBUG(dbgs() << "Adding self-relocations to " << Sym.getName() << "\n");
  346. SmallDenseSet<uintptr_t, 8> ExistingRelocations;
  347. for (auto &E : B.edges()) {
  348. if (E.isRelocation())
  349. ExistingRelocations.insert(E.getOffset());
  350. }
  351. size_t I = 0;
  352. while (I < Content.size()) {
  353. MCInst Instr;
  354. uint64_t InstrSize = 0;
  355. uint64_t InstrStart = SymAddress.getValue() + I;
  356. auto DecodeStatus = Disassembler.getInstruction(
  357. Instr, InstrSize, Content.drop_front(I), InstrStart, CommentStream);
  358. if (DecodeStatus != MCDisassembler::Success) {
  359. LLVM_DEBUG(dbgs() << "Aborting due to disassembly failure at address "
  360. << InstrStart);
  361. return make_error<StringError>(
  362. formatv("failed to disassemble at address {0:x16}", InstrStart),
  363. inconvertibleErrorCode());
  364. }
  365. // Advance to the next instruction.
  366. I += InstrSize;
  367. // Check for a PC-relative address equal to the symbol itself.
  368. auto PCRelAddr =
  369. MIA.evaluateMemoryOperandAddress(Instr, &STI, InstrStart, InstrSize);
  370. if (!PCRelAddr || *PCRelAddr != SymAddress.getValue())
  371. continue;
  372. auto RelocOffInInstr =
  373. MIA.getMemoryOperandRelocationOffset(Instr, InstrSize);
  374. if (!RelocOffInInstr.hasValue() ||
  375. InstrSize - RelocOffInInstr.getValue() != 4) {
  376. LLVM_DEBUG(dbgs() << "Skipping unknown self-relocation at "
  377. << InstrStart);
  378. continue;
  379. }
  380. auto RelocOffInBlock = orc::ExecutorAddr(InstrStart) + *RelocOffInInstr -
  381. SymAddress + Sym.getOffset();
  382. if (ExistingRelocations.contains(RelocOffInBlock))
  383. continue;
  384. LLVM_DEBUG(dbgs() << "Adding delta32 self-relocation at " << InstrStart);
  385. B.addEdge(jitlink::x86_64::Delta32, RelocOffInBlock, Sym, /*Addend=*/-4);
  386. }
  387. return Error::success();
  388. }
  389. } // End namespace orc.
  390. } // End namespace llvm.