OrcV2CBindings.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  1. //===--------------- OrcV2CBindings.cpp - C bindings OrcV2 APIs -----------===//
  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-c/LLJIT.h"
  9. #include "llvm-c/Orc.h"
  10. #include "llvm-c/OrcEE.h"
  11. #include "llvm-c/TargetMachine.h"
  12. #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
  13. #include "llvm/ExecutionEngine/Orc/LLJIT.h"
  14. #include "llvm/ExecutionEngine/Orc/ObjectTransformLayer.h"
  15. #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
  16. #include "llvm/ExecutionEngine/SectionMemoryManager.h"
  17. using namespace llvm;
  18. using namespace llvm::orc;
  19. namespace llvm {
  20. namespace orc {
  21. class InProgressLookupState;
  22. class OrcV2CAPIHelper {
  23. public:
  24. using PoolEntry = SymbolStringPtr::PoolEntry;
  25. using PoolEntryPtr = SymbolStringPtr::PoolEntryPtr;
  26. // Move from SymbolStringPtr to PoolEntryPtr (no change in ref count).
  27. static PoolEntryPtr moveFromSymbolStringPtr(SymbolStringPtr S) {
  28. PoolEntryPtr Result = nullptr;
  29. std::swap(Result, S.S);
  30. return Result;
  31. }
  32. // Move from a PoolEntryPtr to a SymbolStringPtr (no change in ref count).
  33. static SymbolStringPtr moveToSymbolStringPtr(PoolEntryPtr P) {
  34. SymbolStringPtr S;
  35. S.S = P;
  36. return S;
  37. }
  38. // Copy a pool entry to a SymbolStringPtr (increments ref count).
  39. static SymbolStringPtr copyToSymbolStringPtr(PoolEntryPtr P) {
  40. return SymbolStringPtr(P);
  41. }
  42. static PoolEntryPtr getRawPoolEntryPtr(const SymbolStringPtr &S) {
  43. return S.S;
  44. }
  45. static void retainPoolEntry(PoolEntryPtr P) {
  46. SymbolStringPtr S(P);
  47. S.S = nullptr;
  48. }
  49. static void releasePoolEntry(PoolEntryPtr P) {
  50. SymbolStringPtr S;
  51. S.S = P;
  52. }
  53. static InProgressLookupState *extractLookupState(LookupState &LS) {
  54. return LS.IPLS.release();
  55. }
  56. static void resetLookupState(LookupState &LS, InProgressLookupState *IPLS) {
  57. return LS.reset(IPLS);
  58. }
  59. };
  60. } // namespace orc
  61. } // namespace llvm
  62. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ExecutionSession, LLVMOrcExecutionSessionRef)
  63. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(SymbolStringPool, LLVMOrcSymbolStringPoolRef)
  64. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(OrcV2CAPIHelper::PoolEntry,
  65. LLVMOrcSymbolStringPoolEntryRef)
  66. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(MaterializationUnit,
  67. LLVMOrcMaterializationUnitRef)
  68. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(MaterializationResponsibility,
  69. LLVMOrcMaterializationResponsibilityRef)
  70. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(JITDylib, LLVMOrcJITDylibRef)
  71. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ResourceTracker, LLVMOrcResourceTrackerRef)
  72. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(DefinitionGenerator,
  73. LLVMOrcDefinitionGeneratorRef)
  74. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(InProgressLookupState, LLVMOrcLookupStateRef)
  75. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ThreadSafeContext,
  76. LLVMOrcThreadSafeContextRef)
  77. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ThreadSafeModule, LLVMOrcThreadSafeModuleRef)
  78. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(JITTargetMachineBuilder,
  79. LLVMOrcJITTargetMachineBuilderRef)
  80. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ObjectLayer, LLVMOrcObjectLayerRef)
  81. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRTransformLayer, LLVMOrcIRTransformLayerRef)
  82. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ObjectTransformLayer,
  83. LLVMOrcObjectTransformLayerRef)
  84. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(DumpObjects, LLVMOrcDumpObjectsRef)
  85. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IndirectStubsManager,
  86. LLVMOrcIndirectStubsManagerRef)
  87. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LazyCallThroughManager,
  88. LLVMOrcLazyCallThroughManagerRef)
  89. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LLJITBuilder, LLVMOrcLLJITBuilderRef)
  90. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LLJIT, LLVMOrcLLJITRef)
  91. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(TargetMachine, LLVMTargetMachineRef)
  92. namespace {
  93. class OrcCAPIMaterializationUnit : public llvm::orc::MaterializationUnit {
  94. public:
  95. OrcCAPIMaterializationUnit(
  96. std::string Name, SymbolFlagsMap InitialSymbolFlags,
  97. SymbolStringPtr InitSymbol, void *Ctx,
  98. LLVMOrcMaterializationUnitMaterializeFunction Materialize,
  99. LLVMOrcMaterializationUnitDiscardFunction Discard,
  100. LLVMOrcMaterializationUnitDestroyFunction Destroy)
  101. : llvm::orc::MaterializationUnit(
  102. Interface(std::move(InitialSymbolFlags), std::move(InitSymbol))),
  103. Name(std::move(Name)), Ctx(Ctx), Materialize(Materialize),
  104. Discard(Discard), Destroy(Destroy) {}
  105. ~OrcCAPIMaterializationUnit() {
  106. if (Ctx)
  107. Destroy(Ctx);
  108. }
  109. StringRef getName() const override { return Name; }
  110. void materialize(std::unique_ptr<MaterializationResponsibility> R) override {
  111. void *Tmp = Ctx;
  112. Ctx = nullptr;
  113. Materialize(Tmp, wrap(R.release()));
  114. }
  115. private:
  116. void discard(const JITDylib &JD, const SymbolStringPtr &Name) override {
  117. Discard(Ctx, wrap(&JD), wrap(OrcV2CAPIHelper::getRawPoolEntryPtr(Name)));
  118. }
  119. std::string Name;
  120. void *Ctx = nullptr;
  121. LLVMOrcMaterializationUnitMaterializeFunction Materialize = nullptr;
  122. LLVMOrcMaterializationUnitDiscardFunction Discard = nullptr;
  123. LLVMOrcMaterializationUnitDestroyFunction Destroy = nullptr;
  124. };
  125. static JITSymbolFlags toJITSymbolFlags(LLVMJITSymbolFlags F) {
  126. JITSymbolFlags JSF;
  127. if (F.GenericFlags & LLVMJITSymbolGenericFlagsExported)
  128. JSF |= JITSymbolFlags::Exported;
  129. if (F.GenericFlags & LLVMJITSymbolGenericFlagsWeak)
  130. JSF |= JITSymbolFlags::Weak;
  131. if (F.GenericFlags & LLVMJITSymbolGenericFlagsCallable)
  132. JSF |= JITSymbolFlags::Callable;
  133. if (F.GenericFlags & LLVMJITSymbolGenericFlagsMaterializationSideEffectsOnly)
  134. JSF |= JITSymbolFlags::MaterializationSideEffectsOnly;
  135. JSF.getTargetFlags() = F.TargetFlags;
  136. return JSF;
  137. }
  138. static LLVMJITSymbolFlags fromJITSymbolFlags(JITSymbolFlags JSF) {
  139. LLVMJITSymbolFlags F = {0, 0};
  140. if (JSF & JITSymbolFlags::Exported)
  141. F.GenericFlags |= LLVMJITSymbolGenericFlagsExported;
  142. if (JSF & JITSymbolFlags::Weak)
  143. F.GenericFlags |= LLVMJITSymbolGenericFlagsWeak;
  144. if (JSF & JITSymbolFlags::Callable)
  145. F.GenericFlags |= LLVMJITSymbolGenericFlagsCallable;
  146. if (JSF & JITSymbolFlags::MaterializationSideEffectsOnly)
  147. F.GenericFlags |= LLVMJITSymbolGenericFlagsMaterializationSideEffectsOnly;
  148. F.TargetFlags = JSF.getTargetFlags();
  149. return F;
  150. }
  151. static SymbolMap toSymbolMap(LLVMOrcCSymbolMapPairs Syms, size_t NumPairs) {
  152. SymbolMap SM;
  153. for (size_t I = 0; I != NumPairs; ++I) {
  154. JITSymbolFlags Flags = toJITSymbolFlags(Syms[I].Sym.Flags);
  155. SM[OrcV2CAPIHelper::moveToSymbolStringPtr(unwrap(Syms[I].Name))] =
  156. JITEvaluatedSymbol(Syms[I].Sym.Address, Flags);
  157. }
  158. return SM;
  159. }
  160. static SymbolDependenceMap
  161. toSymbolDependenceMap(LLVMOrcCDependenceMapPairs Pairs, size_t NumPairs) {
  162. SymbolDependenceMap SDM;
  163. for (size_t I = 0; I != NumPairs; ++I) {
  164. JITDylib *JD = unwrap(Pairs[I].JD);
  165. SymbolNameSet Names;
  166. for (size_t J = 0; J != Pairs[I].Names.Length; ++J) {
  167. auto Sym = Pairs[I].Names.Symbols[J];
  168. Names.insert(OrcV2CAPIHelper::moveToSymbolStringPtr(unwrap(Sym)));
  169. }
  170. SDM[JD] = Names;
  171. }
  172. return SDM;
  173. }
  174. static LookupKind toLookupKind(LLVMOrcLookupKind K) {
  175. switch (K) {
  176. case LLVMOrcLookupKindStatic:
  177. return LookupKind::Static;
  178. case LLVMOrcLookupKindDLSym:
  179. return LookupKind::DLSym;
  180. }
  181. llvm_unreachable("unrecognized LLVMOrcLookupKind value");
  182. }
  183. static LLVMOrcLookupKind fromLookupKind(LookupKind K) {
  184. switch (K) {
  185. case LookupKind::Static:
  186. return LLVMOrcLookupKindStatic;
  187. case LookupKind::DLSym:
  188. return LLVMOrcLookupKindDLSym;
  189. }
  190. llvm_unreachable("unrecognized LookupKind value");
  191. }
  192. static JITDylibLookupFlags
  193. toJITDylibLookupFlags(LLVMOrcJITDylibLookupFlags LF) {
  194. switch (LF) {
  195. case LLVMOrcJITDylibLookupFlagsMatchExportedSymbolsOnly:
  196. return JITDylibLookupFlags::MatchExportedSymbolsOnly;
  197. case LLVMOrcJITDylibLookupFlagsMatchAllSymbols:
  198. return JITDylibLookupFlags::MatchAllSymbols;
  199. }
  200. llvm_unreachable("unrecognized LLVMOrcJITDylibLookupFlags value");
  201. }
  202. static LLVMOrcJITDylibLookupFlags
  203. fromJITDylibLookupFlags(JITDylibLookupFlags LF) {
  204. switch (LF) {
  205. case JITDylibLookupFlags::MatchExportedSymbolsOnly:
  206. return LLVMOrcJITDylibLookupFlagsMatchExportedSymbolsOnly;
  207. case JITDylibLookupFlags::MatchAllSymbols:
  208. return LLVMOrcJITDylibLookupFlagsMatchAllSymbols;
  209. }
  210. llvm_unreachable("unrecognized JITDylibLookupFlags value");
  211. }
  212. static SymbolLookupFlags toSymbolLookupFlags(LLVMOrcSymbolLookupFlags SLF) {
  213. switch (SLF) {
  214. case LLVMOrcSymbolLookupFlagsRequiredSymbol:
  215. return SymbolLookupFlags::RequiredSymbol;
  216. case LLVMOrcSymbolLookupFlagsWeaklyReferencedSymbol:
  217. return SymbolLookupFlags::WeaklyReferencedSymbol;
  218. }
  219. llvm_unreachable("unrecognized LLVMOrcSymbolLookupFlags value");
  220. }
  221. static LLVMOrcSymbolLookupFlags fromSymbolLookupFlags(SymbolLookupFlags SLF) {
  222. switch (SLF) {
  223. case SymbolLookupFlags::RequiredSymbol:
  224. return LLVMOrcSymbolLookupFlagsRequiredSymbol;
  225. case SymbolLookupFlags::WeaklyReferencedSymbol:
  226. return LLVMOrcSymbolLookupFlagsWeaklyReferencedSymbol;
  227. }
  228. llvm_unreachable("unrecognized SymbolLookupFlags value");
  229. }
  230. static LLVMJITEvaluatedSymbol
  231. fromJITEvaluatedSymbol(const JITEvaluatedSymbol &S) {
  232. return {S.getAddress(), fromJITSymbolFlags(S.getFlags())};
  233. }
  234. } // end anonymous namespace
  235. namespace llvm {
  236. namespace orc {
  237. class CAPIDefinitionGenerator final : public DefinitionGenerator {
  238. public:
  239. CAPIDefinitionGenerator(
  240. LLVMOrcDisposeCAPIDefinitionGeneratorFunction Dispose, void *Ctx,
  241. LLVMOrcCAPIDefinitionGeneratorTryToGenerateFunction TryToGenerate)
  242. : Dispose(Dispose), Ctx(Ctx), TryToGenerate(TryToGenerate) {}
  243. ~CAPIDefinitionGenerator() {
  244. if (Dispose)
  245. Dispose(Ctx);
  246. }
  247. Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD,
  248. JITDylibLookupFlags JDLookupFlags,
  249. const SymbolLookupSet &LookupSet) override {
  250. // Take the lookup state.
  251. LLVMOrcLookupStateRef LSR = ::wrap(OrcV2CAPIHelper::extractLookupState(LS));
  252. // Translate the lookup kind.
  253. LLVMOrcLookupKind CLookupKind = fromLookupKind(K);
  254. // Translate the JITDylibLookupFlags.
  255. LLVMOrcJITDylibLookupFlags CJDLookupFlags =
  256. fromJITDylibLookupFlags(JDLookupFlags);
  257. // Translate the lookup set.
  258. std::vector<LLVMOrcCLookupSetElement> CLookupSet;
  259. CLookupSet.reserve(LookupSet.size());
  260. for (auto &KV : LookupSet) {
  261. LLVMOrcSymbolStringPoolEntryRef Name =
  262. ::wrap(OrcV2CAPIHelper::getRawPoolEntryPtr(KV.first));
  263. LLVMOrcSymbolLookupFlags SLF = fromSymbolLookupFlags(KV.second);
  264. CLookupSet.push_back({Name, SLF});
  265. }
  266. // Run the C TryToGenerate function.
  267. auto Err = unwrap(TryToGenerate(::wrap(this), Ctx, &LSR, CLookupKind,
  268. ::wrap(&JD), CJDLookupFlags,
  269. CLookupSet.data(), CLookupSet.size()));
  270. // Restore the lookup state.
  271. OrcV2CAPIHelper::resetLookupState(LS, ::unwrap(LSR));
  272. return Err;
  273. }
  274. private:
  275. LLVMOrcDisposeCAPIDefinitionGeneratorFunction Dispose;
  276. void *Ctx;
  277. LLVMOrcCAPIDefinitionGeneratorTryToGenerateFunction TryToGenerate;
  278. };
  279. } // end namespace orc
  280. } // end namespace llvm
  281. void LLVMOrcExecutionSessionSetErrorReporter(
  282. LLVMOrcExecutionSessionRef ES, LLVMOrcErrorReporterFunction ReportError,
  283. void *Ctx) {
  284. unwrap(ES)->setErrorReporter(
  285. [=](Error Err) { ReportError(Ctx, wrap(std::move(Err))); });
  286. }
  287. LLVMOrcSymbolStringPoolRef
  288. LLVMOrcExecutionSessionGetSymbolStringPool(LLVMOrcExecutionSessionRef ES) {
  289. return wrap(
  290. unwrap(ES)->getExecutorProcessControl().getSymbolStringPool().get());
  291. }
  292. void LLVMOrcSymbolStringPoolClearDeadEntries(LLVMOrcSymbolStringPoolRef SSP) {
  293. unwrap(SSP)->clearDeadEntries();
  294. }
  295. LLVMOrcSymbolStringPoolEntryRef
  296. LLVMOrcExecutionSessionIntern(LLVMOrcExecutionSessionRef ES, const char *Name) {
  297. return wrap(
  298. OrcV2CAPIHelper::moveFromSymbolStringPtr(unwrap(ES)->intern(Name)));
  299. }
  300. void LLVMOrcExecutionSessionLookup(
  301. LLVMOrcExecutionSessionRef ES, LLVMOrcLookupKind K,
  302. LLVMOrcCJITDylibSearchOrder SearchOrder, size_t SearchOrderSize,
  303. LLVMOrcCLookupSet Symbols, size_t SymbolsSize,
  304. LLVMOrcExecutionSessionLookupHandleResultFunction HandleResult, void *Ctx) {
  305. assert(ES && "ES cannot be null");
  306. assert(SearchOrder && "SearchOrder cannot be null");
  307. assert(Symbols && "Symbols cannot be null");
  308. assert(HandleResult && "HandleResult cannot be null");
  309. JITDylibSearchOrder SO;
  310. for (size_t I = 0; I != SearchOrderSize; ++I)
  311. SO.push_back({unwrap(SearchOrder[I].JD),
  312. toJITDylibLookupFlags(SearchOrder[I].JDLookupFlags)});
  313. SymbolLookupSet SLS;
  314. for (size_t I = 0; I != SymbolsSize; ++I)
  315. SLS.add(OrcV2CAPIHelper::moveToSymbolStringPtr(unwrap(Symbols[I].Name)),
  316. toSymbolLookupFlags(Symbols[I].LookupFlags));
  317. unwrap(ES)->lookup(
  318. toLookupKind(K), SO, std::move(SLS), SymbolState::Ready,
  319. [HandleResult, Ctx](Expected<SymbolMap> Result) {
  320. if (Result) {
  321. SmallVector<LLVMOrcCSymbolMapPair> CResult;
  322. for (auto &KV : *Result)
  323. CResult.push_back(LLVMOrcCSymbolMapPair{
  324. wrap(OrcV2CAPIHelper::getRawPoolEntryPtr(KV.first)),
  325. fromJITEvaluatedSymbol(KV.second)});
  326. HandleResult(LLVMErrorSuccess, CResult.data(), CResult.size(), Ctx);
  327. } else
  328. HandleResult(wrap(Result.takeError()), nullptr, 0, Ctx);
  329. },
  330. NoDependenciesToRegister);
  331. }
  332. void LLVMOrcRetainSymbolStringPoolEntry(LLVMOrcSymbolStringPoolEntryRef S) {
  333. OrcV2CAPIHelper::retainPoolEntry(unwrap(S));
  334. }
  335. void LLVMOrcReleaseSymbolStringPoolEntry(LLVMOrcSymbolStringPoolEntryRef S) {
  336. OrcV2CAPIHelper::releasePoolEntry(unwrap(S));
  337. }
  338. const char *LLVMOrcSymbolStringPoolEntryStr(LLVMOrcSymbolStringPoolEntryRef S) {
  339. return unwrap(S)->getKey().data();
  340. }
  341. LLVMOrcResourceTrackerRef
  342. LLVMOrcJITDylibCreateResourceTracker(LLVMOrcJITDylibRef JD) {
  343. auto RT = unwrap(JD)->createResourceTracker();
  344. // Retain the pointer for the C API client.
  345. RT->Retain();
  346. return wrap(RT.get());
  347. }
  348. LLVMOrcResourceTrackerRef
  349. LLVMOrcJITDylibGetDefaultResourceTracker(LLVMOrcJITDylibRef JD) {
  350. auto RT = unwrap(JD)->getDefaultResourceTracker();
  351. // Retain the pointer for the C API client.
  352. return wrap(RT.get());
  353. }
  354. void LLVMOrcReleaseResourceTracker(LLVMOrcResourceTrackerRef RT) {
  355. ResourceTrackerSP TmpRT(unwrap(RT));
  356. TmpRT->Release();
  357. }
  358. void LLVMOrcResourceTrackerTransferTo(LLVMOrcResourceTrackerRef SrcRT,
  359. LLVMOrcResourceTrackerRef DstRT) {
  360. ResourceTrackerSP TmpRT(unwrap(SrcRT));
  361. TmpRT->transferTo(*unwrap(DstRT));
  362. }
  363. LLVMErrorRef LLVMOrcResourceTrackerRemove(LLVMOrcResourceTrackerRef RT) {
  364. ResourceTrackerSP TmpRT(unwrap(RT));
  365. return wrap(TmpRT->remove());
  366. }
  367. void LLVMOrcDisposeDefinitionGenerator(LLVMOrcDefinitionGeneratorRef DG) {
  368. std::unique_ptr<DefinitionGenerator> TmpDG(unwrap(DG));
  369. }
  370. void LLVMOrcDisposeMaterializationUnit(LLVMOrcMaterializationUnitRef MU) {
  371. std::unique_ptr<MaterializationUnit> TmpMU(unwrap(MU));
  372. }
  373. LLVMOrcMaterializationUnitRef LLVMOrcCreateCustomMaterializationUnit(
  374. const char *Name, void *Ctx, LLVMOrcCSymbolFlagsMapPairs Syms,
  375. size_t NumSyms, LLVMOrcSymbolStringPoolEntryRef InitSym,
  376. LLVMOrcMaterializationUnitMaterializeFunction Materialize,
  377. LLVMOrcMaterializationUnitDiscardFunction Discard,
  378. LLVMOrcMaterializationUnitDestroyFunction Destroy) {
  379. SymbolFlagsMap SFM;
  380. for (size_t I = 0; I != NumSyms; ++I)
  381. SFM[OrcV2CAPIHelper::moveToSymbolStringPtr(unwrap(Syms[I].Name))] =
  382. toJITSymbolFlags(Syms[I].Flags);
  383. auto IS = OrcV2CAPIHelper::moveToSymbolStringPtr(unwrap(InitSym));
  384. return wrap(new OrcCAPIMaterializationUnit(
  385. Name, std::move(SFM), std::move(IS), Ctx, Materialize, Discard, Destroy));
  386. }
  387. LLVMOrcMaterializationUnitRef
  388. LLVMOrcAbsoluteSymbols(LLVMOrcCSymbolMapPairs Syms, size_t NumPairs) {
  389. SymbolMap SM = toSymbolMap(Syms, NumPairs);
  390. return wrap(absoluteSymbols(std::move(SM)).release());
  391. }
  392. LLVMOrcMaterializationUnitRef LLVMOrcLazyReexports(
  393. LLVMOrcLazyCallThroughManagerRef LCTM, LLVMOrcIndirectStubsManagerRef ISM,
  394. LLVMOrcJITDylibRef SourceJD, LLVMOrcCSymbolAliasMapPairs CallableAliases,
  395. size_t NumPairs) {
  396. SymbolAliasMap SAM;
  397. for (size_t I = 0; I != NumPairs; ++I) {
  398. auto pair = CallableAliases[I];
  399. JITSymbolFlags Flags = toJITSymbolFlags(pair.Entry.Flags);
  400. SymbolStringPtr Name =
  401. OrcV2CAPIHelper::moveToSymbolStringPtr(unwrap(pair.Entry.Name));
  402. SAM[OrcV2CAPIHelper::moveToSymbolStringPtr(unwrap(pair.Name))] =
  403. SymbolAliasMapEntry(Name, Flags);
  404. }
  405. return wrap(lazyReexports(*unwrap(LCTM), *unwrap(ISM), *unwrap(SourceJD),
  406. std::move(SAM))
  407. .release());
  408. }
  409. void LLVMOrcDisposeMaterializationResponsibility(
  410. LLVMOrcMaterializationResponsibilityRef MR) {
  411. std::unique_ptr<MaterializationResponsibility> TmpMR(unwrap(MR));
  412. }
  413. LLVMOrcJITDylibRef LLVMOrcMaterializationResponsibilityGetTargetDylib(
  414. LLVMOrcMaterializationResponsibilityRef MR) {
  415. return wrap(&unwrap(MR)->getTargetJITDylib());
  416. }
  417. LLVMOrcExecutionSessionRef
  418. LLVMOrcMaterializationResponsibilityGetExecutionSession(
  419. LLVMOrcMaterializationResponsibilityRef MR) {
  420. return wrap(&unwrap(MR)->getExecutionSession());
  421. }
  422. LLVMOrcCSymbolFlagsMapPairs LLVMOrcMaterializationResponsibilityGetSymbols(
  423. LLVMOrcMaterializationResponsibilityRef MR, size_t *NumPairs) {
  424. auto Symbols = unwrap(MR)->getSymbols();
  425. LLVMOrcCSymbolFlagsMapPairs Result = static_cast<LLVMOrcCSymbolFlagsMapPairs>(
  426. safe_malloc(Symbols.size() * sizeof(LLVMOrcCSymbolFlagsMapPair)));
  427. size_t I = 0;
  428. for (auto const &pair : Symbols) {
  429. auto Name = wrap(OrcV2CAPIHelper::getRawPoolEntryPtr(pair.first));
  430. auto Flags = pair.second;
  431. Result[I] = {Name, fromJITSymbolFlags(Flags)};
  432. I++;
  433. }
  434. *NumPairs = Symbols.size();
  435. return Result;
  436. }
  437. void LLVMOrcDisposeCSymbolFlagsMap(LLVMOrcCSymbolFlagsMapPairs Pairs) {
  438. free(Pairs);
  439. }
  440. LLVMOrcSymbolStringPoolEntryRef
  441. LLVMOrcMaterializationResponsibilityGetInitializerSymbol(
  442. LLVMOrcMaterializationResponsibilityRef MR) {
  443. auto Sym = unwrap(MR)->getInitializerSymbol();
  444. return wrap(OrcV2CAPIHelper::getRawPoolEntryPtr(Sym));
  445. }
  446. LLVMOrcSymbolStringPoolEntryRef *
  447. LLVMOrcMaterializationResponsibilityGetRequestedSymbols(
  448. LLVMOrcMaterializationResponsibilityRef MR, size_t *NumSymbols) {
  449. auto Symbols = unwrap(MR)->getRequestedSymbols();
  450. LLVMOrcSymbolStringPoolEntryRef *Result =
  451. static_cast<LLVMOrcSymbolStringPoolEntryRef *>(safe_malloc(
  452. Symbols.size() * sizeof(LLVMOrcSymbolStringPoolEntryRef)));
  453. size_t I = 0;
  454. for (auto &Name : Symbols) {
  455. Result[I] = wrap(OrcV2CAPIHelper::getRawPoolEntryPtr(Name));
  456. I++;
  457. }
  458. *NumSymbols = Symbols.size();
  459. return Result;
  460. }
  461. void LLVMOrcDisposeSymbols(LLVMOrcSymbolStringPoolEntryRef *Symbols) {
  462. free(Symbols);
  463. }
  464. LLVMErrorRef LLVMOrcMaterializationResponsibilityNotifyResolved(
  465. LLVMOrcMaterializationResponsibilityRef MR, LLVMOrcCSymbolMapPairs Symbols,
  466. size_t NumPairs) {
  467. SymbolMap SM = toSymbolMap(Symbols, NumPairs);
  468. return wrap(unwrap(MR)->notifyResolved(std::move(SM)));
  469. }
  470. LLVMErrorRef LLVMOrcMaterializationResponsibilityNotifyEmitted(
  471. LLVMOrcMaterializationResponsibilityRef MR) {
  472. return wrap(unwrap(MR)->notifyEmitted());
  473. }
  474. LLVMErrorRef LLVMOrcMaterializationResponsibilityDefineMaterializing(
  475. LLVMOrcMaterializationResponsibilityRef MR,
  476. LLVMOrcCSymbolFlagsMapPairs Syms, size_t NumSyms) {
  477. SymbolFlagsMap SFM;
  478. for (size_t I = 0; I != NumSyms; ++I)
  479. SFM[OrcV2CAPIHelper::moveToSymbolStringPtr(unwrap(Syms[I].Name))] =
  480. toJITSymbolFlags(Syms[I].Flags);
  481. return wrap(unwrap(MR)->defineMaterializing(std::move(SFM)));
  482. }
  483. LLVMErrorRef LLVMOrcMaterializationResponsibilityReplace(
  484. LLVMOrcMaterializationResponsibilityRef MR,
  485. LLVMOrcMaterializationUnitRef MU) {
  486. std::unique_ptr<MaterializationUnit> TmpMU(unwrap(MU));
  487. return wrap(unwrap(MR)->replace(std::move(TmpMU)));
  488. }
  489. LLVMErrorRef LLVMOrcMaterializationResponsibilityDelegate(
  490. LLVMOrcMaterializationResponsibilityRef MR,
  491. LLVMOrcSymbolStringPoolEntryRef *Symbols, size_t NumSymbols,
  492. LLVMOrcMaterializationResponsibilityRef *Result) {
  493. SymbolNameSet Syms;
  494. for (size_t I = 0; I != NumSymbols; I++) {
  495. Syms.insert(OrcV2CAPIHelper::moveToSymbolStringPtr(unwrap(Symbols[I])));
  496. }
  497. auto OtherMR = unwrap(MR)->delegate(Syms);
  498. if (!OtherMR) {
  499. return wrap(OtherMR.takeError());
  500. }
  501. *Result = wrap(OtherMR->release());
  502. return LLVMErrorSuccess;
  503. }
  504. void LLVMOrcMaterializationResponsibilityAddDependencies(
  505. LLVMOrcMaterializationResponsibilityRef MR,
  506. LLVMOrcSymbolStringPoolEntryRef Name,
  507. LLVMOrcCDependenceMapPairs Dependencies, size_t NumPairs) {
  508. SymbolDependenceMap SDM = toSymbolDependenceMap(Dependencies, NumPairs);
  509. auto Sym = OrcV2CAPIHelper::moveToSymbolStringPtr(unwrap(Name));
  510. unwrap(MR)->addDependencies(Sym, SDM);
  511. }
  512. void LLVMOrcMaterializationResponsibilityAddDependenciesForAll(
  513. LLVMOrcMaterializationResponsibilityRef MR,
  514. LLVMOrcCDependenceMapPairs Dependencies, size_t NumPairs) {
  515. SymbolDependenceMap SDM = toSymbolDependenceMap(Dependencies, NumPairs);
  516. unwrap(MR)->addDependenciesForAll(SDM);
  517. }
  518. void LLVMOrcMaterializationResponsibilityFailMaterialization(
  519. LLVMOrcMaterializationResponsibilityRef MR) {
  520. unwrap(MR)->failMaterialization();
  521. }
  522. void LLVMOrcIRTransformLayerEmit(LLVMOrcIRTransformLayerRef IRLayer,
  523. LLVMOrcMaterializationResponsibilityRef MR,
  524. LLVMOrcThreadSafeModuleRef TSM) {
  525. std::unique_ptr<ThreadSafeModule> TmpTSM(unwrap(TSM));
  526. unwrap(IRLayer)->emit(
  527. std::unique_ptr<MaterializationResponsibility>(unwrap(MR)),
  528. std::move(*TmpTSM));
  529. }
  530. LLVMOrcJITDylibRef
  531. LLVMOrcExecutionSessionCreateBareJITDylib(LLVMOrcExecutionSessionRef ES,
  532. const char *Name) {
  533. return wrap(&unwrap(ES)->createBareJITDylib(Name));
  534. }
  535. LLVMErrorRef
  536. LLVMOrcExecutionSessionCreateJITDylib(LLVMOrcExecutionSessionRef ES,
  537. LLVMOrcJITDylibRef *Result,
  538. const char *Name) {
  539. auto JD = unwrap(ES)->createJITDylib(Name);
  540. if (!JD)
  541. return wrap(JD.takeError());
  542. *Result = wrap(&*JD);
  543. return LLVMErrorSuccess;
  544. }
  545. LLVMOrcJITDylibRef
  546. LLVMOrcExecutionSessionGetJITDylibByName(LLVMOrcExecutionSessionRef ES,
  547. const char *Name) {
  548. return wrap(unwrap(ES)->getJITDylibByName(Name));
  549. }
  550. LLVMErrorRef LLVMOrcJITDylibDefine(LLVMOrcJITDylibRef JD,
  551. LLVMOrcMaterializationUnitRef MU) {
  552. std::unique_ptr<MaterializationUnit> TmpMU(unwrap(MU));
  553. if (auto Err = unwrap(JD)->define(TmpMU)) {
  554. TmpMU.release();
  555. return wrap(std::move(Err));
  556. }
  557. return LLVMErrorSuccess;
  558. }
  559. LLVMErrorRef LLVMOrcJITDylibClear(LLVMOrcJITDylibRef JD) {
  560. return wrap(unwrap(JD)->clear());
  561. }
  562. void LLVMOrcJITDylibAddGenerator(LLVMOrcJITDylibRef JD,
  563. LLVMOrcDefinitionGeneratorRef DG) {
  564. unwrap(JD)->addGenerator(std::unique_ptr<DefinitionGenerator>(unwrap(DG)));
  565. }
  566. LLVMOrcDefinitionGeneratorRef LLVMOrcCreateCustomCAPIDefinitionGenerator(
  567. LLVMOrcCAPIDefinitionGeneratorTryToGenerateFunction F, void *Ctx,
  568. LLVMOrcDisposeCAPIDefinitionGeneratorFunction Dispose) {
  569. auto DG = std::make_unique<CAPIDefinitionGenerator>(Dispose, Ctx, F);
  570. return wrap(DG.release());
  571. }
  572. void LLVMOrcLookupStateContinueLookup(LLVMOrcLookupStateRef S,
  573. LLVMErrorRef Err) {
  574. LookupState LS;
  575. OrcV2CAPIHelper::resetLookupState(LS, ::unwrap(S));
  576. LS.continueLookup(unwrap(Err));
  577. }
  578. LLVMErrorRef LLVMOrcCreateDynamicLibrarySearchGeneratorForProcess(
  579. LLVMOrcDefinitionGeneratorRef *Result, char GlobalPrefix,
  580. LLVMOrcSymbolPredicate Filter, void *FilterCtx) {
  581. assert(Result && "Result can not be null");
  582. assert((Filter || !FilterCtx) &&
  583. "if Filter is null then FilterCtx must also be null");
  584. DynamicLibrarySearchGenerator::SymbolPredicate Pred;
  585. if (Filter)
  586. Pred = [=](const SymbolStringPtr &Name) -> bool {
  587. return Filter(FilterCtx, wrap(OrcV2CAPIHelper::getRawPoolEntryPtr(Name)));
  588. };
  589. auto ProcessSymsGenerator =
  590. DynamicLibrarySearchGenerator::GetForCurrentProcess(GlobalPrefix, Pred);
  591. if (!ProcessSymsGenerator) {
  592. *Result = nullptr;
  593. return wrap(ProcessSymsGenerator.takeError());
  594. }
  595. *Result = wrap(ProcessSymsGenerator->release());
  596. return LLVMErrorSuccess;
  597. }
  598. LLVMErrorRef LLVMOrcCreateDynamicLibrarySearchGeneratorForPath(
  599. LLVMOrcDefinitionGeneratorRef *Result, const char *FileName,
  600. char GlobalPrefix, LLVMOrcSymbolPredicate Filter, void *FilterCtx) {
  601. assert(Result && "Result can not be null");
  602. assert(FileName && "FileName can not be null");
  603. assert((Filter || !FilterCtx) &&
  604. "if Filter is null then FilterCtx must also be null");
  605. DynamicLibrarySearchGenerator::SymbolPredicate Pred;
  606. if (Filter)
  607. Pred = [=](const SymbolStringPtr &Name) -> bool {
  608. return Filter(FilterCtx, wrap(OrcV2CAPIHelper::getRawPoolEntryPtr(Name)));
  609. };
  610. auto LibrarySymsGenerator =
  611. DynamicLibrarySearchGenerator::Load(FileName, GlobalPrefix, Pred);
  612. if (!LibrarySymsGenerator) {
  613. *Result = nullptr;
  614. return wrap(LibrarySymsGenerator.takeError());
  615. }
  616. *Result = wrap(LibrarySymsGenerator->release());
  617. return LLVMErrorSuccess;
  618. }
  619. LLVMErrorRef LLVMOrcCreateStaticLibrarySearchGeneratorForPath(
  620. LLVMOrcDefinitionGeneratorRef *Result, LLVMOrcObjectLayerRef ObjLayer,
  621. const char *FileName, const char *TargetTriple) {
  622. assert(Result && "Result can not be null");
  623. assert(FileName && "Filename can not be null");
  624. assert(ObjLayer && "ObjectLayer can not be null");
  625. if (TargetTriple) {
  626. auto TT = Triple(TargetTriple);
  627. auto LibrarySymsGenerator =
  628. StaticLibraryDefinitionGenerator::Load(*unwrap(ObjLayer), FileName, TT);
  629. if (!LibrarySymsGenerator) {
  630. *Result = nullptr;
  631. return wrap(LibrarySymsGenerator.takeError());
  632. }
  633. *Result = wrap(LibrarySymsGenerator->release());
  634. return LLVMErrorSuccess;
  635. } else {
  636. auto LibrarySymsGenerator =
  637. StaticLibraryDefinitionGenerator::Load(*unwrap(ObjLayer), FileName);
  638. if (!LibrarySymsGenerator) {
  639. *Result = nullptr;
  640. return wrap(LibrarySymsGenerator.takeError());
  641. }
  642. *Result = wrap(LibrarySymsGenerator->release());
  643. return LLVMErrorSuccess;
  644. }
  645. }
  646. LLVMOrcThreadSafeContextRef LLVMOrcCreateNewThreadSafeContext(void) {
  647. return wrap(new ThreadSafeContext(std::make_unique<LLVMContext>()));
  648. }
  649. LLVMContextRef
  650. LLVMOrcThreadSafeContextGetContext(LLVMOrcThreadSafeContextRef TSCtx) {
  651. return wrap(unwrap(TSCtx)->getContext());
  652. }
  653. void LLVMOrcDisposeThreadSafeContext(LLVMOrcThreadSafeContextRef TSCtx) {
  654. delete unwrap(TSCtx);
  655. }
  656. LLVMErrorRef
  657. LLVMOrcThreadSafeModuleWithModuleDo(LLVMOrcThreadSafeModuleRef TSM,
  658. LLVMOrcGenericIRModuleOperationFunction F,
  659. void *Ctx) {
  660. return wrap(unwrap(TSM)->withModuleDo(
  661. [&](Module &M) { return unwrap(F(Ctx, wrap(&M))); }));
  662. }
  663. LLVMOrcThreadSafeModuleRef
  664. LLVMOrcCreateNewThreadSafeModule(LLVMModuleRef M,
  665. LLVMOrcThreadSafeContextRef TSCtx) {
  666. return wrap(
  667. new ThreadSafeModule(std::unique_ptr<Module>(unwrap(M)), *unwrap(TSCtx)));
  668. }
  669. void LLVMOrcDisposeThreadSafeModule(LLVMOrcThreadSafeModuleRef TSM) {
  670. delete unwrap(TSM);
  671. }
  672. LLVMErrorRef LLVMOrcJITTargetMachineBuilderDetectHost(
  673. LLVMOrcJITTargetMachineBuilderRef *Result) {
  674. assert(Result && "Result can not be null");
  675. auto JTMB = JITTargetMachineBuilder::detectHost();
  676. if (!JTMB) {
  677. Result = nullptr;
  678. return wrap(JTMB.takeError());
  679. }
  680. *Result = wrap(new JITTargetMachineBuilder(std::move(*JTMB)));
  681. return LLVMErrorSuccess;
  682. }
  683. LLVMOrcJITTargetMachineBuilderRef
  684. LLVMOrcJITTargetMachineBuilderCreateFromTargetMachine(LLVMTargetMachineRef TM) {
  685. auto *TemplateTM = unwrap(TM);
  686. auto JTMB =
  687. std::make_unique<JITTargetMachineBuilder>(TemplateTM->getTargetTriple());
  688. (*JTMB)
  689. .setCPU(TemplateTM->getTargetCPU().str())
  690. .setRelocationModel(TemplateTM->getRelocationModel())
  691. .setCodeModel(TemplateTM->getCodeModel())
  692. .setCodeGenOptLevel(TemplateTM->getOptLevel())
  693. .setFeatures(TemplateTM->getTargetFeatureString())
  694. .setOptions(TemplateTM->Options);
  695. LLVMDisposeTargetMachine(TM);
  696. return wrap(JTMB.release());
  697. }
  698. void LLVMOrcDisposeJITTargetMachineBuilder(
  699. LLVMOrcJITTargetMachineBuilderRef JTMB) {
  700. delete unwrap(JTMB);
  701. }
  702. char *LLVMOrcJITTargetMachineBuilderGetTargetTriple(
  703. LLVMOrcJITTargetMachineBuilderRef JTMB) {
  704. auto Tmp = unwrap(JTMB)->getTargetTriple().str();
  705. char *TargetTriple = (char *)malloc(Tmp.size() + 1);
  706. strcpy(TargetTriple, Tmp.c_str());
  707. return TargetTriple;
  708. }
  709. void LLVMOrcJITTargetMachineBuilderSetTargetTriple(
  710. LLVMOrcJITTargetMachineBuilderRef JTMB, const char *TargetTriple) {
  711. unwrap(JTMB)->getTargetTriple() = Triple(TargetTriple);
  712. }
  713. LLVMErrorRef LLVMOrcObjectLayerAddObjectFile(LLVMOrcObjectLayerRef ObjLayer,
  714. LLVMOrcJITDylibRef JD,
  715. LLVMMemoryBufferRef ObjBuffer) {
  716. return wrap(unwrap(ObjLayer)->add(
  717. *unwrap(JD), std::unique_ptr<MemoryBuffer>(unwrap(ObjBuffer))));
  718. }
  719. LLVMErrorRef LLVMOrcLLJITAddObjectFileWithRT(LLVMOrcObjectLayerRef ObjLayer,
  720. LLVMOrcResourceTrackerRef RT,
  721. LLVMMemoryBufferRef ObjBuffer) {
  722. return wrap(
  723. unwrap(ObjLayer)->add(ResourceTrackerSP(unwrap(RT)),
  724. std::unique_ptr<MemoryBuffer>(unwrap(ObjBuffer))));
  725. }
  726. void LLVMOrcObjectLayerEmit(LLVMOrcObjectLayerRef ObjLayer,
  727. LLVMOrcMaterializationResponsibilityRef R,
  728. LLVMMemoryBufferRef ObjBuffer) {
  729. unwrap(ObjLayer)->emit(
  730. std::unique_ptr<MaterializationResponsibility>(unwrap(R)),
  731. std::unique_ptr<MemoryBuffer>(unwrap(ObjBuffer)));
  732. }
  733. void LLVMOrcDisposeObjectLayer(LLVMOrcObjectLayerRef ObjLayer) {
  734. delete unwrap(ObjLayer);
  735. }
  736. void LLVMOrcIRTransformLayerSetTransform(
  737. LLVMOrcIRTransformLayerRef IRTransformLayer,
  738. LLVMOrcIRTransformLayerTransformFunction TransformFunction, void *Ctx) {
  739. unwrap(IRTransformLayer)
  740. ->setTransform(
  741. [=](ThreadSafeModule TSM,
  742. MaterializationResponsibility &R) -> Expected<ThreadSafeModule> {
  743. LLVMOrcThreadSafeModuleRef TSMRef =
  744. wrap(new ThreadSafeModule(std::move(TSM)));
  745. if (LLVMErrorRef Err = TransformFunction(Ctx, &TSMRef, wrap(&R))) {
  746. assert(!TSMRef && "TSMRef was not reset to null on error");
  747. return unwrap(Err);
  748. }
  749. assert(TSMRef && "Transform succeeded, but TSMRef was set to null");
  750. ThreadSafeModule Result = std::move(*unwrap(TSMRef));
  751. LLVMOrcDisposeThreadSafeModule(TSMRef);
  752. return std::move(Result);
  753. });
  754. }
  755. void LLVMOrcObjectTransformLayerSetTransform(
  756. LLVMOrcObjectTransformLayerRef ObjTransformLayer,
  757. LLVMOrcObjectTransformLayerTransformFunction TransformFunction, void *Ctx) {
  758. unwrap(ObjTransformLayer)
  759. ->setTransform([TransformFunction, Ctx](std::unique_ptr<MemoryBuffer> Obj)
  760. -> Expected<std::unique_ptr<MemoryBuffer>> {
  761. LLVMMemoryBufferRef ObjBuffer = wrap(Obj.release());
  762. if (LLVMErrorRef Err = TransformFunction(Ctx, &ObjBuffer)) {
  763. assert(!ObjBuffer && "ObjBuffer was not reset to null on error");
  764. return unwrap(Err);
  765. }
  766. return std::unique_ptr<MemoryBuffer>(unwrap(ObjBuffer));
  767. });
  768. }
  769. LLVMOrcDumpObjectsRef LLVMOrcCreateDumpObjects(const char *DumpDir,
  770. const char *IdentifierOverride) {
  771. assert(DumpDir && "DumpDir should not be null");
  772. assert(IdentifierOverride && "IdentifierOverride should not be null");
  773. return wrap(new DumpObjects(DumpDir, IdentifierOverride));
  774. }
  775. void LLVMOrcDisposeDumpObjects(LLVMOrcDumpObjectsRef DumpObjects) {
  776. delete unwrap(DumpObjects);
  777. }
  778. LLVMErrorRef LLVMOrcDumpObjects_CallOperator(LLVMOrcDumpObjectsRef DumpObjects,
  779. LLVMMemoryBufferRef *ObjBuffer) {
  780. std::unique_ptr<MemoryBuffer> OB(unwrap(*ObjBuffer));
  781. if (auto Result = (*unwrap(DumpObjects))(std::move(OB))) {
  782. *ObjBuffer = wrap(Result->release());
  783. return LLVMErrorSuccess;
  784. } else {
  785. *ObjBuffer = nullptr;
  786. return wrap(Result.takeError());
  787. }
  788. }
  789. LLVMOrcLLJITBuilderRef LLVMOrcCreateLLJITBuilder(void) {
  790. return wrap(new LLJITBuilder());
  791. }
  792. void LLVMOrcDisposeLLJITBuilder(LLVMOrcLLJITBuilderRef Builder) {
  793. delete unwrap(Builder);
  794. }
  795. void LLVMOrcLLJITBuilderSetJITTargetMachineBuilder(
  796. LLVMOrcLLJITBuilderRef Builder, LLVMOrcJITTargetMachineBuilderRef JTMB) {
  797. unwrap(Builder)->setJITTargetMachineBuilder(std::move(*unwrap(JTMB)));
  798. LLVMOrcDisposeJITTargetMachineBuilder(JTMB);
  799. }
  800. void LLVMOrcLLJITBuilderSetObjectLinkingLayerCreator(
  801. LLVMOrcLLJITBuilderRef Builder,
  802. LLVMOrcLLJITBuilderObjectLinkingLayerCreatorFunction F, void *Ctx) {
  803. unwrap(Builder)->setObjectLinkingLayerCreator(
  804. [=](ExecutionSession &ES, const Triple &TT) {
  805. auto TTStr = TT.str();
  806. return std::unique_ptr<ObjectLayer>(
  807. unwrap(F(Ctx, wrap(&ES), TTStr.c_str())));
  808. });
  809. }
  810. LLVMErrorRef LLVMOrcCreateLLJIT(LLVMOrcLLJITRef *Result,
  811. LLVMOrcLLJITBuilderRef Builder) {
  812. assert(Result && "Result can not be null");
  813. if (!Builder)
  814. Builder = LLVMOrcCreateLLJITBuilder();
  815. auto J = unwrap(Builder)->create();
  816. LLVMOrcDisposeLLJITBuilder(Builder);
  817. if (!J) {
  818. Result = nullptr;
  819. return wrap(J.takeError());
  820. }
  821. *Result = wrap(J->release());
  822. return LLVMErrorSuccess;
  823. }
  824. LLVMErrorRef LLVMOrcDisposeLLJIT(LLVMOrcLLJITRef J) {
  825. delete unwrap(J);
  826. return LLVMErrorSuccess;
  827. }
  828. LLVMOrcExecutionSessionRef LLVMOrcLLJITGetExecutionSession(LLVMOrcLLJITRef J) {
  829. return wrap(&unwrap(J)->getExecutionSession());
  830. }
  831. LLVMOrcJITDylibRef LLVMOrcLLJITGetMainJITDylib(LLVMOrcLLJITRef J) {
  832. return wrap(&unwrap(J)->getMainJITDylib());
  833. }
  834. const char *LLVMOrcLLJITGetTripleString(LLVMOrcLLJITRef J) {
  835. return unwrap(J)->getTargetTriple().str().c_str();
  836. }
  837. char LLVMOrcLLJITGetGlobalPrefix(LLVMOrcLLJITRef J) {
  838. return unwrap(J)->getDataLayout().getGlobalPrefix();
  839. }
  840. LLVMOrcSymbolStringPoolEntryRef
  841. LLVMOrcLLJITMangleAndIntern(LLVMOrcLLJITRef J, const char *UnmangledName) {
  842. return wrap(OrcV2CAPIHelper::moveFromSymbolStringPtr(
  843. unwrap(J)->mangleAndIntern(UnmangledName)));
  844. }
  845. LLVMErrorRef LLVMOrcLLJITAddObjectFile(LLVMOrcLLJITRef J, LLVMOrcJITDylibRef JD,
  846. LLVMMemoryBufferRef ObjBuffer) {
  847. return wrap(unwrap(J)->addObjectFile(
  848. *unwrap(JD), std::unique_ptr<MemoryBuffer>(unwrap(ObjBuffer))));
  849. }
  850. LLVMErrorRef LLVMOrcLLJITAddObjectFileWithRT(LLVMOrcLLJITRef J,
  851. LLVMOrcResourceTrackerRef RT,
  852. LLVMMemoryBufferRef ObjBuffer) {
  853. return wrap(unwrap(J)->addObjectFile(
  854. ResourceTrackerSP(unwrap(RT)),
  855. std::unique_ptr<MemoryBuffer>(unwrap(ObjBuffer))));
  856. }
  857. LLVMErrorRef LLVMOrcLLJITAddLLVMIRModule(LLVMOrcLLJITRef J,
  858. LLVMOrcJITDylibRef JD,
  859. LLVMOrcThreadSafeModuleRef TSM) {
  860. std::unique_ptr<ThreadSafeModule> TmpTSM(unwrap(TSM));
  861. return wrap(unwrap(J)->addIRModule(*unwrap(JD), std::move(*TmpTSM)));
  862. }
  863. LLVMErrorRef LLVMOrcLLJITAddLLVMIRModuleWithRT(LLVMOrcLLJITRef J,
  864. LLVMOrcResourceTrackerRef RT,
  865. LLVMOrcThreadSafeModuleRef TSM) {
  866. std::unique_ptr<ThreadSafeModule> TmpTSM(unwrap(TSM));
  867. return wrap(unwrap(J)->addIRModule(ResourceTrackerSP(unwrap(RT)),
  868. std::move(*TmpTSM)));
  869. }
  870. LLVMErrorRef LLVMOrcLLJITLookup(LLVMOrcLLJITRef J,
  871. LLVMOrcJITTargetAddress *Result,
  872. const char *Name) {
  873. assert(Result && "Result can not be null");
  874. auto Sym = unwrap(J)->lookup(Name);
  875. if (!Sym) {
  876. *Result = 0;
  877. return wrap(Sym.takeError());
  878. }
  879. *Result = Sym->getValue();
  880. return LLVMErrorSuccess;
  881. }
  882. LLVMOrcObjectLayerRef LLVMOrcLLJITGetObjLinkingLayer(LLVMOrcLLJITRef J) {
  883. return wrap(&unwrap(J)->getObjLinkingLayer());
  884. }
  885. LLVMOrcObjectTransformLayerRef
  886. LLVMOrcLLJITGetObjTransformLayer(LLVMOrcLLJITRef J) {
  887. return wrap(&unwrap(J)->getObjTransformLayer());
  888. }
  889. LLVMOrcObjectLayerRef
  890. LLVMOrcCreateRTDyldObjectLinkingLayerWithSectionMemoryManager(
  891. LLVMOrcExecutionSessionRef ES) {
  892. assert(ES && "ES must not be null");
  893. return wrap(new RTDyldObjectLinkingLayer(
  894. *unwrap(ES), [] { return std::make_unique<SectionMemoryManager>(); }));
  895. }
  896. LLVMOrcObjectLayerRef
  897. LLVMOrcCreateRTDyldObjectLinkingLayerWithMCJITMemoryManagerLikeCallbacks(
  898. LLVMOrcExecutionSessionRef ES, void *CreateContextCtx,
  899. LLVMMemoryManagerCreateContextCallback CreateContext,
  900. LLVMMemoryManagerNotifyTerminatingCallback NotifyTerminating,
  901. LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
  902. LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
  903. LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
  904. LLVMMemoryManagerDestroyCallback Destroy) {
  905. struct MCJITMemoryManagerLikeCallbacks {
  906. MCJITMemoryManagerLikeCallbacks() = default;
  907. MCJITMemoryManagerLikeCallbacks(
  908. void *CreateContextCtx,
  909. LLVMMemoryManagerCreateContextCallback CreateContext,
  910. LLVMMemoryManagerNotifyTerminatingCallback NotifyTerminating,
  911. LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
  912. LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
  913. LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
  914. LLVMMemoryManagerDestroyCallback Destroy)
  915. : CreateContextCtx(CreateContextCtx), CreateContext(CreateContext),
  916. NotifyTerminating(NotifyTerminating),
  917. AllocateCodeSection(AllocateCodeSection),
  918. AllocateDataSection(AllocateDataSection),
  919. FinalizeMemory(FinalizeMemory), Destroy(Destroy) {}
  920. MCJITMemoryManagerLikeCallbacks(MCJITMemoryManagerLikeCallbacks &&Other) {
  921. std::swap(CreateContextCtx, Other.CreateContextCtx);
  922. std::swap(CreateContext, Other.CreateContext);
  923. std::swap(NotifyTerminating, Other.NotifyTerminating);
  924. std::swap(AllocateCodeSection, Other.AllocateCodeSection);
  925. std::swap(AllocateDataSection, Other.AllocateDataSection);
  926. std::swap(FinalizeMemory, Other.FinalizeMemory);
  927. std::swap(Destroy, Other.Destroy);
  928. }
  929. ~MCJITMemoryManagerLikeCallbacks() {
  930. if (NotifyTerminating)
  931. NotifyTerminating(CreateContextCtx);
  932. }
  933. void *CreateContextCtx = nullptr;
  934. LLVMMemoryManagerCreateContextCallback CreateContext = nullptr;
  935. LLVMMemoryManagerNotifyTerminatingCallback NotifyTerminating = nullptr;
  936. LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection = nullptr;
  937. LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection = nullptr;
  938. LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory = nullptr;
  939. LLVMMemoryManagerDestroyCallback Destroy = nullptr;
  940. };
  941. class MCJITMemoryManagerLikeCallbacksMemMgr : public RTDyldMemoryManager {
  942. public:
  943. MCJITMemoryManagerLikeCallbacksMemMgr(
  944. const MCJITMemoryManagerLikeCallbacks &CBs)
  945. : CBs(CBs) {
  946. Opaque = CBs.CreateContext(CBs.CreateContextCtx);
  947. }
  948. ~MCJITMemoryManagerLikeCallbacksMemMgr() override { CBs.Destroy(Opaque); }
  949. uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
  950. unsigned SectionID,
  951. StringRef SectionName) override {
  952. return CBs.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
  953. SectionName.str().c_str());
  954. }
  955. uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
  956. unsigned SectionID, StringRef SectionName,
  957. bool isReadOnly) override {
  958. return CBs.AllocateDataSection(Opaque, Size, Alignment, SectionID,
  959. SectionName.str().c_str(), isReadOnly);
  960. }
  961. bool finalizeMemory(std::string *ErrMsg) override {
  962. char *ErrMsgCString = nullptr;
  963. bool Result = CBs.FinalizeMemory(Opaque, &ErrMsgCString);
  964. assert((Result || !ErrMsgCString) &&
  965. "Did not expect an error message if FinalizeMemory succeeded");
  966. if (ErrMsgCString) {
  967. if (ErrMsg)
  968. *ErrMsg = ErrMsgCString;
  969. free(ErrMsgCString);
  970. }
  971. return Result;
  972. }
  973. private:
  974. const MCJITMemoryManagerLikeCallbacks &CBs;
  975. void *Opaque = nullptr;
  976. };
  977. assert(ES && "ES must not be null");
  978. assert(CreateContext && "CreateContext must not be null");
  979. assert(NotifyTerminating && "NotifyTerminating must not be null");
  980. assert(AllocateCodeSection && "AllocateCodeSection must not be null");
  981. assert(AllocateDataSection && "AllocateDataSection must not be null");
  982. assert(FinalizeMemory && "FinalizeMemory must not be null");
  983. assert(Destroy && "Destroy must not be null");
  984. MCJITMemoryManagerLikeCallbacks CBs(
  985. CreateContextCtx, CreateContext, NotifyTerminating, AllocateCodeSection,
  986. AllocateDataSection, FinalizeMemory, Destroy);
  987. return wrap(new RTDyldObjectLinkingLayer(*unwrap(ES), [CBs = std::move(CBs)] {
  988. return std::make_unique<MCJITMemoryManagerLikeCallbacksMemMgr>(CBs);
  989. }));
  990. return nullptr;
  991. }
  992. void LLVMOrcRTDyldObjectLinkingLayerRegisterJITEventListener(
  993. LLVMOrcObjectLayerRef RTDyldObjLinkingLayer,
  994. LLVMJITEventListenerRef Listener) {
  995. assert(RTDyldObjLinkingLayer && "RTDyldObjLinkingLayer must not be null");
  996. assert(Listener && "Listener must not be null");
  997. reinterpret_cast<RTDyldObjectLinkingLayer *>(unwrap(RTDyldObjLinkingLayer))
  998. ->registerJITEventListener(*unwrap(Listener));
  999. }
  1000. LLVMOrcIRTransformLayerRef LLVMOrcLLJITGetIRTransformLayer(LLVMOrcLLJITRef J) {
  1001. return wrap(&unwrap(J)->getIRTransformLayer());
  1002. }
  1003. const char *LLVMOrcLLJITGetDataLayoutStr(LLVMOrcLLJITRef J) {
  1004. return unwrap(J)->getDataLayout().getStringRepresentation().c_str();
  1005. }
  1006. LLVMOrcIndirectStubsManagerRef
  1007. LLVMOrcCreateLocalIndirectStubsManager(const char *TargetTriple) {
  1008. auto builder = createLocalIndirectStubsManagerBuilder(Triple(TargetTriple));
  1009. return wrap(builder().release());
  1010. }
  1011. void LLVMOrcDisposeIndirectStubsManager(LLVMOrcIndirectStubsManagerRef ISM) {
  1012. std::unique_ptr<IndirectStubsManager> TmpISM(unwrap(ISM));
  1013. }
  1014. LLVMErrorRef LLVMOrcCreateLocalLazyCallThroughManager(
  1015. const char *TargetTriple, LLVMOrcExecutionSessionRef ES,
  1016. LLVMOrcJITTargetAddress ErrorHandlerAddr,
  1017. LLVMOrcLazyCallThroughManagerRef *Result) {
  1018. auto LCTM = createLocalLazyCallThroughManager(Triple(TargetTriple),
  1019. *unwrap(ES), ErrorHandlerAddr);
  1020. if (!LCTM)
  1021. return wrap(LCTM.takeError());
  1022. *Result = wrap(LCTM->release());
  1023. return LLVMErrorSuccess;
  1024. }
  1025. void LLVMOrcDisposeLazyCallThroughManager(
  1026. LLVMOrcLazyCallThroughManagerRef LCM) {
  1027. std::unique_ptr<LazyCallThroughManager> TmpLCM(unwrap(LCM));
  1028. }