LLVM 24.0.0git
ExecutionEngineBindings.cpp
Go to the documentation of this file.
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
18#include "llvm/IR/Module.h"
22#include <cstring>
23#include <optional>
24
25using namespace llvm;
26
27#define DEBUG_TYPE "jit"
28
29// Wrapping the C bindings types.
31
32
34 return
35 reinterpret_cast<LLVMTargetMachineRef>(const_cast<TargetMachine*>(P));
36}
37
38/*===-- Operations on generic values --------------------------------------===*/
39
41 unsigned long long N,
42 LLVMBool IsSigned) {
43 GenericValue *GenVal = new GenericValue();
44 GenVal->IntVal = APInt(unwrap<IntegerType>(Ty)->getBitWidth(), N, IsSigned);
45 return wrap(GenVal);
46}
47
49 GenericValue *GenVal = new GenericValue();
50 GenVal->PointerVal = P;
51 return wrap(GenVal);
52}
53
55 GenericValue *GenVal = new GenericValue();
56 switch (unwrap(TyRef)->getTypeID()) {
57 case Type::FloatTyID:
58 GenVal->FloatVal = N;
59 break;
61 GenVal->DoubleVal = N;
62 break;
63 default:
64 llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
65 }
66 return wrap(GenVal);
67}
68
70 return unwrap(GenValRef)->IntVal.getBitWidth();
71}
72
73unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef,
74 LLVMBool IsSigned) {
75 GenericValue *GenVal = unwrap(GenValRef);
76 if (IsSigned)
77 return GenVal->IntVal.getSExtValue();
78 else
79 return GenVal->IntVal.getZExtValue();
80}
81
83 return unwrap(GenVal)->PointerVal;
84}
85
87 switch (unwrap(TyRef)->getTypeID()) {
88 case Type::FloatTyID:
89 return unwrap(GenVal)->FloatVal;
91 return unwrap(GenVal)->DoubleVal;
92 default:
93 llvm_unreachable("LLVMGenericValueToFloat supports only float and double.");
94 }
95}
96
98 delete unwrap(GenVal);
99}
100
101/*===-- Operations on execution engines -----------------------------------===*/
102
105 char **OutError) {
106 std::string Error;
107 TargetOptions TO;
108 TO.MCOptions.LibraryOptions = &unwrap(M)->getContext().getLibraryOptions();
109 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
112 .setTargetOptions(TO);
113 if (ExecutionEngine *EE = builder.create()){
114 *OutEE = wrap(EE);
115 return 0;
116 }
117 *OutError = strdup(Error.c_str());
118 return 1;
119}
120
123 char **OutError) {
124 std::string Error;
125 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
128 if (ExecutionEngine *Interp = builder.create()) {
129 *OutInterp = wrap(Interp);
130 return 0;
131 }
132 *OutError = strdup(Error.c_str());
133 return 1;
134}
135
138 unsigned OptLevel,
139 char **OutError) {
140 std::string Error;
141 TargetOptions TO;
142 TO.MCOptions.LibraryOptions = &unwrap(M)->getContext().getLibraryOptions();
143 EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
146 .setOptLevel((CodeGenOptLevel)OptLevel)
147 .setTargetOptions(TO);
148 if (ExecutionEngine *JIT = builder.create()) {
149 *OutJIT = wrap(JIT);
150 return 0;
151 }
152 *OutError = strdup(Error.c_str());
153 return 1;
154}
155
157 size_t SizeOfPassedOptions) {
159 memset(&options, 0, sizeof(options)); // Most fields are zero by default.
160 options.CodeModel = LLVMCodeModelJITDefault;
161
162 memcpy(PassedOptions, &options,
163 std::min(sizeof(options), SizeOfPassedOptions));
164}
165
168 LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions,
169 char **OutError) {
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 "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(&options, sizeof(options));
185 memcpy(&options, PassedOptions, SizeOfPassedOptions);
186
187 TargetOptions targetOptions;
188 targetOptions.EnableFastISel = options.EnableFastISel;
189 targetOptions.MCOptions.LibraryOptions =
190 &unwrap(M)->getContext().getLibraryOptions();
191 std::unique_ptr<Module> Mod(unwrap(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(F.getContext(), "frame-pointer", Value);
200 F.setAttributes(Attrs);
201 }
202
203 std::string Error;
204 EngineBuilder builder(std::move(Mod));
207 .setOptLevel((CodeGenOptLevel)options.OptLevel)
208 .setTargetOptions(targetOptions);
209 bool JIT;
210 if (std::optional<CodeModel::Model> CM = unwrap(options.CodeModel, JIT))
211 builder.setCodeModel(*CM);
212 if (options.MCJMM)
213 builder.setMCJITMemoryManager(
214 std::unique_ptr<RTDyldMemoryManager>(unwrap(options.MCJMM)));
215 if (ExecutionEngine *JIT = builder.create()) {
216 *OutJIT = wrap(JIT);
217 return 0;
218 }
219 *OutError = strdup(Error.c_str());
220 return 1;
221}
222
226
228 unwrap(EE)->finalizeObject();
229 unwrap(EE)->runStaticConstructorsDestructors(false);
230}
231
233 unwrap(EE)->finalizeObject();
234 unwrap(EE)->runStaticConstructorsDestructors(true);
235}
236
238 unsigned ArgC, const char * const *ArgV,
239 const char * const *EnvP) {
240 unwrap(EE)->finalizeObject();
241
242 std::vector<std::string> ArgVec(ArgV, ArgV + ArgC);
243 return unwrap(EE)->runFunctionAsMain(unwrap<Function>(F), ArgVec, EnvP);
244}
245
247 unsigned NumArgs,
248 LLVMGenericValueRef *Args) {
249 unwrap(EE)->finalizeObject();
250
251 std::vector<GenericValue> ArgVec;
252 ArgVec.reserve(NumArgs);
253 for (unsigned I = 0; I != NumArgs; ++I)
254 ArgVec.push_back(*unwrap(Args[I]));
255
256 GenericValue *Result = new GenericValue();
257 *Result = unwrap(EE)->runFunction(unwrap<Function>(F), ArgVec);
258 return wrap(Result);
259}
260
263
265 unwrap(EE)->addModule(std::unique_ptr<Module>(unwrap(M)));
266}
267
269 LLVMModuleRef *OutMod, char **OutError) {
270 Module *Mod = unwrap(M);
271 unwrap(EE)->removeModule(Mod);
272 *OutMod = wrap(Mod);
273 return 0;
274}
275
277 LLVMValueRef *OutFn) {
278 if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) {
279 *OutFn = wrap(F);
280 return 0;
281 }
282 return 1;
283}
284
286 LLVMValueRef Fn) {
287 return nullptr;
288}
289
293
296 return wrap(unwrap(EE)->getTargetMachine());
297}
298
300 void* Addr) {
301 unwrap(EE)->addGlobalMapping(unwrap<GlobalValue>(Global), Addr);
302}
303
305 unwrap(EE)->finalizeObject();
306
307 return unwrap(EE)->getPointerToGlobal(unwrap<GlobalValue>(Global));
308}
309
311 return unwrap(EE)->getGlobalValueAddress(Name);
312}
313
315 return unwrap(EE)->getFunctionAddress(Name);
316}
317
319 char **OutError) {
320 assert(OutError && "OutError must be non-null");
321 auto *ExecEngine = unwrap(EE);
322 if (ExecEngine->hasError()) {
323 *OutError = strdup(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 {
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(errMsgCString);
404 }
405 return result;
406}
407
408} // anonymous namespace
409
411 void *Opaque,
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(new SimpleBindingMemoryManager(functions, Opaque));
427}
428
432
433/*===-- JIT Event Listener functions -------------------------------------===*/
434
435
436#if !LLVM_USE_INTEL_JITEVENTS
441#endif
442
443#if !LLVM_USE_OPROFILE
448#endif
449
450#if !LLVM_USE_PERF
452{
453 return nullptr;
454}
455#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
Lower uses of LDS variables from non kernel functions
#define DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref)
static char getTypeID(Type *Ty)
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define P(N)
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
Builder class for ExecutionEngines.
EngineBuilder & setTargetOptions(const TargetOptions &Opts)
setTargetOptions - Set the target options that the ExecutionEngine target is using.
LLVM_ABI EngineBuilder & setMCJITMemoryManager(std::unique_ptr< RTDyldMemoryManager > mcjmm)
setMCJITMemoryManager - Sets the MCJIT memory manager to use.
EngineBuilder & setCodeModel(CodeModel::Model M)
setCodeModel - Set the CodeModel that the ExecutionEngine target data is using.
EngineBuilder & setOptLevel(CodeGenOptLevel l)
setOptLevel - Set the optimization level for the JIT.
EngineBuilder & setErrorStr(std::string *e)
setErrorStr - Set the error string to write to on error.
EngineBuilder & setEngineKind(EngineKind::Kind w)
setEngineKind - Controls whether the user wants the interpreter, the JIT, or whichever engine works.
ExecutionEngine * create()
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Abstract interface for implementation execution of LLVM modules, designed to support both interpreter...
const cl::LibraryOptionsContext * LibraryOptions
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Primary interface to the complete machine description for the target machine.
MCTargetOptions MCOptions
Machine level options.
unsigned EnableFastISel
EnableFastISel - This flag enables fast-path instruction selection which trades away generated code q...
@ FloatTyID
32-bit floating point type
Definition Type.h:59
@ DoubleTyID
64-bit floating point type
Definition Type.h:60
LLVM Value Representation.
Definition Value.h:75
uint64_t LLVMGetGlobalValueAddress(LLVMExecutionEngineRef EE, const char *Name)
void * LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE, LLVMValueRef Fn)
void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global, void *Addr)
LLVMBool LLVMCreateMCJITCompilerForModule(LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M, LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions, char **OutError)
Create an MCJIT execution engine for a module, with the given options.
LLVM_C_ABI LLVMJITEventListenerRef LLVMCreateOProfileJITEventListener(void)
LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F, unsigned NumArgs, LLVMGenericValueRef *Args)
LLVM_C_ABI LLVMJITEventListenerRef LLVMCreateIntelJITEventListener(void)
LLVM_C_ABI LLVMJITEventListenerRef LLVMCreatePerfJITEventListener(void)
unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenValRef, LLVMBool IsSigned)
void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F)
LLVM_C_ABI void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM)
LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE, LLVMModuleRef M, char **OutError)
struct LLVMOpaqueMCJITMemoryManager * LLVMMCJITMemoryManagerRef
void * LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global)
void(* LLVMMemoryManagerDestroyCallback)(void *Opaque)
uint64_t LLVMGetFunctionAddress(LLVMExecutionEngineRef EE, const char *Name)
struct LLVMOpaqueExecutionEngine * LLVMExecutionEngineRef
LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty, unsigned long long N, LLVMBool IsSigned)
int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F, unsigned ArgC, const char *const *ArgV, const char *const *EnvP)
LLVMTargetMachineRef LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE)
void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE)
double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal)
LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M, LLVMModuleRef *OutMod, char **OutError)
LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE)
void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal)
LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp, LLVMModuleRef M, char **OutError)
struct LLVMOpaqueGenericValue * LLVMGenericValueRef
LLVMBool(* LLVMMemoryManagerFinalizeMemoryCallback)(void *Opaque, char **ErrMsg)
LLVMBool LLVMExecutionEngineGetErrMsg(LLVMExecutionEngineRef EE, char **OutError)
Returns true on error, false on success.
void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE)
void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M)
void LLVMInitializeMCJITCompilerOptions(LLVMMCJITCompilerOptions *PassedOptions, size_t SizeOfPassedOptions)
LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name, LLVMValueRef *OutFn)
uint8_t *(* LLVMMemoryManagerAllocateDataSectionCallback)(void *Opaque, uintptr_t Size, unsigned Alignment, unsigned SectionID, const char *SectionName, LLVMBool IsReadOnly)
LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P)
unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef)
void * LLVMGenericValueToPointer(LLVMGenericValueRef GenVal)
LLVM_C_ABI LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(void *Opaque, LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection, LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection, LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory, LLVMMemoryManagerDestroyCallback Destroy)
Create a simple custom MCJIT memory manager.
uint8_t *(* LLVMMemoryManagerAllocateCodeSectionCallback)(void *Opaque, uintptr_t Size, unsigned Alignment, unsigned SectionID, const char *SectionName)
LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M, unsigned OptLevel, char **OutError)
void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE)
LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef TyRef, double N)
struct LLVMOpaqueValue * LLVMValueRef
Represents an individual value in LLVM IR.
Definition Types.h:75
int LLVMBool
Definition Types.h:28
struct LLVMOpaqueType * LLVMTypeRef
Each value in the LLVM IR has a type, an LLVMTypeRef.
Definition Types.h:68
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
Definition Types.h:61
struct LLVMOpaqueJITEventListener * LLVMJITEventListenerRef
Definition Types.h:165
struct LLVMOpaqueTargetMachine * LLVMTargetMachineRef
@ LLVMCodeModelJITDefault
struct LLVMOpaqueTargetData * LLVMTargetDataRef
Definition Core.h:34
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const char SectionName[]
static const Kind Either
This is an optimization pass for GlobalISel generic memory operations.
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:280
@ Global
Append to llvm.global_dtors.
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
Attribute unwrap(LLVMAttributeRef Attr)
Definition Attributes.h:397
LLVMAttributeRef wrap(Attribute Attr)
Definition Attributes.h:392
#define N