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