1 //===-- ExternalFunctions.cpp - Implement External Functions --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains both code to deal with invoking "external" functions, but
11 // also contains code that implements "exported" external functions.
13 // There are currently two mechanisms for handling external functions in the
14 // Interpreter. The first is to implement lle_* wrapper functions that are
15 // specific to well-known library functions which manually translate the
16 // arguments from GenericValues and make the call. If such a wrapper does
17 // not exist, and libffi is available, then the Interpreter will attempt to
18 // invoke the function using libffi, after finding its address.
20 //===----------------------------------------------------------------------===//
22 #include "Interpreter.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Module.h"
25 #include "llvm/Config/config.h" // Detect libffi
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/System/DynamicLibrary.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/System/Mutex.h"
49 static ManagedStatic
<sys::Mutex
> FunctionsLock
;
51 typedef GenericValue (*ExFunc
)(const FunctionType
*,
52 const std::vector
<GenericValue
> &);
53 static ManagedStatic
<std::map
<const Function
*, ExFunc
> > ExportedFunctions
;
54 static std::map
<std::string
, ExFunc
> FuncNames
;
57 typedef void (*RawFunc
)();
58 static ManagedStatic
<std::map
<const Function
*, RawFunc
> > RawFunctions
;
61 static Interpreter
*TheInterpreter
;
63 static char getTypeID(const Type
*Ty
) {
64 switch (Ty
->getTypeID()) {
65 case Type::VoidTyID
: return 'V';
66 case Type::IntegerTyID
:
67 switch (cast
<IntegerType
>(Ty
)->getBitWidth()) {
75 case Type::FloatTyID
: return 'F';
76 case Type::DoubleTyID
: return 'D';
77 case Type::PointerTyID
: return 'P';
78 case Type::FunctionTyID
:return 'M';
79 case Type::StructTyID
: return 'T';
80 case Type::ArrayTyID
: return 'A';
81 case Type::OpaqueTyID
: return 'O';
86 // Try to find address of external function given a Function object.
87 // Please note, that interpreter doesn't know how to assemble a
88 // real call in general case (this is JIT job), that's why it assumes,
89 // that all external functions has the same (and pretty "general") signature.
90 // The typical example of such functions are "lle_X_" ones.
91 static ExFunc
lookupFunction(const Function
*F
) {
92 // Function not found, look it up... start by figuring out what the
93 // composite function name should be.
94 std::string ExtName
= "lle_";
95 const FunctionType
*FT
= F
->getFunctionType();
96 for (unsigned i
= 0, e
= FT
->getNumContainedTypes(); i
!= e
; ++i
)
97 ExtName
+= getTypeID(FT
->getContainedType(i
));
98 ExtName
+ "_" + F
->getNameStr();
100 sys::ScopedLock
Writer(*FunctionsLock
);
101 ExFunc FnPtr
= FuncNames
[ExtName
];
103 FnPtr
= FuncNames
["lle_X_" + F
->getNameStr()];
104 if (FnPtr
== 0) // Try calling a generic function... if it exists...
105 FnPtr
= (ExFunc
)(intptr_t)
106 sys::DynamicLibrary::SearchForAddressOfSymbol("lle_X_"+F
->getNameStr());
108 ExportedFunctions
->insert(std::make_pair(F
, FnPtr
)); // Cache for later
113 static ffi_type
*ffiTypeFor(const Type
*Ty
) {
114 switch (Ty
->getTypeID()) {
115 case Type::VoidTyID
: return &ffi_type_void
;
116 case Type::IntegerTyID
:
117 switch (cast
<IntegerType
>(Ty
)->getBitWidth()) {
118 case 8: return &ffi_type_sint8
;
119 case 16: return &ffi_type_sint16
;
120 case 32: return &ffi_type_sint32
;
121 case 64: return &ffi_type_sint64
;
123 case Type::FloatTyID
: return &ffi_type_float
;
124 case Type::DoubleTyID
: return &ffi_type_double
;
125 case Type::PointerTyID
: return &ffi_type_pointer
;
128 // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
129 report_fatal_error("Type could not be mapped for use with libffi.");
133 static void *ffiValueFor(const Type
*Ty
, const GenericValue
&AV
,
135 switch (Ty
->getTypeID()) {
136 case Type::IntegerTyID
:
137 switch (cast
<IntegerType
>(Ty
)->getBitWidth()) {
139 int8_t *I8Ptr
= (int8_t *) ArgDataPtr
;
140 *I8Ptr
= (int8_t) AV
.IntVal
.getZExtValue();
144 int16_t *I16Ptr
= (int16_t *) ArgDataPtr
;
145 *I16Ptr
= (int16_t) AV
.IntVal
.getZExtValue();
149 int32_t *I32Ptr
= (int32_t *) ArgDataPtr
;
150 *I32Ptr
= (int32_t) AV
.IntVal
.getZExtValue();
154 int64_t *I64Ptr
= (int64_t *) ArgDataPtr
;
155 *I64Ptr
= (int64_t) AV
.IntVal
.getZExtValue();
159 case Type::FloatTyID
: {
160 float *FloatPtr
= (float *) ArgDataPtr
;
161 *FloatPtr
= AV
.FloatVal
;
164 case Type::DoubleTyID
: {
165 double *DoublePtr
= (double *) ArgDataPtr
;
166 *DoublePtr
= AV
.DoubleVal
;
169 case Type::PointerTyID
: {
170 void **PtrPtr
= (void **) ArgDataPtr
;
176 // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
177 report_fatal_error("Type value could not be mapped for use with libffi.");
181 static bool ffiInvoke(RawFunc Fn
, Function
*F
,
182 const std::vector
<GenericValue
> &ArgVals
,
183 const TargetData
*TD
, GenericValue
&Result
) {
185 const FunctionType
*FTy
= F
->getFunctionType();
186 const unsigned NumArgs
= F
->arg_size();
188 // TODO: We don't have type information about the remaining arguments, because
189 // this information is never passed into ExecutionEngine::runFunction().
190 if (ArgVals
.size() > NumArgs
&& F
->isVarArg()) {
191 report_fatal_error("Calling external var arg function '" + F
->getName()
192 + "' is not supported by the Interpreter.");
195 unsigned ArgBytes
= 0;
197 std::vector
<ffi_type
*> args(NumArgs
);
198 for (Function::const_arg_iterator A
= F
->arg_begin(), E
= F
->arg_end();
200 const unsigned ArgNo
= A
->getArgNo();
201 const Type
*ArgTy
= FTy
->getParamType(ArgNo
);
202 args
[ArgNo
] = ffiTypeFor(ArgTy
);
203 ArgBytes
+= TD
->getTypeStoreSize(ArgTy
);
206 SmallVector
<uint8_t, 128> ArgData
;
207 ArgData
.resize(ArgBytes
);
208 uint8_t *ArgDataPtr
= ArgData
.data();
209 SmallVector
<void*, 16> values(NumArgs
);
210 for (Function::const_arg_iterator A
= F
->arg_begin(), E
= F
->arg_end();
212 const unsigned ArgNo
= A
->getArgNo();
213 const Type
*ArgTy
= FTy
->getParamType(ArgNo
);
214 values
[ArgNo
] = ffiValueFor(ArgTy
, ArgVals
[ArgNo
], ArgDataPtr
);
215 ArgDataPtr
+= TD
->getTypeStoreSize(ArgTy
);
218 const Type
*RetTy
= FTy
->getReturnType();
219 ffi_type
*rtype
= ffiTypeFor(RetTy
);
221 if (ffi_prep_cif(&cif
, FFI_DEFAULT_ABI
, NumArgs
, rtype
, &args
[0]) == FFI_OK
) {
222 SmallVector
<uint8_t, 128> ret
;
223 if (RetTy
->getTypeID() != Type::VoidTyID
)
224 ret
.resize(TD
->getTypeStoreSize(RetTy
));
225 ffi_call(&cif
, Fn
, ret
.data(), values
.data());
226 switch (RetTy
->getTypeID()) {
227 case Type::IntegerTyID
:
228 switch (cast
<IntegerType
>(RetTy
)->getBitWidth()) {
229 case 8: Result
.IntVal
= APInt(8 , *(int8_t *) ret
.data()); break;
230 case 16: Result
.IntVal
= APInt(16, *(int16_t*) ret
.data()); break;
231 case 32: Result
.IntVal
= APInt(32, *(int32_t*) ret
.data()); break;
232 case 64: Result
.IntVal
= APInt(64, *(int64_t*) ret
.data()); break;
235 case Type::FloatTyID
: Result
.FloatVal
= *(float *) ret
.data(); break;
236 case Type::DoubleTyID
: Result
.DoubleVal
= *(double*) ret
.data(); break;
237 case Type::PointerTyID
: Result
.PointerVal
= *(void **) ret
.data(); break;
247 GenericValue
Interpreter::callExternalFunction(Function
*F
,
248 const std::vector
<GenericValue
> &ArgVals
) {
249 TheInterpreter
= this;
251 FunctionsLock
->acquire();
253 // Do a lookup to see if the function is in our cache... this should just be a
254 // deferred annotation!
255 std::map
<const Function
*, ExFunc
>::iterator FI
= ExportedFunctions
->find(F
);
256 if (ExFunc Fn
= (FI
== ExportedFunctions
->end()) ? lookupFunction(F
)
258 FunctionsLock
->release();
259 return Fn(F
->getFunctionType(), ArgVals
);
263 std::map
<const Function
*, RawFunc
>::iterator RF
= RawFunctions
->find(F
);
265 if (RF
== RawFunctions
->end()) {
266 RawFn
= (RawFunc
)(intptr_t)
267 sys::DynamicLibrary::SearchForAddressOfSymbol(F
->getName());
269 RawFn
= (RawFunc
)(intptr_t)getPointerToGlobalIfAvailable(F
);
271 RawFunctions
->insert(std::make_pair(F
, RawFn
)); // Cache for later
276 FunctionsLock
->release();
279 if (RawFn
!= 0 && ffiInvoke(RawFn
, F
, ArgVals
, getTargetData(), Result
))
283 if (F
->getName() == "__main")
284 errs() << "Tried to execute an unknown external function: "
285 << F
->getType()->getDescription() << " __main\n";
287 report_fatal_error("Tried to execute an unknown external function: " +
288 F
->getType()->getDescription() + " " +F
->getName());
290 errs() << "Recompiling LLVM with --enable-libffi might help.\n";
292 return GenericValue();
296 //===----------------------------------------------------------------------===//
297 // Functions "exported" to the running application...
300 // Visual Studio warns about returning GenericValue in extern "C" linkage
302 #pragma warning(disable : 4190)
305 extern "C" { // Don't add C++ manglings to llvm mangling :)
307 // void atexit(Function*)
308 GenericValue
lle_X_atexit(const FunctionType
*FT
,
309 const std::vector
<GenericValue
> &Args
) {
310 assert(Args
.size() == 1);
311 TheInterpreter
->addAtExitHandler((Function
*)GVTOP(Args
[0]));
318 GenericValue
lle_X_exit(const FunctionType
*FT
,
319 const std::vector
<GenericValue
> &Args
) {
320 TheInterpreter
->exitCalled(Args
[0]);
321 return GenericValue();
325 GenericValue
lle_X_abort(const FunctionType
*FT
,
326 const std::vector
<GenericValue
> &Args
) {
327 //FIXME: should we report or raise here?
328 //report_fatal_error("Interpreted program raised SIGABRT");
330 return GenericValue();
333 // int sprintf(char *, const char *, ...) - a very rough implementation to make
335 GenericValue
lle_X_sprintf(const FunctionType
*FT
,
336 const std::vector
<GenericValue
> &Args
) {
337 char *OutputBuffer
= (char *)GVTOP(Args
[0]);
338 const char *FmtStr
= (const char *)GVTOP(Args
[1]);
341 // printf should return # chars printed. This is completely incorrect, but
342 // close enough for now.
344 GV
.IntVal
= APInt(32, strlen(FmtStr
));
347 case 0: return GV
; // Null terminator...
348 default: // Normal nonspecial character
349 sprintf(OutputBuffer
++, "%c", *FmtStr
++);
351 case '\\': { // Handle escape codes
352 sprintf(OutputBuffer
, "%c%c", *FmtStr
, *(FmtStr
+1));
353 FmtStr
+= 2; OutputBuffer
+= 2;
356 case '%': { // Handle format specifiers
357 char FmtBuf
[100] = "", Buffer
[1000] = "";
360 char Last
= *FB
++ = *FmtStr
++;
361 unsigned HowLong
= 0;
362 while (Last
!= 'c' && Last
!= 'd' && Last
!= 'i' && Last
!= 'u' &&
363 Last
!= 'o' && Last
!= 'x' && Last
!= 'X' && Last
!= 'e' &&
364 Last
!= 'E' && Last
!= 'g' && Last
!= 'G' && Last
!= 'f' &&
365 Last
!= 'p' && Last
!= 's' && Last
!= '%') {
366 if (Last
== 'l' || Last
== 'L') HowLong
++; // Keep track of l's
367 Last
= *FB
++ = *FmtStr
++;
373 memcpy(Buffer
, "%", 2); break;
375 sprintf(Buffer
, FmtBuf
, uint32_t(Args
[ArgNo
++].IntVal
.getZExtValue()));
382 TheInterpreter
->getTargetData()->getPointerSizeInBits() == 64 &&
383 sizeof(long) < sizeof(int64_t)) {
384 // Make sure we use %lld with a 64 bit argument because we might be
385 // compiling LLI on a 32 bit compiler.
386 unsigned Size
= strlen(FmtBuf
);
387 FmtBuf
[Size
] = FmtBuf
[Size
-1];
389 FmtBuf
[Size
-1] = 'l';
391 sprintf(Buffer
, FmtBuf
, Args
[ArgNo
++].IntVal
.getZExtValue());
393 sprintf(Buffer
, FmtBuf
,uint32_t(Args
[ArgNo
++].IntVal
.getZExtValue()));
395 case 'e': case 'E': case 'g': case 'G': case 'f':
396 sprintf(Buffer
, FmtBuf
, Args
[ArgNo
++].DoubleVal
); break;
398 sprintf(Buffer
, FmtBuf
, (void*)GVTOP(Args
[ArgNo
++])); break;
400 sprintf(Buffer
, FmtBuf
, (char*)GVTOP(Args
[ArgNo
++])); break;
402 errs() << "<unknown printf code '" << *FmtStr
<< "'!>";
405 size_t Len
= strlen(Buffer
);
406 memcpy(OutputBuffer
, Buffer
, Len
+ 1);
415 // int printf(const char *, ...) - a very rough implementation to make output
417 GenericValue
lle_X_printf(const FunctionType
*FT
,
418 const std::vector
<GenericValue
> &Args
) {
420 std::vector
<GenericValue
> NewArgs
;
421 NewArgs
.push_back(PTOGV((void*)&Buffer
[0]));
422 NewArgs
.insert(NewArgs
.end(), Args
.begin(), Args
.end());
423 GenericValue GV
= lle_X_sprintf(FT
, NewArgs
);
428 // int sscanf(const char *format, ...);
429 GenericValue
lle_X_sscanf(const FunctionType
*FT
,
430 const std::vector
<GenericValue
> &args
) {
431 assert(args
.size() < 10 && "Only handle up to 10 args to sscanf right now!");
434 for (unsigned i
= 0; i
< args
.size(); ++i
)
435 Args
[i
] = (char*)GVTOP(args
[i
]);
438 GV
.IntVal
= APInt(32, sscanf(Args
[0], Args
[1], Args
[2], Args
[3], Args
[4],
439 Args
[5], Args
[6], Args
[7], Args
[8], Args
[9]));
443 // int scanf(const char *format, ...);
444 GenericValue
lle_X_scanf(const FunctionType
*FT
,
445 const std::vector
<GenericValue
> &args
) {
446 assert(args
.size() < 10 && "Only handle up to 10 args to scanf right now!");
449 for (unsigned i
= 0; i
< args
.size(); ++i
)
450 Args
[i
] = (char*)GVTOP(args
[i
]);
453 GV
.IntVal
= APInt(32, scanf( Args
[0], Args
[1], Args
[2], Args
[3], Args
[4],
454 Args
[5], Args
[6], Args
[7], Args
[8], Args
[9]));
458 // int fprintf(FILE *, const char *, ...) - a very rough implementation to make
460 GenericValue
lle_X_fprintf(const FunctionType
*FT
,
461 const std::vector
<GenericValue
> &Args
) {
462 assert(Args
.size() >= 2);
464 std::vector
<GenericValue
> NewArgs
;
465 NewArgs
.push_back(PTOGV(Buffer
));
466 NewArgs
.insert(NewArgs
.end(), Args
.begin()+1, Args
.end());
467 GenericValue GV
= lle_X_sprintf(FT
, NewArgs
);
469 fputs(Buffer
, (FILE *) GVTOP(Args
[0]));
475 // Done with externals; turn the warning back on
477 #pragma warning(default: 4190)
481 void Interpreter::initializeExternalFunctions() {
482 sys::ScopedLock
Writer(*FunctionsLock
);
483 FuncNames
["lle_X_atexit"] = lle_X_atexit
;
484 FuncNames
["lle_X_exit"] = lle_X_exit
;
485 FuncNames
["lle_X_abort"] = lle_X_abort
;
487 FuncNames
["lle_X_printf"] = lle_X_printf
;
488 FuncNames
["lle_X_sprintf"] = lle_X_sprintf
;
489 FuncNames
["lle_X_sscanf"] = lle_X_sscanf
;
490 FuncNames
["lle_X_scanf"] = lle_X_scanf
;
491 FuncNames
["lle_X_fprintf"] = lle_X_fprintf
;