1 //===-- ExternalFunctions.cpp - Implement External Functions --------------===//
3 // This file contains both code to deal with invoking "external" functions, but
4 // also contains code that implements "exported" external functions.
6 // External functions in LLI are implemented by dlopen'ing the lli executable
7 // and using dlsym to look op the functions that we want to invoke. If a
8 // function is found, then the arguments are mangled and passed in to the
11 //===----------------------------------------------------------------------===//
13 #include "Interpreter.h"
14 #include "llvm/DerivedTypes.h"
15 #include "../test/Libraries/libinstr/tracelib.h"
26 typedef GenericValue (*ExFunc)(FunctionType *, const vector<GenericValue> &);
27 static std::map<const Function *, ExFunc> Functions;
28 static std::map<std::string, ExFunc> FuncNames;
30 static Interpreter *TheInterpreter;
32 // getCurrentExecutablePath() - Return the directory that the lli executable
35 std::string Interpreter::getCurrentExecutablePath() const {
37 if (dladdr(&TheInterpreter, &Info) == 0) return "";
39 std::string LinkAddr(Info.dli_fname);
40 unsigned SlashPos = LinkAddr.rfind('/');
41 if (SlashPos != std::string::npos)
42 LinkAddr.resize(SlashPos); // Trim the executable name off...
48 static char getTypeID(const Type *Ty) {
49 switch (Ty->getPrimitiveID()) {
50 case Type::VoidTyID: return 'V';
51 case Type::BoolTyID: return 'o';
52 case Type::UByteTyID: return 'B';
53 case Type::SByteTyID: return 'b';
54 case Type::UShortTyID: return 'S';
55 case Type::ShortTyID: return 's';
56 case Type::UIntTyID: return 'I';
57 case Type::IntTyID: return 'i';
58 case Type::ULongTyID: return 'L';
59 case Type::LongTyID: return 'l';
60 case Type::FloatTyID: return 'F';
61 case Type::DoubleTyID: return 'D';
62 case Type::PointerTyID: return 'P';
63 case Type::FunctionTyID: return 'M';
64 case Type::StructTyID: return 'T';
65 case Type::ArrayTyID: return 'A';
66 case Type::OpaqueTyID: return 'O';
71 static ExFunc lookupFunction(const Function *M) {
72 // Function not found, look it up... start by figuring out what the
73 // composite function name should be.
74 std::string ExtName = "lle_";
75 const FunctionType *MT = M->getFunctionType();
76 for (unsigned i = 0; const Type *Ty = MT->getContainedType(i); ++i)
77 ExtName += getTypeID(Ty);
78 ExtName += "_" + M->getName();
80 //cout << "Tried: '" << ExtName << "'\n";
81 ExFunc FnPtr = FuncNames[ExtName];
83 FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ExtName.c_str());
85 FnPtr = FuncNames["lle_X_"+M->getName()];
86 if (FnPtr == 0) // Try calling a generic function... if it exists...
87 FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ("lle_X_"+M->getName()).c_str());
89 Functions.insert(std::make_pair(M, FnPtr)); // Cache for later
93 GenericValue Interpreter::callExternalMethod(Function *M,
94 const vector<GenericValue> &ArgVals) {
95 TheInterpreter = this;
97 // Do a lookup to see if the function is in our cache... this should just be a
98 // defered annotation!
99 std::map<const Function *, ExFunc>::iterator FI = Functions.find(M);
100 ExFunc Fn = (FI == Functions.end()) ? lookupFunction(M) : FI->second;
102 cout << "Tried to execute an unknown external function: "
103 << M->getType()->getDescription() << " " << M->getName() << "\n";
104 return GenericValue();
107 // TODO: FIXME when types are not const!
108 GenericValue Result = Fn(const_cast<FunctionType*>(M->getFunctionType()),
114 //===----------------------------------------------------------------------===//
115 // Functions "exported" to the running application...
117 extern "C" { // Don't add C++ manglings to llvm mangling :)
119 // Implement void printstr([ubyte {x N}] *)
120 GenericValue lle_VP_printstr(FunctionType *M, const vector<GenericValue> &ArgVal){
121 assert(ArgVal.size() == 1 && "printstr only takes one argument!");
122 cout << (char*)ArgVal[0].PointerVal;
123 return GenericValue();
126 // Implement 'void print(X)' for every type...
127 GenericValue lle_X_print(FunctionType *M, const vector<GenericValue> &ArgVals) {
128 assert(ArgVals.size() == 1 && "generic print only takes one argument!");
130 Interpreter::print(M->getParamTypes()[0], ArgVals[0]);
131 return GenericValue();
134 // Implement 'void printVal(X)' for every type...
135 GenericValue lle_X_printVal(FunctionType *M, const vector<GenericValue> &ArgVal) {
136 assert(ArgVal.size() == 1 && "generic print only takes one argument!");
138 // Specialize print([ubyte {x N} ] *) and print(sbyte *)
139 if (PointerType *PTy = dyn_cast<PointerType>(M->getParamTypes()[0].get()))
140 if (PTy->getElementType() == Type::SByteTy ||
141 isa<ArrayType>(PTy->getElementType())) {
142 return lle_VP_printstr(M, ArgVal);
145 Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);
146 return GenericValue();
149 // Implement 'void printString(X)'
150 // Argument must be [ubyte {x N} ] * or sbyte *
151 GenericValue lle_X_printString(FunctionType *M, const vector<GenericValue> &ArgVal) {
152 assert(ArgVal.size() == 1 && "generic print only takes one argument!");
153 return lle_VP_printstr(M, ArgVal);
156 // Implement 'void print<TYPE>(X)' for each primitive type or pointer type
157 #define PRINT_TYPE_FUNC(TYPENAME,TYPEID) \
158 GenericValue lle_X_print##TYPENAME(FunctionType *M,\
159 const vector<GenericValue> &ArgVal) {\
160 assert(ArgVal.size() == 1 && "generic print only takes one argument!");\
161 assert(M->getParamTypes()[0].get()->getPrimitiveID() == Type::TYPEID);\
162 Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);\
163 return GenericValue();\
166 PRINT_TYPE_FUNC(SByte, SByteTyID)
167 PRINT_TYPE_FUNC(UByte, UByteTyID)
168 PRINT_TYPE_FUNC(Short, ShortTyID)
169 PRINT_TYPE_FUNC(UShort, UShortTyID)
170 PRINT_TYPE_FUNC(Int, IntTyID)
171 PRINT_TYPE_FUNC(UInt, UIntTyID)
172 PRINT_TYPE_FUNC(Long, LongTyID)
173 PRINT_TYPE_FUNC(ULong, ULongTyID)
174 PRINT_TYPE_FUNC(Float, FloatTyID)
175 PRINT_TYPE_FUNC(Double, DoubleTyID)
176 PRINT_TYPE_FUNC(Pointer, PointerTyID)
179 // void "putchar"(sbyte)
180 GenericValue lle_Vb_putchar(FunctionType *M, const vector<GenericValue> &Args) {
181 cout << Args[0].SByteVal;
182 return GenericValue();
185 // int "putchar"(int)
186 GenericValue lle_ii_putchar(FunctionType *M, const vector<GenericValue> &Args) {
187 cout << ((char)Args[0].IntVal) << std::flush;
191 // void "putchar"(ubyte)
192 GenericValue lle_VB_putchar(FunctionType *M, const vector<GenericValue> &Args) {
193 cout << Args[0].SByteVal << std::flush;
198 GenericValue lle_V___main(FunctionType *M, const vector<GenericValue> &Args) {
199 return GenericValue();
203 GenericValue lle_X_exit(FunctionType *M, const vector<GenericValue> &Args) {
204 TheInterpreter->exitCalled(Args[0]);
205 return GenericValue();
208 // void *malloc(uint)
209 GenericValue lle_X_malloc(FunctionType *M, const vector<GenericValue> &Args) {
210 assert(Args.size() == 1 && "Malloc expects one argument!");
212 GV.PointerVal = (PointerTy)malloc(Args[0].UIntVal);
217 GenericValue lle_X_free(FunctionType *M, const vector<GenericValue> &Args) {
218 assert(Args.size() == 1);
219 free((void*)Args[0].PointerVal);
220 return GenericValue();
224 GenericValue lle_X_atoi(FunctionType *M, const vector<GenericValue> &Args) {
225 assert(Args.size() == 1);
227 GV.IntVal = atoi((char*)Args[0].PointerVal);
231 // double pow(double, double)
232 GenericValue lle_X_pow(FunctionType *M, const vector<GenericValue> &Args) {
233 assert(Args.size() == 2);
235 GV.DoubleVal = pow(Args[0].DoubleVal, Args[1].DoubleVal);
239 // double exp(double)
240 GenericValue lle_X_exp(FunctionType *M, const vector<GenericValue> &Args) {
241 assert(Args.size() == 1);
243 GV.DoubleVal = exp(Args[0].DoubleVal);
247 // double sqrt(double)
248 GenericValue lle_X_sqrt(FunctionType *M, const vector<GenericValue> &Args) {
249 assert(Args.size() == 1);
251 GV.DoubleVal = sqrt(Args[0].DoubleVal);
255 // double log(double)
256 GenericValue lle_X_log(FunctionType *M, const vector<GenericValue> &Args) {
257 assert(Args.size() == 1);
259 GV.DoubleVal = log(Args[0].DoubleVal);
263 // double floor(double)
264 GenericValue lle_X_floor(FunctionType *M, const vector<GenericValue> &Args) {
265 assert(Args.size() == 1);
267 GV.DoubleVal = floor(Args[0].DoubleVal);
272 GenericValue lle_X_drand48(FunctionType *M, const vector<GenericValue> &Args) {
273 assert(Args.size() == 0);
275 GV.DoubleVal = drand48();
280 GenericValue lle_X_lrand48(FunctionType *M, const vector<GenericValue> &Args) {
281 assert(Args.size() == 0);
283 GV.IntVal = lrand48();
287 // void srand48(long)
288 GenericValue lle_X_srand48(FunctionType *M, const vector<GenericValue> &Args) {
289 assert(Args.size() == 1);
290 srand48(Args[0].IntVal);
291 return GenericValue();
295 GenericValue lle_X_srand(FunctionType *M, const vector<GenericValue> &Args) {
296 assert(Args.size() == 1);
297 srand(Args[0].UIntVal);
298 return GenericValue();
301 // int sprintf(sbyte *, sbyte *, ...) - a very rough implementation to make
303 GenericValue lle_X_sprintf(FunctionType *M, const vector<GenericValue> &Args) {
304 char *OutputBuffer = (char *)Args[0].PointerVal;
305 const char *FmtStr = (const char *)Args[1].PointerVal;
308 // printf should return # chars printed. This is completely incorrect, but
309 // close enough for now.
310 GenericValue GV; GV.IntVal = strlen(FmtStr);
313 case 0: return GV; // Null terminator...
314 default: // Normal nonspecial character
315 sprintf(OutputBuffer++, "%c", *FmtStr++);
317 case '\\': { // Handle escape codes
318 sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
319 FmtStr += 2; OutputBuffer += 2;
322 case '%': { // Handle format specifiers
323 char FmtBuf[100] = "", Buffer[1000] = "";
326 char Last = *FB++ = *FmtStr++;
327 unsigned HowLong = 0;
328 while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
329 Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
330 Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
331 Last != 'p' && Last != 's' && Last != '%') {
332 if (Last == 'l' || Last == 'L') HowLong++; // Keep track of l's
333 Last = *FB++ = *FmtStr++;
339 sprintf(Buffer, FmtBuf); break;
341 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal); break;
346 sprintf(Buffer, FmtBuf, Args[ArgNo++].ULongVal);
348 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal); break;
349 case 'e': case 'E': case 'g': case 'G': case 'f':
350 sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
352 sprintf(Buffer, FmtBuf, (void*)Args[ArgNo++].PointerVal); break;
354 sprintf(Buffer, FmtBuf, (char*)Args[ArgNo++].PointerVal); break;
355 default: cout << "<unknown printf code '" << *FmtStr << "'!>";
358 strcpy(OutputBuffer, Buffer);
359 OutputBuffer += strlen(Buffer);
366 // int printf(sbyte *, ...) - a very rough implementation to make output useful.
367 GenericValue lle_X_printf(FunctionType *M, const vector<GenericValue> &Args) {
369 vector<GenericValue> NewArgs;
370 GenericValue GV; GV.PointerVal = (PointerTy)Buffer;
371 NewArgs.push_back(GV);
372 NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
373 GV = lle_X_sprintf(M, NewArgs);
378 // int sscanf(const char *format, ...);
379 GenericValue lle_X_sscanf(FunctionType *M, const vector<GenericValue> &args) {
380 assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
382 const char *Args[10];
383 for (unsigned i = 0; i < args.size(); ++i)
384 Args[i] = (const char*)args[i].PointerVal;
387 GV.IntVal = sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
388 Args[5], Args[6], Args[7], Args[8], Args[9]);
393 // int clock(void) - Profiling implementation
394 GenericValue lle_i_clock(FunctionType *M, const vector<GenericValue> &Args) {
395 extern int clock(void);
396 GenericValue GV; GV.IntVal = clock();
400 //===----------------------------------------------------------------------===//
402 //===----------------------------------------------------------------------===//
404 // FILE *fopen(const char *filename, const char *mode);
405 GenericValue lle_X_fopen(FunctionType *M, const vector<GenericValue> &Args) {
406 assert(Args.size() == 2);
409 GV.PointerVal = (PointerTy)fopen((const char *)Args[0].PointerVal,
410 (const char *)Args[1].PointerVal);
414 // int fclose(FILE *F);
415 GenericValue lle_X_fclose(FunctionType *M, const vector<GenericValue> &Args) {
416 assert(Args.size() == 1);
419 GV.IntVal = fclose((FILE *)Args[0].PointerVal);
423 // size_t fread(void *ptr, size_t size, size_t nitems, FILE *stream);
424 GenericValue lle_X_fread(FunctionType *M, const vector<GenericValue> &Args) {
425 assert(Args.size() == 4);
428 GV.UIntVal = fread((void*)Args[0].PointerVal, Args[1].UIntVal,
429 Args[2].UIntVal, (FILE*)Args[3].PointerVal);
433 // size_t fwrite(const void *ptr, size_t size, size_t nitems, FILE *stream);
434 GenericValue lle_X_fwrite(FunctionType *M, const vector<GenericValue> &Args) {
435 assert(Args.size() == 4);
438 GV.UIntVal = fwrite((void*)Args[0].PointerVal, Args[1].UIntVal,
439 Args[2].UIntVal, (FILE*)Args[3].PointerVal);
443 // char *fgets(char *s, int n, FILE *stream);
444 GenericValue lle_X_fgets(FunctionType *M, const vector<GenericValue> &Args) {
445 assert(Args.size() == 3);
448 GV.PointerVal = (PointerTy)fgets((char*)Args[0].PointerVal, Args[1].IntVal,
449 (FILE*)Args[2].PointerVal);
453 // int fflush(FILE *stream);
454 GenericValue lle_X_fflush(FunctionType *M, const vector<GenericValue> &Args) {
455 assert(Args.size() == 1);
458 GV.IntVal = fflush((FILE*)Args[0].PointerVal);
462 // unsigned int HashPointerToSeqNum(char* ptr)
463 GenericValue lle_X_HashPointerToSeqNum(FunctionType *M, const vector<GenericValue> &Args) {
464 assert(Args.size() == 1);
467 GV.UIntVal = HashPointerToSeqNum((char*) Args[0].PointerVal);
471 // void ReleasePointerSeqNum(char* ptr);
472 GenericValue lle_X_ReleasePointerSeqNum(FunctionType *M, const vector<GenericValue> &Args) {
473 assert(Args.size() == 1);
474 ReleasePointerSeqNum((char*) Args[0].PointerVal);
475 return GenericValue();
478 // void RecordPointer(char* ptr);
479 GenericValue lle_X_RecordPointer(FunctionType *M, const vector<GenericValue> &Args) {
480 assert(Args.size() == 1);
481 RecordPointer((char*) Args[0].PointerVal);
482 return GenericValue();
485 // void PushPointerSet();
486 GenericValue lle_X_PushPointerSet(FunctionType *M, const vector<GenericValue> &Args) {
487 assert(Args.size() == 0);
489 return GenericValue();
492 // void ReleaseRecordedPointers();
493 GenericValue lle_X_ReleasePointersPopSet(FunctionType *M, const vector<GenericValue> &Args) {
494 assert(Args.size() == 0);
495 ReleasePointersPopSet();
496 return GenericValue();
502 void Interpreter::initializeExternalMethods() {
503 FuncNames["lle_VP_printstr"] = lle_VP_printstr;
504 FuncNames["lle_X_print"] = lle_X_print;
505 FuncNames["lle_X_printVal"] = lle_X_printVal;
506 FuncNames["lle_X_printString"] = lle_X_printString;
507 FuncNames["lle_X_printUByte"] = lle_X_printUByte;
508 FuncNames["lle_X_printSByte"] = lle_X_printSByte;
509 FuncNames["lle_X_printUShort"] = lle_X_printUShort;
510 FuncNames["lle_X_printShort"] = lle_X_printShort;
511 FuncNames["lle_X_printInt"] = lle_X_printInt;
512 FuncNames["lle_X_printUInt"] = lle_X_printUInt;
513 FuncNames["lle_X_printLong"] = lle_X_printLong;
514 FuncNames["lle_X_printULong"] = lle_X_printULong;
515 FuncNames["lle_X_printFloat"] = lle_X_printFloat;
516 FuncNames["lle_X_printDouble"] = lle_X_printDouble;
517 FuncNames["lle_X_printPointer"] = lle_X_printPointer;
518 FuncNames["lle_Vb_putchar"] = lle_Vb_putchar;
519 FuncNames["lle_ii_putchar"] = lle_ii_putchar;
520 FuncNames["lle_VB_putchar"] = lle_VB_putchar;
521 FuncNames["lle_V___main"] = lle_V___main;
522 FuncNames["lle_X_exit"] = lle_X_exit;
523 FuncNames["lle_X_malloc"] = lle_X_malloc;
524 FuncNames["lle_X_free"] = lle_X_free;
525 FuncNames["lle_X_atoi"] = lle_X_atoi;
526 FuncNames["lle_X_pow"] = lle_X_pow;
527 FuncNames["lle_X_exp"] = lle_X_exp;
528 FuncNames["lle_X_log"] = lle_X_log;
529 FuncNames["lle_X_floor"] = lle_X_floor;
530 FuncNames["lle_X_srand"] = lle_X_srand;
531 FuncNames["lle_X_drand48"] = lle_X_drand48;
532 FuncNames["lle_X_srand48"] = lle_X_srand48;
533 FuncNames["lle_X_lrand48"] = lle_X_lrand48;
534 FuncNames["lle_X_sqrt"] = lle_X_sqrt;
535 FuncNames["lle_X_printf"] = lle_X_printf;
536 FuncNames["lle_X_sprintf"] = lle_X_sprintf;
537 FuncNames["lle_X_sscanf"] = lle_X_sscanf;
538 FuncNames["lle_i_clock"] = lle_i_clock;
539 FuncNames["lle_X_fopen"] = lle_X_fopen;
540 FuncNames["lle_X_fclose"] = lle_X_fclose;
541 FuncNames["lle_X_fread"] = lle_X_fread;
542 FuncNames["lle_X_fwrite"] = lle_X_fwrite;
543 FuncNames["lle_X_fgets"] = lle_X_fgets;
544 FuncNames["lle_X_fflush"] = lle_X_fflush;
545 FuncNames["lle_X_HashPointerToSeqNum"] = lle_X_HashPointerToSeqNum;
546 FuncNames["lle_X_ReleasePointerSeqNum"] = lle_X_ReleasePointerSeqNum;
547 FuncNames["lle_X_RecordPointer"] = lle_X_RecordPointer;
548 FuncNames["lle_X_PushPointerSet"] = lle_X_PushPointerSet;
549 FuncNames["lle_X_ReleasePointersPopSet"] = lle_X_ReleasePointersPopSet;