blob: 12ca9cd1d34021c3215d2ceaa7bc96208544c47d [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- ExternalFunctions.cpp - Implement External Functions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains both code to deal with invoking "external" functions, but
11// also contains code that implements "exported" external functions.
12//
Nick Lewycky63254ee2009-02-04 06:26:47 +000013// 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.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000019//
20//===----------------------------------------------------------------------===//
21
22#include "Interpreter.h"
23#include "llvm/DerivedTypes.h"
24#include "llvm/Module.h"
Nick Lewycky63254ee2009-02-04 06:26:47 +000025#include "llvm/Config/config.h" // Detect libffi
Edwin Törökced9ff82009-07-11 13:10:19 +000026#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000027#include "llvm/System/DynamicLibrary.h"
28#include "llvm/Target/TargetData.h"
Chuck Rose III9a2da442007-07-27 18:26:35 +000029#include "llvm/Support/ManagedStatic.h"
Owen Anderson7c9c0682009-06-22 22:30:56 +000030#include "llvm/System/Mutex.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031#include <csignal>
Duncan Sands05f68372008-10-08 07:23:46 +000032#include <cstdio>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#include <map>
34#include <cmath>
Anton Korobeynikov357a27d2008-02-20 11:08:44 +000035#include <cstring>
Zhou Shenga80aaba2007-12-12 06:16:47 +000036
Nick Lewyckyc0b55e62009-04-13 04:26:06 +000037#ifdef HAVE_FFI_CALL
Nick Lewycky63254ee2009-02-04 06:26:47 +000038#ifdef HAVE_FFI_H
39#include <ffi.h>
Nick Lewyckyc0b55e62009-04-13 04:26:06 +000040#define USE_LIBFFI
Nick Lewycky63254ee2009-02-04 06:26:47 +000041#elif HAVE_FFI_FFI_H
42#include <ffi/ffi.h>
Nick Lewyckyc0b55e62009-04-13 04:26:06 +000043#define USE_LIBFFI
Zhou Shenga80aaba2007-12-12 06:16:47 +000044#endif
Nick Lewycky63254ee2009-02-04 06:26:47 +000045#endif
Tanya Lattner295e3772009-01-22 20:09:20 +000046
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047using namespace llvm;
48
Owen Anderson7c9c0682009-06-22 22:30:56 +000049static ManagedStatic<sys::Mutex> FunctionsLock;
50
Nick Lewycky63254ee2009-02-04 06:26:47 +000051typedef GenericValue (*ExFunc)(const FunctionType *,
52 const std::vector<GenericValue> &);
53static ManagedStatic<std::map<const Function *, ExFunc> > ExportedFunctions;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000054static std::map<std::string, ExFunc> FuncNames;
55
Nick Lewyckyc0b55e62009-04-13 04:26:06 +000056#ifdef USE_LIBFFI
Dan Gohman3dbe9442009-08-12 22:10:57 +000057typedef void (*RawFunc)();
Nick Lewycky63254ee2009-02-04 06:26:47 +000058static ManagedStatic<std::map<const Function *, RawFunc> > RawFunctions;
59#endif
60
Dan Gohmanf17a25c2007-07-18 16:29:46 +000061static Interpreter *TheInterpreter;
62
63static 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()) {
68 case 1: return 'o';
69 case 8: return 'B';
70 case 16: return 'S';
71 case 32: return 'I';
72 case 64: return 'L';
73 default: return 'N';
74 }
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';
82 default: return 'U';
83 }
84}
85
Anton Korobeynikov85a94032007-07-30 23:03:25 +000086// 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.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000091static 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));
Daniel Dunbar1e13b972009-07-24 08:24:36 +000098 ExtName + "_" + F->getNameStr();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000099
Owen Andersonbe44bed2009-07-07 18:33:04 +0000100 sys::ScopedLock Writer(*FunctionsLock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000101 ExFunc FnPtr = FuncNames[ExtName];
102 if (FnPtr == 0)
Daniel Dunbar1e13b972009-07-24 08:24:36 +0000103 FnPtr = FuncNames["lle_X_" + F->getNameStr()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000104 if (FnPtr == 0) // Try calling a generic function... if it exists...
Daniel Dunbar936763a2009-07-22 21:10:12 +0000105 FnPtr = (ExFunc)(intptr_t)
Daniel Dunbar1e13b972009-07-24 08:24:36 +0000106 sys::DynamicLibrary::SearchForAddressOfSymbol("lle_X_"+F->getNameStr());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107 if (FnPtr != 0)
Nick Lewycky63254ee2009-02-04 06:26:47 +0000108 ExportedFunctions->insert(std::make_pair(F, FnPtr)); // Cache for later
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000109 return FnPtr;
110}
111
Nick Lewyckyc0b55e62009-04-13 04:26:06 +0000112#ifdef USE_LIBFFI
Nick Lewycky63254ee2009-02-04 06:26:47 +0000113static 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;
122 }
123 case Type::FloatTyID: return &ffi_type_float;
124 case Type::DoubleTyID: return &ffi_type_double;
125 case Type::PointerTyID: return &ffi_type_pointer;
126 default: break;
127 }
128 // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
Edwin Törökced9ff82009-07-11 13:10:19 +0000129 llvm_report_error("Type could not be mapped for use with libffi.");
Nick Lewycky63254ee2009-02-04 06:26:47 +0000130 return NULL;
131}
132
133static void *ffiValueFor(const Type *Ty, const GenericValue &AV,
134 void *ArgDataPtr) {
135 switch (Ty->getTypeID()) {
136 case Type::IntegerTyID:
137 switch (cast<IntegerType>(Ty)->getBitWidth()) {
138 case 8: {
139 int8_t *I8Ptr = (int8_t *) ArgDataPtr;
140 *I8Ptr = (int8_t) AV.IntVal.getZExtValue();
141 return ArgDataPtr;
142 }
143 case 16: {
144 int16_t *I16Ptr = (int16_t *) ArgDataPtr;
145 *I16Ptr = (int16_t) AV.IntVal.getZExtValue();
146 return ArgDataPtr;
147 }
148 case 32: {
149 int32_t *I32Ptr = (int32_t *) ArgDataPtr;
150 *I32Ptr = (int32_t) AV.IntVal.getZExtValue();
151 return ArgDataPtr;
152 }
153 case 64: {
154 int64_t *I64Ptr = (int64_t *) ArgDataPtr;
155 *I64Ptr = (int64_t) AV.IntVal.getZExtValue();
156 return ArgDataPtr;
157 }
158 }
159 case Type::FloatTyID: {
160 float *FloatPtr = (float *) ArgDataPtr;
161 *FloatPtr = AV.DoubleVal;
162 return ArgDataPtr;
163 }
164 case Type::DoubleTyID: {
165 double *DoublePtr = (double *) ArgDataPtr;
166 *DoublePtr = AV.DoubleVal;
167 return ArgDataPtr;
168 }
169 case Type::PointerTyID: {
170 void **PtrPtr = (void **) ArgDataPtr;
171 *PtrPtr = GVTOP(AV);
172 return ArgDataPtr;
173 }
174 default: break;
175 }
176 // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
Edwin Törökced9ff82009-07-11 13:10:19 +0000177 llvm_report_error("Type value could not be mapped for use with libffi.");
Nick Lewycky63254ee2009-02-04 06:26:47 +0000178 return NULL;
179}
180
181static bool ffiInvoke(RawFunc Fn, Function *F,
182 const std::vector<GenericValue> &ArgVals,
183 const TargetData *TD, GenericValue &Result) {
184 ffi_cif cif;
185 const FunctionType *FTy = F->getFunctionType();
186 const unsigned NumArgs = F->arg_size();
187
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()) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000191 llvm_report_error("Calling external var arg function '" + F->getName()
192 + "' is not supported by the Interpreter.");
Nick Lewycky63254ee2009-02-04 06:26:47 +0000193 }
194
195 unsigned ArgBytes = 0;
196
197 std::vector<ffi_type*> args(NumArgs);
198 for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
199 A != E; ++A) {
200 const unsigned ArgNo = A->getArgNo();
201 const Type *ArgTy = FTy->getParamType(ArgNo);
202 args[ArgNo] = ffiTypeFor(ArgTy);
203 ArgBytes += TD->getTypeStoreSize(ArgTy);
204 }
205
206 uint8_t *ArgData = (uint8_t*) alloca(ArgBytes);
207 uint8_t *ArgDataPtr = ArgData;
208 std::vector<void*> values(NumArgs);
209 for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
210 A != E; ++A) {
211 const unsigned ArgNo = A->getArgNo();
212 const Type *ArgTy = FTy->getParamType(ArgNo);
213 values[ArgNo] = ffiValueFor(ArgTy, ArgVals[ArgNo], ArgDataPtr);
214 ArgDataPtr += TD->getTypeStoreSize(ArgTy);
215 }
216
217 const Type *RetTy = FTy->getReturnType();
218 ffi_type *rtype = ffiTypeFor(RetTy);
219
220 if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NumArgs, rtype, &args[0]) == FFI_OK) {
221 void *ret = NULL;
222 if (RetTy->getTypeID() != Type::VoidTyID)
223 ret = alloca(TD->getTypeStoreSize(RetTy));
224 ffi_call(&cif, Fn, ret, &values[0]);
225 switch (RetTy->getTypeID()) {
226 case Type::IntegerTyID:
227 switch (cast<IntegerType>(RetTy)->getBitWidth()) {
228 case 8: Result.IntVal = APInt(8 , *(int8_t *) ret); break;
229 case 16: Result.IntVal = APInt(16, *(int16_t*) ret); break;
230 case 32: Result.IntVal = APInt(32, *(int32_t*) ret); break;
231 case 64: Result.IntVal = APInt(64, *(int64_t*) ret); break;
232 }
233 break;
234 case Type::FloatTyID: Result.FloatVal = *(float *) ret; break;
235 case Type::DoubleTyID: Result.DoubleVal = *(double*) ret; break;
236 case Type::PointerTyID: Result.PointerVal = *(void **) ret; break;
237 default: break;
238 }
239 return true;
240 }
241
242 return false;
243}
Nick Lewyckyc0b55e62009-04-13 04:26:06 +0000244#endif // USE_LIBFFI
Nick Lewycky63254ee2009-02-04 06:26:47 +0000245
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246GenericValue Interpreter::callExternalFunction(Function *F,
247 const std::vector<GenericValue> &ArgVals) {
248 TheInterpreter = this;
249
Owen Anderson7c9c0682009-06-22 22:30:56 +0000250 FunctionsLock->acquire();
251
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252 // Do a lookup to see if the function is in our cache... this should just be a
253 // deferred annotation!
Nick Lewycky63254ee2009-02-04 06:26:47 +0000254 std::map<const Function *, ExFunc>::iterator FI = ExportedFunctions->find(F);
255 if (ExFunc Fn = (FI == ExportedFunctions->end()) ? lookupFunction(F)
Owen Anderson7c9c0682009-06-22 22:30:56 +0000256 : FI->second) {
257 FunctionsLock->release();
Nick Lewycky63254ee2009-02-04 06:26:47 +0000258 return Fn(F->getFunctionType(), ArgVals);
Owen Anderson7c9c0682009-06-22 22:30:56 +0000259 }
Nick Lewycky63254ee2009-02-04 06:26:47 +0000260
Nick Lewyckyc0b55e62009-04-13 04:26:06 +0000261#ifdef USE_LIBFFI
Nick Lewycky63254ee2009-02-04 06:26:47 +0000262 std::map<const Function *, RawFunc>::iterator RF = RawFunctions->find(F);
263 RawFunc RawFn;
264 if (RF == RawFunctions->end()) {
265 RawFn = (RawFunc)(intptr_t)
266 sys::DynamicLibrary::SearchForAddressOfSymbol(F->getName());
267 if (RawFn != 0)
268 RawFunctions->insert(std::make_pair(F, RawFn)); // Cache for later
269 } else {
270 RawFn = RF->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000271 }
Owen Anderson7c9c0682009-06-22 22:30:56 +0000272
273 FunctionsLock->release();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000274
Nick Lewycky63254ee2009-02-04 06:26:47 +0000275 GenericValue Result;
276 if (RawFn != 0 && ffiInvoke(RawFn, F, ArgVals, getTargetData(), Result))
277 return Result;
Nick Lewyckyc0b55e62009-04-13 04:26:06 +0000278#endif // USE_LIBFFI
Nick Lewycky63254ee2009-02-04 06:26:47 +0000279
Edwin Törökced9ff82009-07-11 13:10:19 +0000280 if (F->getName() == "__main")
Chris Lattner5febcae2009-08-23 08:43:55 +0000281 errs() << "Tried to execute an unknown external function: "
Edwin Törökced9ff82009-07-11 13:10:19 +0000282 << F->getType()->getDescription() << " __main\n";
283 else
284 llvm_report_error("Tried to execute an unknown external function: " +
285 F->getType()->getDescription() + " " +F->getName());
Nick Lewycky63254ee2009-02-04 06:26:47 +0000286 return GenericValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000287}
288
289
290//===----------------------------------------------------------------------===//
291// Functions "exported" to the running application...
292//
Daniel Dunbar04de3242009-08-07 20:50:09 +0000293
294// Visual Studio warns about returning GenericValue in extern "C" linkage
295#ifdef _MSC_VER
296 #pragma warning(disable : 4190)
297#endif
298
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000299extern "C" { // Don't add C++ manglings to llvm mangling :)
300
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000301// void atexit(Function*)
Nick Lewycky63254ee2009-02-04 06:26:47 +0000302GenericValue lle_X_atexit(const FunctionType *FT,
303 const std::vector<GenericValue> &Args) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304 assert(Args.size() == 1);
305 TheInterpreter->addAtExitHandler((Function*)GVTOP(Args[0]));
306 GenericValue GV;
307 GV.IntVal = 0;
308 return GV;
309}
310
311// void exit(int)
Nick Lewycky63254ee2009-02-04 06:26:47 +0000312GenericValue lle_X_exit(const FunctionType *FT,
313 const std::vector<GenericValue> &Args) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000314 TheInterpreter->exitCalled(Args[0]);
315 return GenericValue();
316}
317
318// void abort(void)
Nick Lewycky63254ee2009-02-04 06:26:47 +0000319GenericValue lle_X_abort(const FunctionType *FT,
320 const std::vector<GenericValue> &Args) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000321 //FIXME: should we report or raise here?
322 //llvm_report_error("Interpreted program raised SIGABRT");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000323 raise (SIGABRT);
324 return GenericValue();
325}
326
Nick Lewycky63254ee2009-02-04 06:26:47 +0000327// int sprintf(char *, const char *, ...) - a very rough implementation to make
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000328// output useful.
Nick Lewycky63254ee2009-02-04 06:26:47 +0000329GenericValue lle_X_sprintf(const FunctionType *FT,
330 const std::vector<GenericValue> &Args) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331 char *OutputBuffer = (char *)GVTOP(Args[0]);
332 const char *FmtStr = (const char *)GVTOP(Args[1]);
333 unsigned ArgNo = 2;
334
335 // printf should return # chars printed. This is completely incorrect, but
336 // close enough for now.
337 GenericValue GV;
338 GV.IntVal = APInt(32, strlen(FmtStr));
339 while (1) {
340 switch (*FmtStr) {
341 case 0: return GV; // Null terminator...
342 default: // Normal nonspecial character
343 sprintf(OutputBuffer++, "%c", *FmtStr++);
344 break;
345 case '\\': { // Handle escape codes
346 sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
347 FmtStr += 2; OutputBuffer += 2;
348 break;
349 }
350 case '%': { // Handle format specifiers
351 char FmtBuf[100] = "", Buffer[1000] = "";
352 char *FB = FmtBuf;
353 *FB++ = *FmtStr++;
354 char Last = *FB++ = *FmtStr++;
355 unsigned HowLong = 0;
356 while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
357 Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
358 Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
359 Last != 'p' && Last != 's' && Last != '%') {
360 if (Last == 'l' || Last == 'L') HowLong++; // Keep track of l's
361 Last = *FB++ = *FmtStr++;
362 }
363 *FB = 0;
364
365 switch (Last) {
366 case '%':
Dan Gohmane5dce982008-08-05 23:36:35 +0000367 strcpy(Buffer, "%"); break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000368 case 'c':
369 sprintf(Buffer, FmtBuf, uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
370 break;
371 case 'd': case 'i':
372 case 'u': case 'o':
373 case 'x': case 'X':
374 if (HowLong >= 1) {
375 if (HowLong == 1 &&
376 TheInterpreter->getTargetData()->getPointerSizeInBits() == 64 &&
377 sizeof(long) < sizeof(int64_t)) {
378 // Make sure we use %lld with a 64 bit argument because we might be
379 // compiling LLI on a 32 bit compiler.
380 unsigned Size = strlen(FmtBuf);
381 FmtBuf[Size] = FmtBuf[Size-1];
382 FmtBuf[Size+1] = 0;
383 FmtBuf[Size-1] = 'l';
384 }
385 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal.getZExtValue());
386 } else
387 sprintf(Buffer, FmtBuf,uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
388 break;
389 case 'e': case 'E': case 'g': case 'G': case 'f':
390 sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
391 case 'p':
392 sprintf(Buffer, FmtBuf, (void*)GVTOP(Args[ArgNo++])); break;
393 case 's':
394 sprintf(Buffer, FmtBuf, (char*)GVTOP(Args[ArgNo++])); break;
Chris Lattner5febcae2009-08-23 08:43:55 +0000395 default:
396 errs() << "<unknown printf code '" << *FmtStr << "'!>";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000397 ArgNo++; break;
398 }
399 strcpy(OutputBuffer, Buffer);
400 OutputBuffer += strlen(Buffer);
401 }
402 break;
403 }
404 }
405 return GV;
406}
407
Nick Lewycky63254ee2009-02-04 06:26:47 +0000408// int printf(const char *, ...) - a very rough implementation to make output
409// useful.
410GenericValue lle_X_printf(const FunctionType *FT,
411 const std::vector<GenericValue> &Args) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000412 char Buffer[10000];
Nick Lewycky63254ee2009-02-04 06:26:47 +0000413 std::vector<GenericValue> NewArgs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000414 NewArgs.push_back(PTOGV((void*)&Buffer[0]));
415 NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
416 GenericValue GV = lle_X_sprintf(FT, NewArgs);
Chris Lattner5febcae2009-08-23 08:43:55 +0000417 outs() << Buffer;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000418 return GV;
419}
420
Owen Anderson35b47072009-08-13 21:58:54 +0000421static void ByteswapSCANFResults(LLVMContext &C,
422 const char *Fmt, void *Arg0, void *Arg1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000423 void *Arg2, void *Arg3, void *Arg4, void *Arg5,
424 void *Arg6, void *Arg7, void *Arg8) {
425 void *Args[] = { Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, 0 };
426
427 // Loop over the format string, munging read values as appropriate (performs
428 // byteswaps as necessary).
429 unsigned ArgNo = 0;
430 while (*Fmt) {
431 if (*Fmt++ == '%') {
432 // Read any flag characters that may be present...
433 bool Suppress = false;
434 bool Half = false;
435 bool Long = false;
436 bool LongLong = false; // long long or long double
437
438 while (1) {
439 switch (*Fmt++) {
440 case '*': Suppress = true; break;
441 case 'a': /*Allocate = true;*/ break; // We don't need to track this
442 case 'h': Half = true; break;
443 case 'l': Long = true; break;
444 case 'q':
445 case 'L': LongLong = true; break;
446 default:
447 if (Fmt[-1] > '9' || Fmt[-1] < '0') // Ignore field width specs
448 goto Out;
449 }
450 }
451 Out:
452
453 // Read the conversion character
454 if (!Suppress && Fmt[-1] != '%') { // Nothing to do?
455 unsigned Size = 0;
456 const Type *Ty = 0;
457
458 switch (Fmt[-1]) {
459 case 'i': case 'o': case 'u': case 'x': case 'X': case 'n': case 'p':
460 case 'd':
461 if (Long || LongLong) {
Owen Anderson35b47072009-08-13 21:58:54 +0000462 Size = 8; Ty = Type::getInt64Ty(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000463 } else if (Half) {
Owen Anderson35b47072009-08-13 21:58:54 +0000464 Size = 4; Ty = Type::getInt16Ty(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000465 } else {
Owen Anderson35b47072009-08-13 21:58:54 +0000466 Size = 4; Ty = Type::getInt32Ty(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000467 }
468 break;
469
470 case 'e': case 'g': case 'E':
471 case 'f':
472 if (Long || LongLong) {
Owen Anderson35b47072009-08-13 21:58:54 +0000473 Size = 8; Ty = Type::getDoubleTy(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000474 } else {
Owen Anderson35b47072009-08-13 21:58:54 +0000475 Size = 4; Ty = Type::getFloatTy(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000476 }
477 break;
478
479 case 's': case 'c': case '[': // No byteswap needed
480 Size = 1;
Owen Anderson35b47072009-08-13 21:58:54 +0000481 Ty = Type::getInt8Ty(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000482 break;
483
484 default: break;
485 }
486
487 if (Size) {
488 GenericValue GV;
489 void *Arg = Args[ArgNo++];
490 memcpy(&GV, Arg, Size);
491 TheInterpreter->StoreValueToMemory(GV, (GenericValue*)Arg, Ty);
492 }
493 }
494 }
495 }
496}
497
498// int sscanf(const char *format, ...);
Nick Lewycky63254ee2009-02-04 06:26:47 +0000499GenericValue lle_X_sscanf(const FunctionType *FT,
500 const std::vector<GenericValue> &args) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000501 assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
502
503 char *Args[10];
504 for (unsigned i = 0; i < args.size(); ++i)
505 Args[i] = (char*)GVTOP(args[i]);
506
507 GenericValue GV;
508 GV.IntVal = APInt(32, sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
509 Args[5], Args[6], Args[7], Args[8], Args[9]));
Owen Anderson35b47072009-08-13 21:58:54 +0000510 ByteswapSCANFResults(FT->getContext(),
511 Args[1], Args[2], Args[3], Args[4],
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000512 Args[5], Args[6], Args[7], Args[8], Args[9], 0);
513 return GV;
514}
515
516// int scanf(const char *format, ...);
Nick Lewycky63254ee2009-02-04 06:26:47 +0000517GenericValue lle_X_scanf(const FunctionType *FT,
518 const std::vector<GenericValue> &args) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000519 assert(args.size() < 10 && "Only handle up to 10 args to scanf right now!");
520
521 char *Args[10];
522 for (unsigned i = 0; i < args.size(); ++i)
523 Args[i] = (char*)GVTOP(args[i]);
524
525 GenericValue GV;
526 GV.IntVal = APInt(32, scanf( Args[0], Args[1], Args[2], Args[3], Args[4],
527 Args[5], Args[6], Args[7], Args[8], Args[9]));
Owen Anderson35b47072009-08-13 21:58:54 +0000528 ByteswapSCANFResults(FT->getContext(),
529 Args[0], Args[1], Args[2], Args[3], Args[4],
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000530 Args[5], Args[6], Args[7], Args[8], Args[9]);
531 return GV;
532}
533
Nick Lewycky63254ee2009-02-04 06:26:47 +0000534// int fprintf(FILE *, const char *, ...) - a very rough implementation to make
535// output useful.
536GenericValue lle_X_fprintf(const FunctionType *FT,
537 const std::vector<GenericValue> &Args) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000538 assert(Args.size() >= 2);
539 char Buffer[10000];
Nick Lewycky63254ee2009-02-04 06:26:47 +0000540 std::vector<GenericValue> NewArgs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000541 NewArgs.push_back(PTOGV(Buffer));
542 NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end());
543 GenericValue GV = lle_X_sprintf(FT, NewArgs);
544
Nick Lewycky63254ee2009-02-04 06:26:47 +0000545 fputs(Buffer, (FILE *) GVTOP(Args[0]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000546 return GV;
547}
548
549} // End extern "C"
550
Daniel Dunbar04de3242009-08-07 20:50:09 +0000551// Done with externals; turn the warning back on
552#ifdef _MSC_VER
553 #pragma warning(default: 4190)
554#endif
555
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000556
557void Interpreter::initializeExternalFunctions() {
Owen Andersonbe44bed2009-07-07 18:33:04 +0000558 sys::ScopedLock Writer(*FunctionsLock);
Nick Lewycky63254ee2009-02-04 06:26:47 +0000559 FuncNames["lle_X_atexit"] = lle_X_atexit;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000560 FuncNames["lle_X_exit"] = lle_X_exit;
561 FuncNames["lle_X_abort"] = lle_X_abort;
Nick Lewycky63254ee2009-02-04 06:26:47 +0000562
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000563 FuncNames["lle_X_printf"] = lle_X_printf;
564 FuncNames["lle_X_sprintf"] = lle_X_sprintf;
565 FuncNames["lle_X_sscanf"] = lle_X_sscanf;
566 FuncNames["lle_X_scanf"] = lle_X_scanf;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000567 FuncNames["lle_X_fprintf"] = lle_X_fprintf;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000568}
569