1 //===-- ExternalMethods.cpp - Implement External Functions ----------------===//
3 // This file contains both code to deal with invoking "external" methods, but
4 // also contains code that implements "exported" external methods.
6 // External methods in LLI are implemented by dlopen'ing the lli executable and
7 // using dlsym to look op the methods that we want to invoke. If a method is
8 // found, then the arguments are mangled and passed in to the function call.
10 //===----------------------------------------------------------------------===//
12 #include "Interpreter.h"
13 #include "llvm/DerivedTypes.h"
23 typedef GenericValue (*ExFunc)(FunctionType *, const vector<GenericValue> &);
24 static std::map<const Function *, ExFunc> Functions;
25 static std::map<std::string, ExFunc> FuncNames;
27 static Interpreter *TheInterpreter;
29 // getCurrentExecutablePath() - Return the directory that the lli executable
32 std::string Interpreter::getCurrentExecutablePath() const {
34 if (dladdr(&TheInterpreter, &Info) == 0) return "";
36 std::string LinkAddr(Info.dli_fname);
37 unsigned SlashPos = LinkAddr.rfind('/');
38 if (SlashPos != std::string::npos)
39 LinkAddr.resize(SlashPos); // Trim the executable name off...
45 static char getTypeID(const Type *Ty) {
46 switch (Ty->getPrimitiveID()) {
47 case Type::VoidTyID: return 'V';
48 case Type::BoolTyID: return 'o';
49 case Type::UByteTyID: return 'B';
50 case Type::SByteTyID: return 'b';
51 case Type::UShortTyID: return 'S';
52 case Type::ShortTyID: return 's';
53 case Type::UIntTyID: return 'I';
54 case Type::IntTyID: return 'i';
55 case Type::ULongTyID: return 'L';
56 case Type::LongTyID: return 'l';
57 case Type::FloatTyID: return 'F';
58 case Type::DoubleTyID: return 'D';
59 case Type::PointerTyID: return 'P';
60 case Type::FunctionTyID: return 'M';
61 case Type::StructTyID: return 'T';
62 case Type::ArrayTyID: return 'A';
63 case Type::OpaqueTyID: return 'O';
68 static ExFunc lookupFunction(const Function *M) {
69 // Function not found, look it up... start by figuring out what the
70 // composite function name should be.
71 std::string ExtName = "lle_";
72 const FunctionType *MT = M->getFunctionType();
73 for (unsigned i = 0; const Type *Ty = MT->getContainedType(i); ++i)
74 ExtName += getTypeID(Ty);
75 ExtName += "_" + M->getName();
77 //cout << "Tried: '" << ExtName << "'\n";
78 ExFunc FnPtr = FuncNames[ExtName];
80 FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ExtName.c_str());
82 FnPtr = FuncNames["lle_X_"+M->getName()];
83 if (FnPtr == 0) // Try calling a generic function... if it exists...
84 FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ("lle_X_"+M->getName()).c_str());
86 Functions.insert(std::make_pair(M, FnPtr)); // Cache for later
90 GenericValue Interpreter::callExternalMethod(Function *M,
91 const vector<GenericValue> &ArgVals) {
92 TheInterpreter = this;
94 // Do a lookup to see if the method is in our cache... this should just be a
95 // defered annotation!
96 std::map<const Function *, ExFunc>::iterator FI = Functions.find(M);
97 ExFunc Fn = (FI == Functions.end()) ? lookupFunction(M) : FI->second;
99 cout << "Tried to execute an unknown external method: "
100 << M->getType()->getDescription() << " " << M->getName() << "\n";
101 return GenericValue();
104 // TODO: FIXME when types are not const!
105 GenericValue Result = Fn(const_cast<FunctionType*>(M->getFunctionType()),ArgVals);
110 //===----------------------------------------------------------------------===//
111 // Functions "exported" to the running application...
113 extern "C" { // Don't add C++ manglings to llvm mangling :)
115 // Implement void printstr([ubyte {x N}] *)
116 GenericValue lle_VP_printstr(FunctionType *M, const vector<GenericValue> &ArgVal){
117 assert(ArgVal.size() == 1 && "printstr only takes one argument!");
118 cout << (char*)ArgVal[0].PointerVal;
119 return GenericValue();
122 // Implement 'void print(X)' for every type...
123 GenericValue lle_X_print(FunctionType *M, const vector<GenericValue> &ArgVals) {
124 assert(ArgVals.size() == 1 && "generic print only takes one argument!");
126 Interpreter::print(M->getParamTypes()[0], ArgVals[0]);
127 return GenericValue();
130 // Implement 'void printVal(X)' for every type...
131 GenericValue lle_X_printVal(FunctionType *M, const vector<GenericValue> &ArgVal) {
132 assert(ArgVal.size() == 1 && "generic print only takes one argument!");
134 // Specialize print([ubyte {x N} ] *) and print(sbyte *)
135 if (PointerType *PTy = dyn_cast<PointerType>(M->getParamTypes()[0].get()))
136 if (PTy->getElementType() == Type::SByteTy ||
137 isa<ArrayType>(PTy->getElementType())) {
138 return lle_VP_printstr(M, ArgVal);
141 Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);
142 return GenericValue();
145 // Implement 'void printString(X)'
146 // Argument must be [ubyte {x N} ] * or sbyte *
147 GenericValue lle_X_printString(FunctionType *M, const vector<GenericValue> &ArgVal) {
148 assert(ArgVal.size() == 1 && "generic print only takes one argument!");
149 return lle_VP_printstr(M, ArgVal);
152 // Implement 'void print<TYPE>(X)' for each primitive type or pointer type
153 #define PRINT_TYPE_FUNC(TYPENAME,TYPEID) \
154 GenericValue lle_X_print##TYPENAME(FunctionType *M,\
155 const vector<GenericValue> &ArgVal) {\
156 assert(ArgVal.size() == 1 && "generic print only takes one argument!");\
157 assert(M->getParamTypes()[0].get()->getPrimitiveID() == Type::TYPEID);\
158 Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);\
159 return GenericValue();\
162 PRINT_TYPE_FUNC(SByte, SByteTyID)
163 PRINT_TYPE_FUNC(UByte, UByteTyID)
164 PRINT_TYPE_FUNC(Short, ShortTyID)
165 PRINT_TYPE_FUNC(UShort, UShortTyID)
166 PRINT_TYPE_FUNC(Int, IntTyID)
167 PRINT_TYPE_FUNC(UInt, UIntTyID)
168 PRINT_TYPE_FUNC(Long, LongTyID)
169 PRINT_TYPE_FUNC(ULong, ULongTyID)
170 PRINT_TYPE_FUNC(Float, FloatTyID)
171 PRINT_TYPE_FUNC(Double, DoubleTyID)
172 PRINT_TYPE_FUNC(Pointer, PointerTyID)
175 // void "putchar"(sbyte)
176 GenericValue lle_Vb_putchar(FunctionType *M, const vector<GenericValue> &Args) {
177 cout << Args[0].SByteVal;
178 return GenericValue();
181 // int "putchar"(int)
182 GenericValue lle_ii_putchar(FunctionType *M, const vector<GenericValue> &Args) {
183 cout << ((char)Args[0].IntVal) << std::flush;
187 // void "putchar"(ubyte)
188 GenericValue lle_VB_putchar(FunctionType *M, const vector<GenericValue> &Args) {
189 cout << Args[0].SByteVal << std::flush;
194 GenericValue lle_V___main(FunctionType *M, const vector<GenericValue> &Args) {
195 return GenericValue();
199 GenericValue lle_X_exit(FunctionType *M, const vector<GenericValue> &Args) {
200 TheInterpreter->exitCalled(Args[0]);
201 return GenericValue();
204 // void *malloc(uint)
205 GenericValue lle_X_malloc(FunctionType *M, const vector<GenericValue> &Args) {
206 assert(Args.size() == 1 && "Malloc expects one argument!");
208 GV.PointerVal = (PointerTy)malloc(Args[0].UIntVal);
213 GenericValue lle_X_free(FunctionType *M, const vector<GenericValue> &Args) {
214 assert(Args.size() == 1);
215 free((void*)Args[0].PointerVal);
216 return GenericValue();
220 GenericValue lle_X_atoi(FunctionType *M, const vector<GenericValue> &Args) {
221 assert(Args.size() == 1);
223 GV.IntVal = atoi((char*)Args[0].PointerVal);
227 // double pow(double, double)
228 GenericValue lle_X_pow(FunctionType *M, const vector<GenericValue> &Args) {
229 assert(Args.size() == 2);
231 GV.DoubleVal = pow(Args[0].DoubleVal, Args[1].DoubleVal);
235 // double exp(double)
236 GenericValue lle_X_exp(FunctionType *M, const vector<GenericValue> &Args) {
237 assert(Args.size() == 1);
239 GV.DoubleVal = exp(Args[0].DoubleVal);
243 // double sqrt(double)
244 GenericValue lle_X_sqrt(FunctionType *M, const vector<GenericValue> &Args) {
245 assert(Args.size() == 1);
247 GV.DoubleVal = sqrt(Args[0].DoubleVal);
251 // double log(double)
252 GenericValue lle_X_log(FunctionType *M, const vector<GenericValue> &Args) {
253 assert(Args.size() == 1);
255 GV.DoubleVal = log(Args[0].DoubleVal);
259 // double floor(double)
260 GenericValue lle_X_floor(FunctionType *M, const vector<GenericValue> &Args) {
261 assert(Args.size() == 1);
263 GV.DoubleVal = floor(Args[0].DoubleVal);
268 GenericValue lle_X_drand48(FunctionType *M, const vector<GenericValue> &Args) {
269 assert(Args.size() == 0);
271 GV.DoubleVal = drand48();
276 GenericValue lle_X_lrand48(FunctionType *M, const vector<GenericValue> &Args) {
277 assert(Args.size() == 0);
279 GV.IntVal = lrand48();
283 // void srand48(long)
284 GenericValue lle_X_srand48(FunctionType *M, const vector<GenericValue> &Args) {
285 assert(Args.size() == 1);
286 srand48(Args[0].IntVal);
287 return GenericValue();
291 GenericValue lle_X_srand(FunctionType *M, const vector<GenericValue> &Args) {
292 assert(Args.size() == 1);
293 srand(Args[0].UIntVal);
294 return GenericValue();
297 // int sprintf(sbyte *, sbyte *, ...) - a very rough implementation to make
299 GenericValue lle_X_sprintf(FunctionType *M, const vector<GenericValue> &Args) {
300 char *OutputBuffer = (char *)Args[0].PointerVal;
301 const char *FmtStr = (const char *)Args[1].PointerVal;
304 // printf should return # chars printed. This is completely incorrect, but
305 // close enough for now.
306 GenericValue GV; GV.IntVal = strlen(FmtStr);
309 case 0: return GV; // Null terminator...
310 default: // Normal nonspecial character
311 sprintf(OutputBuffer++, "%c", *FmtStr++);
313 case '\\': { // Handle escape codes
314 sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
315 FmtStr += 2; OutputBuffer += 2;
318 case '%': { // Handle format specifiers
319 char FmtBuf[100] = "", Buffer[1000] = "";
322 char Last = *FB++ = *FmtStr++;
323 unsigned HowLong = 0;
324 while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
325 Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
326 Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
327 Last != 'p' && Last != 's' && Last != '%') {
328 if (Last == 'l' || Last == 'L') HowLong++; // Keep track of l's
329 Last = *FB++ = *FmtStr++;
335 sprintf(Buffer, FmtBuf); break;
337 sprintf(Buffer, FmtBuf, Args[ArgNo++].SByteVal); break;
342 sprintf(Buffer, FmtBuf, Args[ArgNo++].ULongVal);
344 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal); break;
345 case 'e': case 'E': case 'g': case 'G': case 'f':
346 sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
348 sprintf(Buffer, FmtBuf, (void*)Args[ArgNo++].PointerVal); break;
350 sprintf(Buffer, FmtBuf, (char*)Args[ArgNo++].PointerVal); break;
351 default: cout << "<unknown printf code '" << *FmtStr << "'!>";
354 strcpy(OutputBuffer, Buffer);
355 OutputBuffer += strlen(Buffer);
362 // int printf(sbyte *, ...) - a very rough implementation to make output useful.
363 GenericValue lle_X_printf(FunctionType *M, const vector<GenericValue> &Args) {
365 vector<GenericValue> NewArgs;
366 GenericValue GV; GV.PointerVal = (PointerTy)Buffer;
367 NewArgs.push_back(GV);
368 NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
369 GV = lle_X_sprintf(M, NewArgs);
374 // int sscanf(const char *format, ...);
375 GenericValue lle_X_sscanf(FunctionType *M, const vector<GenericValue> &args) {
376 assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
378 const char *Args[10];
379 for (unsigned i = 0; i < args.size(); ++i)
380 Args[i] = (const char*)args[i].PointerVal;
383 GV.IntVal = sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
384 Args[5], Args[6], Args[7], Args[8], Args[9]);
389 // int clock(void) - Profiling implementation
390 GenericValue lle_i_clock(FunctionType *M, const vector<GenericValue> &Args) {
391 extern int clock(void);
392 GenericValue GV; GV.IntVal = clock();
396 //===----------------------------------------------------------------------===//
398 //===----------------------------------------------------------------------===//
400 // FILE *fopen(const char *filename, const char *mode);
401 GenericValue lle_X_fopen(FunctionType *M, const vector<GenericValue> &Args) {
402 assert(Args.size() == 2);
405 GV.PointerVal = (PointerTy)fopen((const char *)Args[0].PointerVal,
406 (const char *)Args[1].PointerVal);
410 // int fclose(FILE *F);
411 GenericValue lle_X_fclose(FunctionType *M, const vector<GenericValue> &Args) {
412 assert(Args.size() == 1);
415 GV.IntVal = fclose((FILE *)Args[0].PointerVal);
419 // size_t fread(void *ptr, size_t size, size_t nitems, FILE *stream);
420 GenericValue lle_X_fread(FunctionType *M, const vector<GenericValue> &Args) {
421 assert(Args.size() == 4);
424 GV.UIntVal = fread((void*)Args[0].PointerVal, Args[1].UIntVal,
425 Args[2].UIntVal, (FILE*)Args[3].PointerVal);
429 // size_t fwrite(const void *ptr, size_t size, size_t nitems, FILE *stream);
430 GenericValue lle_X_fwrite(FunctionType *M, const vector<GenericValue> &Args) {
431 assert(Args.size() == 4);
434 GV.UIntVal = fwrite((void*)Args[0].PointerVal, Args[1].UIntVal,
435 Args[2].UIntVal, (FILE*)Args[3].PointerVal);
439 // char *fgets(char *s, int n, FILE *stream);
440 GenericValue lle_X_fgets(FunctionType *M, const vector<GenericValue> &Args) {
441 assert(Args.size() == 3);
444 GV.PointerVal = (PointerTy)fgets((char*)Args[0].PointerVal, Args[1].IntVal,
445 (FILE*)Args[2].PointerVal);
449 // int fflush(FILE *stream);
450 GenericValue lle_X_fflush(FunctionType *M, const vector<GenericValue> &Args) {
451 assert(Args.size() == 1);
454 GV.IntVal = fflush((FILE*)Args[0].PointerVal);
461 void Interpreter::initializeExternalMethods() {
462 FuncNames["lle_VP_printstr"] = lle_VP_printstr;
463 FuncNames["lle_X_print"] = lle_X_print;
464 FuncNames["lle_X_printVal"] = lle_X_printVal;
465 FuncNames["lle_X_printString"] = lle_X_printString;
466 FuncNames["lle_X_printUByte"] = lle_X_printUByte;
467 FuncNames["lle_X_printSByte"] = lle_X_printSByte;
468 FuncNames["lle_X_printUShort"] = lle_X_printUShort;
469 FuncNames["lle_X_printShort"] = lle_X_printShort;
470 FuncNames["lle_X_printInt"] = lle_X_printInt;
471 FuncNames["lle_X_printUInt"] = lle_X_printUInt;
472 FuncNames["lle_X_printLong"] = lle_X_printLong;
473 FuncNames["lle_X_printULong"] = lle_X_printULong;
474 FuncNames["lle_X_printFloat"] = lle_X_printFloat;
475 FuncNames["lle_X_printDouble"] = lle_X_printDouble;
476 FuncNames["lle_X_printPointer"] = lle_X_printPointer;
477 FuncNames["lle_Vb_putchar"] = lle_Vb_putchar;
478 FuncNames["lle_ii_putchar"] = lle_ii_putchar;
479 FuncNames["lle_VB_putchar"] = lle_VB_putchar;
480 FuncNames["lle_V___main"] = lle_V___main;
481 FuncNames["lle_X_exit"] = lle_X_exit;
482 FuncNames["lle_X_malloc"] = lle_X_malloc;
483 FuncNames["lle_X_free"] = lle_X_free;
484 FuncNames["lle_X_atoi"] = lle_X_atoi;
485 FuncNames["lle_X_pow"] = lle_X_pow;
486 FuncNames["lle_X_exp"] = lle_X_exp;
487 FuncNames["lle_X_log"] = lle_X_log;
488 FuncNames["lle_X_floor"] = lle_X_floor;
489 FuncNames["lle_X_srand"] = lle_X_srand;
490 FuncNames["lle_X_drand48"] = lle_X_drand48;
491 FuncNames["lle_X_srand48"] = lle_X_srand48;
492 FuncNames["lle_X_lrand48"] = lle_X_lrand48;
493 FuncNames["lle_X_sqrt"] = lle_X_sqrt;
494 FuncNames["lle_X_printf"] = lle_X_printf;
495 FuncNames["lle_X_sprintf"] = lle_X_sprintf;
496 FuncNames["lle_X_sscanf"] = lle_X_sscanf;
497 FuncNames["lle_i_clock"] = lle_i_clock;
498 FuncNames["lle_X_fopen"] = lle_X_fopen;
499 FuncNames["lle_X_fclose"] = lle_X_fclose;
500 FuncNames["lle_X_fread"] = lle_X_fread;
501 FuncNames["lle_X_fwrite"] = lle_X_fwrite;
502 FuncNames["lle_X_fgets"] = lle_X_fgets;
503 FuncNames["lle_X_fflush"] = lle_X_fflush;