blob: b0221019b559848225c92850f8d724491ba8c18a [file] [log] [blame]
Chris Lattner2fbfdcf2002-04-07 20:49:59 +00001//===-- ExternalFunctions.cpp - Implement External Functions --------------===//
Misha Brukmand1c881a2005-04-21 22:43:08 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmand1c881a2005-04-21 22:43:08 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Misha Brukmand1c881a2005-04-21 22:43:08 +00009//
Chris Lattner2fbfdcf2002-04-07 20:49:59 +000010// This file contains both code to deal with invoking "external" functions, but
11// also contains code that implements "exported" external functions.
Chris Lattner7720c8e2001-09-10 04:50:17 +000012//
Nick Lewyckyf9c5c5c2009-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.
Chris Lattner7720c8e2001-09-10 04:50:17 +000019//
20//===----------------------------------------------------------------------===//
21
22#include "Interpreter.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000023#include "llvm/Config/config.h" // Detect libffi
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/Module.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000027#include "llvm/Support/DynamicLibrary.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000028#include "llvm/Support/ErrorHandling.h"
Chuck Rose III936baaa2007-07-27 18:26:35 +000029#include "llvm/Support/ManagedStatic.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000030#include "llvm/Support/Mutex.h"
Stephen Hines37ed9c12014-12-01 14:51:49 -080031#include "llvm/Support/UniqueLock.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000032#include <cmath>
Brian Gaekeb56a6bc2003-11-05 01:18:49 +000033#include <csignal>
Duncan Sands4520dd22008-10-08 07:23:46 +000034#include <cstdio>
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000035#include <cstring>
Chandler Carruthd04a8d42012-12-03 16:50:05 +000036#include <map>
Zhou Sheng621dead2007-12-12 06:16:47 +000037
Nick Lewycky93f70fc2009-04-13 04:26:06 +000038#ifdef HAVE_FFI_CALL
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000039#ifdef HAVE_FFI_H
40#include <ffi.h>
Nick Lewycky93f70fc2009-04-13 04:26:06 +000041#define USE_LIBFFI
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000042#elif HAVE_FFI_FFI_H
43#include <ffi/ffi.h>
Nick Lewycky93f70fc2009-04-13 04:26:06 +000044#define USE_LIBFFI
Zhou Sheng621dead2007-12-12 06:16:47 +000045#endif
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000046#endif
Tanya Lattner32aaee62009-01-22 20:09:20 +000047
Chris Lattnerf7a743d2003-12-14 23:25:48 +000048using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000049
Owen Andersonc2265702009-06-22 22:30:56 +000050static ManagedStatic<sys::Mutex> FunctionsLock;
51
Chris Lattnerdb125cf2011-07-18 04:54:35 +000052typedef GenericValue (*ExFunc)(FunctionType *,
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000053 const std::vector<GenericValue> &);
54static ManagedStatic<std::map<const Function *, ExFunc> > ExportedFunctions;
Stephen Hines37ed9c12014-12-01 14:51:49 -080055static ManagedStatic<std::map<std::string, ExFunc> > FuncNames;
Chris Lattner7720c8e2001-09-10 04:50:17 +000056
Nick Lewycky93f70fc2009-04-13 04:26:06 +000057#ifdef USE_LIBFFI
Dan Gohmana9ad0412009-08-12 22:10:57 +000058typedef void (*RawFunc)();
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000059static ManagedStatic<std::map<const Function *, RawFunc> > RawFunctions;
60#endif
61
Chris Lattnere43db882001-10-27 04:15:57 +000062static Interpreter *TheInterpreter;
63
Chris Lattnerdb125cf2011-07-18 04:54:35 +000064static char getTypeID(Type *Ty) {
Chris Lattnerf70c22b2004-06-17 18:19:28 +000065 switch (Ty->getTypeID()) {
Chris Lattner7720c8e2001-09-10 04:50:17 +000066 case Type::VoidTyID: return 'V';
Reid Spencera54b7cb2007-01-12 07:05:14 +000067 case Type::IntegerTyID:
68 switch (cast<IntegerType>(Ty)->getBitWidth()) {
69 case 1: return 'o';
70 case 8: return 'B';
71 case 16: return 'S';
72 case 32: return 'I';
73 case 64: return 'L';
74 default: return 'N';
75 }
Chris Lattner7720c8e2001-09-10 04:50:17 +000076 case Type::FloatTyID: return 'F';
77 case Type::DoubleTyID: return 'D';
78 case Type::PointerTyID: return 'P';
Reid Spencere49661b2006-12-31 05:51:36 +000079 case Type::FunctionTyID:return 'M';
Chris Lattner7720c8e2001-09-10 04:50:17 +000080 case Type::StructTyID: return 'T';
81 case Type::ArrayTyID: return 'A';
Chris Lattner7720c8e2001-09-10 04:50:17 +000082 default: return 'U';
83 }
84}
85
Anton Korobeynikov42346f52007-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.
Brian Gaeke58a6faa2003-10-10 17:03:10 +000091static ExFunc lookupFunction(const Function *F) {
Chris Lattner7720c8e2001-09-10 04:50:17 +000092 // Function not found, look it up... start by figuring out what the
93 // composite function name should be.
Chris Lattner697954c2002-01-20 22:54:45 +000094 std::string ExtName = "lle_";
Chris Lattnerdb125cf2011-07-18 04:54:35 +000095 FunctionType *FT = F->getFunctionType();
Brian Gaeke58a6faa2003-10-10 17:03:10 +000096 for (unsigned i = 0, e = FT->getNumContainedTypes(); i != e; ++i)
97 ExtName += getTypeID(FT->getContainedType(i));
Benjamin Kramera7b0cb72011-11-15 16:27:03 +000098 ExtName += "_" + F->getName().str();
Chris Lattner7720c8e2001-09-10 04:50:17 +000099
Owen Andersona9d1f2c2009-07-07 18:33:04 +0000100 sys::ScopedLock Writer(*FunctionsLock);
Stephen Hines37ed9c12014-12-01 14:51:49 -0800101 ExFunc FnPtr = (*FuncNames)[ExtName];
Stephen Hinesdce4a402014-05-29 02:49:00 -0700102 if (!FnPtr)
Stephen Hines37ed9c12014-12-01 14:51:49 -0800103 FnPtr = (*FuncNames)["lle_X_" + F->getName().str()];
Stephen Hinesdce4a402014-05-29 02:49:00 -0700104 if (!FnPtr) // Try calling a generic function... if it exists...
Daniel Dunbar8f603022009-07-22 21:10:12 +0000105 FnPtr = (ExFunc)(intptr_t)
Benjamin Kramera7b0cb72011-11-15 16:27:03 +0000106 sys::DynamicLibrary::SearchForAddressOfSymbol("lle_X_" +
107 F->getName().str());
Stephen Hinesdce4a402014-05-29 02:49:00 -0700108 if (FnPtr)
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000109 ExportedFunctions->insert(std::make_pair(F, FnPtr)); // Cache for later
Chris Lattner7720c8e2001-09-10 04:50:17 +0000110 return FnPtr;
111}
112
Nick Lewycky93f70fc2009-04-13 04:26:06 +0000113#ifdef USE_LIBFFI
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000114static ffi_type *ffiTypeFor(Type *Ty) {
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000115 switch (Ty->getTypeID()) {
116 case Type::VoidTyID: return &ffi_type_void;
117 case Type::IntegerTyID:
118 switch (cast<IntegerType>(Ty)->getBitWidth()) {
119 case 8: return &ffi_type_sint8;
120 case 16: return &ffi_type_sint16;
121 case 32: return &ffi_type_sint32;
122 case 64: return &ffi_type_sint64;
123 }
124 case Type::FloatTyID: return &ffi_type_float;
125 case Type::DoubleTyID: return &ffi_type_double;
126 case Type::PointerTyID: return &ffi_type_pointer;
127 default: break;
128 }
129 // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
Chris Lattner75361b62010-04-07 22:58:41 +0000130 report_fatal_error("Type could not be mapped for use with libffi.");
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000131 return NULL;
132}
133
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000134static void *ffiValueFor(Type *Ty, const GenericValue &AV,
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000135 void *ArgDataPtr) {
136 switch (Ty->getTypeID()) {
137 case Type::IntegerTyID:
138 switch (cast<IntegerType>(Ty)->getBitWidth()) {
139 case 8: {
140 int8_t *I8Ptr = (int8_t *) ArgDataPtr;
141 *I8Ptr = (int8_t) AV.IntVal.getZExtValue();
142 return ArgDataPtr;
143 }
144 case 16: {
145 int16_t *I16Ptr = (int16_t *) ArgDataPtr;
146 *I16Ptr = (int16_t) AV.IntVal.getZExtValue();
147 return ArgDataPtr;
148 }
149 case 32: {
150 int32_t *I32Ptr = (int32_t *) ArgDataPtr;
151 *I32Ptr = (int32_t) AV.IntVal.getZExtValue();
152 return ArgDataPtr;
153 }
154 case 64: {
155 int64_t *I64Ptr = (int64_t *) ArgDataPtr;
156 *I64Ptr = (int64_t) AV.IntVal.getZExtValue();
157 return ArgDataPtr;
158 }
159 }
160 case Type::FloatTyID: {
161 float *FloatPtr = (float *) ArgDataPtr;
Nick Lewyckyb5106f52009-11-18 05:43:15 +0000162 *FloatPtr = AV.FloatVal;
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000163 return ArgDataPtr;
164 }
165 case Type::DoubleTyID: {
166 double *DoublePtr = (double *) ArgDataPtr;
167 *DoublePtr = AV.DoubleVal;
168 return ArgDataPtr;
169 }
170 case Type::PointerTyID: {
171 void **PtrPtr = (void **) ArgDataPtr;
172 *PtrPtr = GVTOP(AV);
173 return ArgDataPtr;
174 }
175 default: break;
176 }
177 // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
Chris Lattner75361b62010-04-07 22:58:41 +0000178 report_fatal_error("Type value could not be mapped for use with libffi.");
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000179 return NULL;
180}
181
182static bool ffiInvoke(RawFunc Fn, Function *F,
183 const std::vector<GenericValue> &ArgVals,
Micah Villmow3574eca2012-10-08 16:38:25 +0000184 const DataLayout *TD, GenericValue &Result) {
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000185 ffi_cif cif;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000186 FunctionType *FTy = F->getFunctionType();
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000187 const unsigned NumArgs = F->arg_size();
188
189 // TODO: We don't have type information about the remaining arguments, because
190 // this information is never passed into ExecutionEngine::runFunction().
191 if (ArgVals.size() > NumArgs && F->isVarArg()) {
Chris Lattner75361b62010-04-07 22:58:41 +0000192 report_fatal_error("Calling external var arg function '" + F->getName()
Torok Edwin7d696d82009-07-11 13:10:19 +0000193 + "' is not supported by the Interpreter.");
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000194 }
195
196 unsigned ArgBytes = 0;
197
198 std::vector<ffi_type*> args(NumArgs);
199 for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
200 A != E; ++A) {
201 const unsigned ArgNo = A->getArgNo();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000202 Type *ArgTy = FTy->getParamType(ArgNo);
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000203 args[ArgNo] = ffiTypeFor(ArgTy);
204 ArgBytes += TD->getTypeStoreSize(ArgTy);
205 }
206
Nick Lewycky7de3bd22009-09-18 16:46:16 +0000207 SmallVector<uint8_t, 128> ArgData;
208 ArgData.resize(ArgBytes);
209 uint8_t *ArgDataPtr = ArgData.data();
210 SmallVector<void*, 16> values(NumArgs);
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000211 for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
212 A != E; ++A) {
213 const unsigned ArgNo = A->getArgNo();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000214 Type *ArgTy = FTy->getParamType(ArgNo);
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000215 values[ArgNo] = ffiValueFor(ArgTy, ArgVals[ArgNo], ArgDataPtr);
216 ArgDataPtr += TD->getTypeStoreSize(ArgTy);
217 }
218
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000219 Type *RetTy = FTy->getReturnType();
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000220 ffi_type *rtype = ffiTypeFor(RetTy);
221
222 if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NumArgs, rtype, &args[0]) == FFI_OK) {
Nick Lewycky7de3bd22009-09-18 16:46:16 +0000223 SmallVector<uint8_t, 128> ret;
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000224 if (RetTy->getTypeID() != Type::VoidTyID)
Nick Lewycky7de3bd22009-09-18 16:46:16 +0000225 ret.resize(TD->getTypeStoreSize(RetTy));
226 ffi_call(&cif, Fn, ret.data(), values.data());
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000227 switch (RetTy->getTypeID()) {
228 case Type::IntegerTyID:
229 switch (cast<IntegerType>(RetTy)->getBitWidth()) {
Nick Lewycky7de3bd22009-09-18 16:46:16 +0000230 case 8: Result.IntVal = APInt(8 , *(int8_t *) ret.data()); break;
231 case 16: Result.IntVal = APInt(16, *(int16_t*) ret.data()); break;
232 case 32: Result.IntVal = APInt(32, *(int32_t*) ret.data()); break;
233 case 64: Result.IntVal = APInt(64, *(int64_t*) ret.data()); break;
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000234 }
235 break;
Nick Lewycky7de3bd22009-09-18 16:46:16 +0000236 case Type::FloatTyID: Result.FloatVal = *(float *) ret.data(); break;
237 case Type::DoubleTyID: Result.DoubleVal = *(double*) ret.data(); break;
238 case Type::PointerTyID: Result.PointerVal = *(void **) ret.data(); break;
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000239 default: break;
240 }
241 return true;
242 }
243
244 return false;
245}
Nick Lewycky93f70fc2009-04-13 04:26:06 +0000246#endif // USE_LIBFFI
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000247
Chris Lattner4e7dd8f2005-01-21 19:59:37 +0000248GenericValue Interpreter::callExternalFunction(Function *F,
Chris Lattner44edb6b2003-05-14 14:21:30 +0000249 const std::vector<GenericValue> &ArgVals) {
Chris Lattnere43db882001-10-27 04:15:57 +0000250 TheInterpreter = this;
251
Stephen Hines37ed9c12014-12-01 14:51:49 -0800252 unique_lock<sys::Mutex> Guard(*FunctionsLock);
Owen Andersonc2265702009-06-22 22:30:56 +0000253
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000254 // Do a lookup to see if the function is in our cache... this should just be a
Misha Brukmand5d96b92003-10-10 17:42:19 +0000255 // deferred annotation!
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000256 std::map<const Function *, ExFunc>::iterator FI = ExportedFunctions->find(F);
257 if (ExFunc Fn = (FI == ExportedFunctions->end()) ? lookupFunction(F)
Owen Andersonc2265702009-06-22 22:30:56 +0000258 : FI->second) {
Stephen Hines37ed9c12014-12-01 14:51:49 -0800259 Guard.unlock();
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000260 return Fn(F->getFunctionType(), ArgVals);
Owen Andersonc2265702009-06-22 22:30:56 +0000261 }
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000262
Nick Lewycky93f70fc2009-04-13 04:26:06 +0000263#ifdef USE_LIBFFI
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000264 std::map<const Function *, RawFunc>::iterator RF = RawFunctions->find(F);
265 RawFunc RawFn;
266 if (RF == RawFunctions->end()) {
267 RawFn = (RawFunc)(intptr_t)
268 sys::DynamicLibrary::SearchForAddressOfSymbol(F->getName());
Torok Edwin820580d2010-03-30 20:15:13 +0000269 if (!RawFn)
Duncan Sands34727662010-07-12 08:16:59 +0000270 RawFn = (RawFunc)(intptr_t)getPointerToGlobalIfAvailable(F);
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000271 if (RawFn != 0)
272 RawFunctions->insert(std::make_pair(F, RawFn)); // Cache for later
273 } else {
274 RawFn = RF->second;
Chris Lattner7720c8e2001-09-10 04:50:17 +0000275 }
Daniel Dunbare4a57432009-09-17 00:14:44 +0000276
Stephen Hines37ed9c12014-12-01 14:51:49 -0800277 Guard.unlock();
Chris Lattner7720c8e2001-09-10 04:50:17 +0000278
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000279 GenericValue Result;
Micah Villmow3574eca2012-10-08 16:38:25 +0000280 if (RawFn != 0 && ffiInvoke(RawFn, F, ArgVals, getDataLayout(), Result))
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000281 return Result;
Nick Lewycky93f70fc2009-04-13 04:26:06 +0000282#endif // USE_LIBFFI
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000283
Torok Edwin7d696d82009-07-11 13:10:19 +0000284 if (F->getName() == "__main")
David Greenec74fe782010-01-05 01:53:59 +0000285 errs() << "Tried to execute an unknown external function: "
Chris Lattner0cd0d882011-06-18 21:18:23 +0000286 << *F->getType() << " __main\n";
Torok Edwin7d696d82009-07-11 13:10:19 +0000287 else
Chris Lattner75361b62010-04-07 22:58:41 +0000288 report_fatal_error("Tried to execute an unknown external function: " +
Chris Lattner0cd0d882011-06-18 21:18:23 +0000289 F->getName());
Nick Lewycky0e49fe82009-11-17 07:52:09 +0000290#ifndef USE_LIBFFI
David Greenec74fe782010-01-05 01:53:59 +0000291 errs() << "Recompiling LLVM with --enable-libffi might help.\n";
Nick Lewycky0e49fe82009-11-17 07:52:09 +0000292#endif
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000293 return GenericValue();
Chris Lattner7720c8e2001-09-10 04:50:17 +0000294}
295
296
297//===----------------------------------------------------------------------===//
Chris Lattnerb408b122002-03-29 03:57:15 +0000298// Functions "exported" to the running application...
Chris Lattner7720c8e2001-09-10 04:50:17 +0000299//
Daniel Dunbar482cccd2009-08-07 20:50:09 +0000300
Chris Lattner44edb6b2003-05-14 14:21:30 +0000301// void atexit(Function*)
NAKAMURA Takumi4bf6c192012-02-24 00:20:08 +0000302static
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000303GenericValue lle_X_atexit(FunctionType *FT,
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000304 const std::vector<GenericValue> &Args) {
Chris Lattner44edb6b2003-05-14 14:21:30 +0000305 assert(Args.size() == 1);
306 TheInterpreter->addAtExitHandler((Function*)GVTOP(Args[0]));
307 GenericValue GV;
Reid Spencerbfcd5992007-03-06 03:08:12 +0000308 GV.IntVal = 0;
Chris Lattner44edb6b2003-05-14 14:21:30 +0000309 return GV;
Chris Lattnerf8f2afb2001-10-18 21:55:32 +0000310}
311
Chris Lattner005cbce2002-10-02 21:12:13 +0000312// void exit(int)
NAKAMURA Takumi4bf6c192012-02-24 00:20:08 +0000313static
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000314GenericValue lle_X_exit(FunctionType *FT,
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000315 const std::vector<GenericValue> &Args) {
Chris Lattnere43db882001-10-27 04:15:57 +0000316 TheInterpreter->exitCalled(Args[0]);
317 return GenericValue();
318}
319
Chris Lattner005cbce2002-10-02 21:12:13 +0000320// void abort(void)
NAKAMURA Takumi4bf6c192012-02-24 00:20:08 +0000321static
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000322GenericValue lle_X_abort(FunctionType *FT,
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000323 const std::vector<GenericValue> &Args) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000324 //FIXME: should we report or raise here?
Chris Lattner75361b62010-04-07 22:58:41 +0000325 //report_fatal_error("Interpreted program raised SIGABRT");
Brian Gaekeb56a6bc2003-11-05 01:18:49 +0000326 raise (SIGABRT);
Chris Lattner1ee34a52002-05-20 21:17:16 +0000327 return GenericValue();
328}
329
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000330// int sprintf(char *, const char *, ...) - a very rough implementation to make
Chris Lattnere7c6f722001-12-13 00:43:47 +0000331// output useful.
NAKAMURA Takumi4bf6c192012-02-24 00:20:08 +0000332static
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000333GenericValue lle_X_sprintf(FunctionType *FT,
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000334 const std::vector<GenericValue> &Args) {
Chris Lattnerb1118742003-01-13 00:59:47 +0000335 char *OutputBuffer = (char *)GVTOP(Args[0]);
336 const char *FmtStr = (const char *)GVTOP(Args[1]);
Chris Lattnere7c6f722001-12-13 00:43:47 +0000337 unsigned ArgNo = 2;
Chris Lattner08845a22001-10-29 20:27:45 +0000338
339 // printf should return # chars printed. This is completely incorrect, but
340 // close enough for now.
Daniel Dunbare4a57432009-09-17 00:14:44 +0000341 GenericValue GV;
Reid Spencerbfcd5992007-03-06 03:08:12 +0000342 GV.IntVal = APInt(32, strlen(FmtStr));
Chris Lattner08845a22001-10-29 20:27:45 +0000343 while (1) {
344 switch (*FmtStr) {
345 case 0: return GV; // Null terminator...
346 default: // Normal nonspecial character
Chris Lattnere7c6f722001-12-13 00:43:47 +0000347 sprintf(OutputBuffer++, "%c", *FmtStr++);
Chris Lattner08845a22001-10-29 20:27:45 +0000348 break;
349 case '\\': { // Handle escape codes
Chris Lattnere7c6f722001-12-13 00:43:47 +0000350 sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
351 FmtStr += 2; OutputBuffer += 2;
Chris Lattner08845a22001-10-29 20:27:45 +0000352 break;
353 }
354 case '%': { // Handle format specifiers
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000355 char FmtBuf[100] = "", Buffer[1000] = "";
356 char *FB = FmtBuf;
357 *FB++ = *FmtStr++;
358 char Last = *FB++ = *FmtStr++;
359 unsigned HowLong = 0;
360 while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
361 Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
362 Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
363 Last != 'p' && Last != 's' && Last != '%') {
364 if (Last == 'l' || Last == 'L') HowLong++; // Keep track of l's
365 Last = *FB++ = *FmtStr++;
Chris Lattner08845a22001-10-29 20:27:45 +0000366 }
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000367 *FB = 0;
Misha Brukmand1c881a2005-04-21 22:43:08 +0000368
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000369 switch (Last) {
370 case '%':
Benjamin Kramer12ea66a2010-01-28 18:04:38 +0000371 memcpy(Buffer, "%", 2); break;
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000372 case 'c':
Reid Spencerbfcd5992007-03-06 03:08:12 +0000373 sprintf(Buffer, FmtBuf, uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
374 break;
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000375 case 'd': case 'i':
376 case 'u': case 'o':
377 case 'x': case 'X':
Chris Lattner69ab7a82002-08-02 23:08:32 +0000378 if (HowLong >= 1) {
Chris Lattner1543e402003-08-24 14:02:47 +0000379 if (HowLong == 1 &&
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000380 TheInterpreter->getDataLayout()->getPointerSizeInBits() == 64 &&
Reid Spencer19b7e0e2006-05-24 19:21:13 +0000381 sizeof(long) < sizeof(int64_t)) {
Chris Lattner69ab7a82002-08-02 23:08:32 +0000382 // Make sure we use %lld with a 64 bit argument because we might be
383 // compiling LLI on a 32 bit compiler.
384 unsigned Size = strlen(FmtBuf);
385 FmtBuf[Size] = FmtBuf[Size-1];
386 FmtBuf[Size+1] = 0;
387 FmtBuf[Size-1] = 'l';
388 }
Reid Spencerbfcd5992007-03-06 03:08:12 +0000389 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal.getZExtValue());
Chris Lattner69ab7a82002-08-02 23:08:32 +0000390 } else
Reid Spencerbfcd5992007-03-06 03:08:12 +0000391 sprintf(Buffer, FmtBuf,uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
392 break;
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000393 case 'e': case 'E': case 'g': case 'G': case 'f':
394 sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
395 case 'p':
Chris Lattnerb1118742003-01-13 00:59:47 +0000396 sprintf(Buffer, FmtBuf, (void*)GVTOP(Args[ArgNo++])); break;
Misha Brukmand1c881a2005-04-21 22:43:08 +0000397 case 's':
Chris Lattnerb1118742003-01-13 00:59:47 +0000398 sprintf(Buffer, FmtBuf, (char*)GVTOP(Args[ArgNo++])); break;
Chris Lattnerd9ea85a2009-08-23 08:43:55 +0000399 default:
David Greenec74fe782010-01-05 01:53:59 +0000400 errs() << "<unknown printf code '" << *FmtStr << "'!>";
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000401 ArgNo++; break;
Chris Lattner08845a22001-10-29 20:27:45 +0000402 }
Benjamin Kramer12ea66a2010-01-28 18:04:38 +0000403 size_t Len = strlen(Buffer);
404 memcpy(OutputBuffer, Buffer, Len + 1);
405 OutputBuffer += Len;
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000406 }
Chris Lattner08845a22001-10-29 20:27:45 +0000407 break;
408 }
Chris Lattner08845a22001-10-29 20:27:45 +0000409 }
Elena Demikhovsky4ca0ce22013-09-02 06:40:09 +0000410 return GV;
Chris Lattner08845a22001-10-29 20:27:45 +0000411}
412
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000413// int printf(const char *, ...) - a very rough implementation to make output
414// useful.
NAKAMURA Takumi4bf6c192012-02-24 00:20:08 +0000415static
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000416GenericValue lle_X_printf(FunctionType *FT,
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000417 const std::vector<GenericValue> &Args) {
Chris Lattnere7c6f722001-12-13 00:43:47 +0000418 char Buffer[10000];
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000419 std::vector<GenericValue> NewArgs;
Reid Spencerb3b07272007-04-21 17:11:45 +0000420 NewArgs.push_back(PTOGV((void*)&Buffer[0]));
Chris Lattnere7c6f722001-12-13 00:43:47 +0000421 NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
Reid Spencer97e0c222007-03-30 16:41:50 +0000422 GenericValue GV = lle_X_sprintf(FT, NewArgs);
Chris Lattnerd9ea85a2009-08-23 08:43:55 +0000423 outs() << Buffer;
Chris Lattnere7c6f722001-12-13 00:43:47 +0000424 return GV;
425}
426
Chris Lattner665ee882002-03-08 22:51:07 +0000427// int sscanf(const char *format, ...);
NAKAMURA Takumi4bf6c192012-02-24 00:20:08 +0000428static
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000429GenericValue lle_X_sscanf(FunctionType *FT,
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000430 const std::vector<GenericValue> &args) {
Chris Lattner665ee882002-03-08 22:51:07 +0000431 assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
432
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000433 char *Args[10];
Chris Lattner665ee882002-03-08 22:51:07 +0000434 for (unsigned i = 0; i < args.size(); ++i)
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000435 Args[i] = (char*)GVTOP(args[i]);
Chris Lattner665ee882002-03-08 22:51:07 +0000436
437 GenericValue GV;
Reid Spencerbfcd5992007-03-06 03:08:12 +0000438 GV.IntVal = APInt(32, sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
Elena Demikhovsky4ca0ce22013-09-02 06:40:09 +0000439 Args[5], Args[6], Args[7], Args[8], Args[9]));
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000440 return GV;
441}
442
443// int scanf(const char *format, ...);
NAKAMURA Takumi4bf6c192012-02-24 00:20:08 +0000444static
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000445GenericValue lle_X_scanf(FunctionType *FT,
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000446 const std::vector<GenericValue> &args) {
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000447 assert(args.size() < 10 && "Only handle up to 10 args to scanf right now!");
448
449 char *Args[10];
450 for (unsigned i = 0; i < args.size(); ++i)
451 Args[i] = (char*)GVTOP(args[i]);
452
453 GenericValue GV;
Reid Spencerbfcd5992007-03-06 03:08:12 +0000454 GV.IntVal = APInt(32, scanf( Args[0], Args[1], Args[2], Args[3], Args[4],
Elena Demikhovsky4ca0ce22013-09-02 06:40:09 +0000455 Args[5], Args[6], Args[7], Args[8], Args[9]));
Chris Lattner665ee882002-03-08 22:51:07 +0000456 return GV;
457}
458
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000459// int fprintf(FILE *, const char *, ...) - a very rough implementation to make
460// output useful.
NAKAMURA Takumi4bf6c192012-02-24 00:20:08 +0000461static
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000462GenericValue lle_X_fprintf(FunctionType *FT,
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000463 const std::vector<GenericValue> &Args) {
Chris Lattner9dbf6dd2003-04-21 22:43:20 +0000464 assert(Args.size() >= 2);
Chris Lattnercf9b4f02002-11-06 23:05:03 +0000465 char Buffer[10000];
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000466 std::vector<GenericValue> NewArgs;
Chris Lattnerb1118742003-01-13 00:59:47 +0000467 NewArgs.push_back(PTOGV(Buffer));
Chris Lattnercf9b4f02002-11-06 23:05:03 +0000468 NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end());
Reid Spencer97e0c222007-03-30 16:41:50 +0000469 GenericValue GV = lle_X_sprintf(FT, NewArgs);
Chris Lattnercf9b4f02002-11-06 23:05:03 +0000470
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000471 fputs(Buffer, (FILE *) GVTOP(Args[0]));
Chris Lattnercf9b4f02002-11-06 23:05:03 +0000472 return GV;
473}
474
Benjamin Kramercf472392013-09-11 12:42:39 +0000475static GenericValue lle_X_memset(FunctionType *FT,
476 const std::vector<GenericValue> &Args) {
Elena Demikhovsky4ca0ce22013-09-02 06:40:09 +0000477 int val = (int)Args[1].IntVal.getSExtValue();
478 size_t len = (size_t)Args[2].IntVal.getZExtValue();
Benjamin Kramercf472392013-09-11 12:42:39 +0000479 memset((void *)GVTOP(Args[0]), val, len);
Elena Demikhovsky4ca0ce22013-09-02 06:40:09 +0000480 // llvm.memset.* returns void, lle_X_* returns GenericValue,
481 // so here we return GenericValue with IntVal set to zero
482 GenericValue GV;
483 GV.IntVal = 0;
484 return GV;
485}
486
Benjamin Kramercf472392013-09-11 12:42:39 +0000487static GenericValue lle_X_memcpy(FunctionType *FT,
488 const std::vector<GenericValue> &Args) {
Elena Demikhovsky4ca0ce22013-09-02 06:40:09 +0000489 memcpy(GVTOP(Args[0]), GVTOP(Args[1]),
490 (size_t)(Args[2].IntVal.getLimitedValue()));
491
Benjamin Kramercf472392013-09-11 12:42:39 +0000492 // llvm.memcpy* returns void, lle_X_* returns GenericValue,
Elena Demikhovsky4ca0ce22013-09-02 06:40:09 +0000493 // so here we return GenericValue with IntVal set to zero
494 GenericValue GV;
495 GV.IntVal = 0;
496 return GV;
497}
498
Chris Lattnerda82ed52003-05-08 16:18:31 +0000499void Interpreter::initializeExternalFunctions() {
Owen Andersona9d1f2c2009-07-07 18:33:04 +0000500 sys::ScopedLock Writer(*FunctionsLock);
Stephen Hines37ed9c12014-12-01 14:51:49 -0800501 (*FuncNames)["lle_X_atexit"] = lle_X_atexit;
502 (*FuncNames)["lle_X_exit"] = lle_X_exit;
503 (*FuncNames)["lle_X_abort"] = lle_X_abort;
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000504
Stephen Hines37ed9c12014-12-01 14:51:49 -0800505 (*FuncNames)["lle_X_printf"] = lle_X_printf;
506 (*FuncNames)["lle_X_sprintf"] = lle_X_sprintf;
507 (*FuncNames)["lle_X_sscanf"] = lle_X_sscanf;
508 (*FuncNames)["lle_X_scanf"] = lle_X_scanf;
509 (*FuncNames)["lle_X_fprintf"] = lle_X_fprintf;
510 (*FuncNames)["lle_X_memset"] = lle_X_memset;
511 (*FuncNames)["lle_X_memcpy"] = lle_X_memcpy;
Chris Lattner4721f132001-10-30 20:28:00 +0000512}