1//===-- ExecutionEngineBindings.cpp - C bindings for EEs ------------------===//
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// This file defines the C bindings for the ExecutionEngine library.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm-c/ExecutionEngine.h"
14#include "llvm/ExecutionEngine/ExecutionEngine.h"
15#include "llvm/ExecutionEngine/GenericValue.h"
16#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
17#include "llvm/IR/DerivedTypes.h"
18#include "llvm/IR/Module.h"
19#include "llvm/Support/ErrorHandling.h"
20#include "llvm/Target/CodeGenCWrappers.h"
21#include "llvm/Target/TargetOptions.h"
22#include <cstring>
23#include <optional>
24
25using namespace llvm;
26
27#define DEBUG_TYPE "jit"
28
29// Wrapping the C bindings types.
30DEFINE_SIMPLE_CONVERSION_FUNCTIONS(GenericValue, LLVMGenericValueRef)
31
32
33static LLVMTargetMachineRef wrap(const TargetMachine *P) {
34 return
35 reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine*>(P));
36}
37
38/*===-- Operations on generic values --------------------------------------===*/
39
40LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,
41 unsigned long long N,
42 LLVMBool IsSigned) {
43 GenericValue *GenVal = new GenericValue();
44 GenVal->IntVal = APInt(unwrap<IntegerType>(P: Ty)->getBitWidth(), N, IsSigned);
45 return wrap(P: GenVal);
46}
47
48LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P) {
49 GenericValue *GenVal = new GenericValue();
50 GenVal->PointerVal = P;
51 return wrap(P: GenVal);
52}
53
54LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N) {
55 GenericValue *GenVal = new GenericValue();
56 switch (unwrap(P: TyRef)->getTypeID()) {
57 case Type::FloatTyID:
58 GenVal->FloatVal = N;
59 break;
60 case Type::DoubleTyID:
61 GenVal->DoubleVal = N;
62 break;
63 default:
64 llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
65 }
66 return wrap(P: GenVal);
67}
68
69unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef) {
70 return unwrap(P: GenValRef)->IntVal.getBitWidth();
71}
72
73unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,
74 LLVMBool IsSigned) {
75 GenericValue *GenVal = unwrap(P: GenValRef);
76 if (IsSigned)
77 return GenVal->IntVal.getSExtValue();
78 else
79 return GenVal->IntVal.getZExtValue();
80}
81
82void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal) {
83 return unwrap(P: GenVal)->PointerVal;
84}
85
86double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal) {
87 switch (unwrap(P: TyRef)->getTypeID()) {
88 case Type::FloatTyID:
89 return unwrap(P: GenVal)->FloatVal;
90 case Type::DoubleTyID:
91 return unwrap(P: GenVal)->DoubleVal;
92 default:
93 llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
94 }
95}
96
97void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
98 delete unwrap(P: GenVal);
99}
100
101/*===-- Operations on execution engines -----------------------------------===*/
102
103LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE,
104 LLVMModuleRef M,
105 char **OutError) {
106 std::string Error;
107 TargetOptions TO;
108 TO.MCOptions.LibraryOptions = &unwrap(P: M)->getContext().getLibraryOptions();
109 EngineBuilder builder(std::unique_ptr<Module>(unwrap(P: M)));
110 builder.setEngineKind(EngineKind::Either)
111 .setErrorStr(&Error)
112 .setTargetOptions(TO);
113 if (ExecutionEngine *EE = builder.create()){
114 *OutEE = wrap(P: EE);
115 return 0;
116 }
117 *OutError = strdup(s: Error.c_str());
118 return 1;
119}
120
121LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp,
122 LLVMModuleRef M,
123 char **OutError) {
124 std::string Error;
125 EngineBuilder builder(std::unique_ptr<Module>(unwrap(P: M)));
126 builder.setEngineKind(EngineKind::Interpreter)
127 .setErrorStr(&Error);
128 if (ExecutionEngine *Interp = builder.create()) {
129 *OutInterp = wrap(P: Interp);
130 return 0;
131 }
132 *OutError = strdup(s: Error.c_str());
133 return 1;
134}
135
136LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
137 LLVMModuleRef M,
138 unsigned OptLevel,
139 char **OutError) {
140 std::string Error;
141 TargetOptions TO;
142 TO.MCOptions.LibraryOptions = &unwrap(P: M)->getContext().getLibraryOptions();
143 EngineBuilder builder(std::unique_ptr<Module>(unwrap(P: M)));
144 builder.setEngineKind(EngineKind::JIT)
145 .setErrorStr(&Error)
146 .setOptLevel((CodeGenOptLevel)OptLevel)
147 .setTargetOptions(TO);
148 if (ExecutionEngine *JIT = builder.create()) {
149 *OutJIT = wrap(P: JIT);
150 return 0;
151 }
152 *OutError = strdup(s: Error.c_str());
153 return 1;
154}
155
156void LLVMInitializeMCJITCompilerOptions(LLVMMCJITCompilerOptions *PassedOptions,
157 size_t SizeOfPassedOptions) {
158 LLVMMCJITCompilerOptions options;
159 memset(s: &options, c: 0, n: sizeof(options)); // Most fields are zero by default.
160 options.CodeModel = LLVMCodeModelJITDefault;
161
162 memcpy(dest: PassedOptions, src: &options,
163 n: std::min(a: sizeof(options), b: SizeOfPassedOptions));
164}
165
166LLVMBool LLVMCreateMCJITCompilerForModule(
167 LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M,
168 LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions,
169 char **OutError) {
170 LLVMMCJITCompilerOptions options;
171 // If the user passed a larger sized options struct, then they were compiled
172 // against a newer LLVM. Tell them that something is wrong.
173 if (SizeOfPassedOptions > sizeof(options)) {
174 *OutError = strdup(
175 s: "Refusing to use options struct that is larger than my own; assuming "
176 "LLVM library mismatch.");
177 return 1;
178 }
179
180 // Defend against the user having an old version of the API by ensuring that
181 // any fields they didn't see are cleared. We must defend against fields being
182 // set to the bitwise equivalent of zero, and assume that this means "do the
183 // default" as if that option hadn't been available.
184 LLVMInitializeMCJITCompilerOptions(PassedOptions: &options, SizeOfPassedOptions: sizeof(options));
185 memcpy(dest: &options, src: PassedOptions, n: SizeOfPassedOptions);
186
187 TargetOptions targetOptions;
188 targetOptions.EnableFastISel = options.EnableFastISel;
189 targetOptions.MCOptions.LibraryOptions =
190 &unwrap(P: M)->getContext().getLibraryOptions();
191 std::unique_ptr<Module> Mod(unwrap(P: M));
192
193 if (Mod)
194 // Set function attribute "frame-pointer" based on
195 // NoFramePointerElim.
196 for (auto &F : *Mod) {
197 auto Attrs = F.getAttributes();
198 StringRef Value = options.NoFramePointerElim ? "all" : "none";
199 Attrs = Attrs.addFnAttribute(C&: F.getContext(), Kind: "frame-pointer", Value);
200 F.setAttributes(Attrs);
201 }
202
203 std::string Error;
204 EngineBuilder builder(std::move(Mod));
205 builder.setEngineKind(EngineKind::JIT)
206 .setErrorStr(&Error)
207 .setOptLevel((CodeGenOptLevel)options.OptLevel)
208 .setTargetOptions(targetOptions);
209 bool JIT;
210 if (std::optional<CodeModel::Model> CM = unwrap(Model: options.CodeModel, JIT))
211 builder.setCodeModel(*CM);
212 if (options.MCJMM)
213 builder.setMCJITMemoryManager(
214 std::unique_ptr<RTDyldMemoryManager>(unwrap(P: options.MCJMM)));
215 if (ExecutionEngine *JIT = builder.create()) {
216 *OutJIT = wrap(P: JIT);
217 return 0;
218 }
219 *OutError = strdup(s: Error.c_str());
220 return 1;
221}
222
223void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE) {
224 delete unwrap(P: EE);
225}
226
227void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE) {
228 unwrap(P: EE)->finalizeObject();
229 unwrap(P: EE)->runStaticConstructorsDestructors(isDtors: false);
230}
231
232void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE) {
233 unwrap(P: EE)->finalizeObject();
234 unwrap(P: EE)->runStaticConstructorsDestructors(isDtors: true);
235}
236
237int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
238 unsigned ArgC, const char * const *ArgV,
239 const char * const *EnvP) {
240 unwrap(P: EE)->finalizeObject();
241
242 std::vector<std::string> ArgVec(ArgV, ArgV + ArgC);
243 return unwrap(P: EE)->runFunctionAsMain(Fn: unwrap<Function>(P: F), argv: ArgVec, envp: EnvP);
244}
245
246LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
247 unsigned NumArgs,
248 LLVMGenericValueRef *Args) {
249 unwrap(P: EE)->finalizeObject();
250
251 std::vector<GenericValue> ArgVec;
252 ArgVec.reserve(n: NumArgs);
253 for (unsigned I = 0; I != NumArgs; ++I)
254 ArgVec.push_back(x: *unwrap(P: Args[I]));
255
256 GenericValue *Result = new GenericValue();
257 *Result = unwrap(P: EE)->runFunction(F: unwrap<Function>(P: F), ArgValues: ArgVec);
258 return wrap(P: Result);
259}
260
261void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F) {
262}
263
264void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M){
265 unwrap(P: EE)->addModule(M: std::unique_ptr<Module>(unwrap(P: M)));
266}
267
268LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
269 LLVMModuleRef *OutMod, char **OutError) {
270 Module *Mod = unwrap(P: M);
271 unwrap(P: EE)->removeModule(M: Mod);
272 *OutMod = wrap(P: Mod);
273 return 0;
274}
275
276LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
277 LLVMValueRef *OutFn) {
278 if (Function *F = unwrap(P: EE)->FindFunctionNamed(FnName: Name)) {
279 *OutFn = wrap(P: F);
280 return 0;
281 }
282 return 1;
283}
284
285void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
286 LLVMValueRef Fn) {
287 return nullptr;
288}
289
290LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE) {
291 return wrap(P: &unwrap(P: EE)->getDataLayout());
292}
293
294LLVMTargetMachineRef
295LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE) {
296 return wrap(P: unwrap(P: EE)->getTargetMachine());
297}
298
299void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
300 void* Addr) {
301 unwrap(P: EE)->addGlobalMapping(GV: unwrap<GlobalValue>(P: Global), Addr);
302}
303
304void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global) {
305 unwrap(P: EE)->finalizeObject();
306
307 return unwrap(P: EE)->getPointerToGlobal(GV: unwrap<GlobalValue>(P: Global));
308}
309
310uint64_t LLVMGetGlobalValueAddress(LLVMExecutionEngineRef EE, const char *Name) {
311 return unwrap(P: EE)->getGlobalValueAddress(Name);
312}
313
314uint64_t LLVMGetFunctionAddress(LLVMExecutionEngineRef EE, const char *Name) {
315 return unwrap(P: EE)->getFunctionAddress(Name);
316}
317
318LLVMBool LLVMExecutionEngineGetErrMsg(LLVMExecutionEngineRef EE,
319 char **OutError) {
320 assert(OutError && "OutError must be non-null");
321 auto *ExecEngine = unwrap(P: EE);
322 if (ExecEngine->hasError()) {
323 *OutError = strdup(s: ExecEngine->getErrorMessage().c_str());
324 ExecEngine->clearErrorMessage();
325 return true;
326 }
327 return false;
328}
329
330/*===-- Operations on memory managers -------------------------------------===*/
331
332namespace {
333
334struct SimpleBindingMMFunctions {
335 LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection;
336 LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection;
337 LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory;
338 LLVMMemoryManagerDestroyCallback Destroy;
339};
340
341class SimpleBindingMemoryManager : public RTDyldMemoryManager {
342public:
343 SimpleBindingMemoryManager(const SimpleBindingMMFunctions& Functions,
344 void *Opaque);
345 ~SimpleBindingMemoryManager() override;
346
347 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
348 unsigned SectionID,
349 StringRef SectionName) override;
350
351 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
352 unsigned SectionID, StringRef SectionName,
353 bool isReadOnly) override;
354
355 bool finalizeMemory(std::string *ErrMsg) override;
356
357private:
358 SimpleBindingMMFunctions Functions;
359 void *Opaque;
360};
361
362SimpleBindingMemoryManager::SimpleBindingMemoryManager(
363 const SimpleBindingMMFunctions& Functions,
364 void *Opaque)
365 : Functions(Functions), Opaque(Opaque) {
366 assert(Functions.AllocateCodeSection &&
367 "No AllocateCodeSection function provided!");
368 assert(Functions.AllocateDataSection &&
369 "No AllocateDataSection function provided!");
370 assert(Functions.FinalizeMemory &&
371 "No FinalizeMemory function provided!");
372 assert(Functions.Destroy &&
373 "No Destroy function provided!");
374}
375
376SimpleBindingMemoryManager::~SimpleBindingMemoryManager() {
377 Functions.Destroy(Opaque);
378}
379
380uint8_t *SimpleBindingMemoryManager::allocateCodeSection(
381 uintptr_t Size, unsigned Alignment, unsigned SectionID,
382 StringRef SectionName) {
383 return Functions.AllocateCodeSection(Opaque, Size, Alignment, SectionID,
384 SectionName.str().c_str());
385}
386
387uint8_t *SimpleBindingMemoryManager::allocateDataSection(
388 uintptr_t Size, unsigned Alignment, unsigned SectionID,
389 StringRef SectionName, bool isReadOnly) {
390 return Functions.AllocateDataSection(Opaque, Size, Alignment, SectionID,
391 SectionName.str().c_str(),
392 isReadOnly);
393}
394
395bool SimpleBindingMemoryManager::finalizeMemory(std::string *ErrMsg) {
396 char *errMsgCString = nullptr;
397 bool result = Functions.FinalizeMemory(Opaque, &errMsgCString);
398 assert((result || !errMsgCString) &&
399 "Did not expect an error message if FinalizeMemory succeeded");
400 if (errMsgCString) {
401 if (ErrMsg)
402 *ErrMsg = errMsgCString;
403 free(ptr: errMsgCString);
404 }
405 return result;
406}
407
408} // anonymous namespace
409
410LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
411 void *Opaque,
412 LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
413 LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
414 LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
415 LLVMMemoryManagerDestroyCallback Destroy) {
416
417 if (!AllocateCodeSection || !AllocateDataSection || !FinalizeMemory ||
418 !Destroy)
419 return nullptr;
420
421 SimpleBindingMMFunctions functions;
422 functions.AllocateCodeSection = AllocateCodeSection;
423 functions.AllocateDataSection = AllocateDataSection;
424 functions.FinalizeMemory = FinalizeMemory;
425 functions.Destroy = Destroy;
426 return wrap(P: new SimpleBindingMemoryManager(functions, Opaque));
427}
428
429void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM) {
430 delete unwrap(P: MM);
431}
432
433/*===-- JIT Event Listener functions -------------------------------------===*/
434
435
436#if !LLVM_USE_INTEL_JITEVENTS
437LLVMJITEventListenerRef LLVMCreateIntelJITEventListener(void)
438{
439 return nullptr;
440}
441#endif
442
443#if !LLVM_USE_OPROFILE
444LLVMJITEventListenerRef LLVMCreateOProfileJITEventListener(void)
445{
446 return nullptr;
447}
448#endif
449
450#if !LLVM_USE_PERF
451LLVMJITEventListenerRef LLVMCreatePerfJITEventListener(void)
452{
453 return nullptr;
454}
455#endif
456