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 "ExecutionAnnotations.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/Target/TargetData.h"
28 typedef GenericValue (*ExFunc)(FunctionType *, const vector<GenericValue> &);
29 static std::map<const Function *, ExFunc> Functions;
30 static std::map<std::string, ExFunc> FuncNames;
32 static Interpreter *TheInterpreter;
34 // getCurrentExecutablePath() - Return the directory that the lli executable
37 std::string Interpreter::getCurrentExecutablePath() const {
39 if (dladdr(&TheInterpreter, &Info) == 0) return "";
41 std::string LinkAddr(Info.dli_fname);
42 unsigned SlashPos = LinkAddr.rfind('/');
43 if (SlashPos != std::string::npos)
44 LinkAddr.resize(SlashPos); // Trim the executable name off...
50 static char getTypeID(const Type *Ty) {
51 switch (Ty->getPrimitiveID()) {
52 case Type::VoidTyID: return 'V';
53 case Type::BoolTyID: return 'o';
54 case Type::UByteTyID: return 'B';
55 case Type::SByteTyID: return 'b';
56 case Type::UShortTyID: return 'S';
57 case Type::ShortTyID: return 's';
58 case Type::UIntTyID: return 'I';
59 case Type::IntTyID: return 'i';
60 case Type::ULongTyID: return 'L';
61 case Type::LongTyID: return 'l';
62 case Type::FloatTyID: return 'F';
63 case Type::DoubleTyID: return 'D';
64 case Type::PointerTyID: return 'P';
65 case Type::FunctionTyID: return 'M';
66 case Type::StructTyID: return 'T';
67 case Type::ArrayTyID: return 'A';
68 case Type::OpaqueTyID: return 'O';
73 static ExFunc lookupFunction(const Function *M) {
74 // Function not found, look it up... start by figuring out what the
75 // composite function name should be.
76 std::string ExtName = "lle_";
77 const FunctionType *MT = M->getFunctionType();
78 for (unsigned i = 0; const Type *Ty = MT->getContainedType(i); ++i)
79 ExtName += getTypeID(Ty);
80 ExtName += "_" + M->getName();
82 //cout << "Tried: '" << ExtName << "'\n";
83 ExFunc FnPtr = FuncNames[ExtName];
85 FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ExtName.c_str());
87 FnPtr = FuncNames["lle_X_"+M->getName()];
88 if (FnPtr == 0) // Try calling a generic function... if it exists...
89 FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ("lle_X_"+M->getName()).c_str());
91 Functions.insert(std::make_pair(M, FnPtr)); // Cache for later
95 GenericValue Interpreter::callExternalMethod(Function *M,
96 const vector<GenericValue> &ArgVals) {
97 TheInterpreter = this;
99 // Do a lookup to see if the function is in our cache... this should just be a
100 // defered annotation!
101 std::map<const Function *, ExFunc>::iterator FI = Functions.find(M);
102 ExFunc Fn = (FI == Functions.end()) ? lookupFunction(M) : FI->second;
104 cout << "Tried to execute an unknown external function: "
105 << M->getType()->getDescription() << " " << M->getName() << "\n";
106 return GenericValue();
109 // TODO: FIXME when types are not const!
110 GenericValue Result = Fn(const_cast<FunctionType*>(M->getFunctionType()),
116 //===----------------------------------------------------------------------===//
117 // Functions "exported" to the running application...
119 extern "C" { // Don't add C++ manglings to llvm mangling :)
121 // Implement void printstr([ubyte {x N}] *)
122 GenericValue lle_VP_printstr(FunctionType *M, const vector<GenericValue> &ArgVal){
123 assert(ArgVal.size() == 1 && "printstr only takes one argument!");
124 cout << (char*)ArgVal[0].PointerVal;
125 return GenericValue();
128 // Implement 'void print(X)' for every type...
129 GenericValue lle_X_print(FunctionType *M, const vector<GenericValue> &ArgVals) {
130 assert(ArgVals.size() == 1 && "generic print only takes one argument!");
132 Interpreter::print(M->getParamTypes()[0], ArgVals[0]);
133 return GenericValue();
136 // Implement 'void printVal(X)' for every type...
137 GenericValue lle_X_printVal(FunctionType *M, const vector<GenericValue> &ArgVal) {
138 assert(ArgVal.size() == 1 && "generic print only takes one argument!");
140 // Specialize print([ubyte {x N} ] *) and print(sbyte *)
141 if (const PointerType *PTy =
142 dyn_cast<PointerType>(M->getParamTypes()[0].get()))
143 if (PTy->getElementType() == Type::SByteTy ||
144 isa<ArrayType>(PTy->getElementType())) {
145 return lle_VP_printstr(M, ArgVal);
148 Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);
149 return GenericValue();
152 // Implement 'void printString(X)'
153 // Argument must be [ubyte {x N} ] * or sbyte *
154 GenericValue lle_X_printString(FunctionType *M, const vector<GenericValue> &ArgVal) {
155 assert(ArgVal.size() == 1 && "generic print only takes one argument!");
156 return lle_VP_printstr(M, ArgVal);
159 // Implement 'void print<TYPE>(X)' for each primitive type or pointer type
160 #define PRINT_TYPE_FUNC(TYPENAME,TYPEID) \
161 GenericValue lle_X_print##TYPENAME(FunctionType *M,\
162 const vector<GenericValue> &ArgVal) {\
163 assert(ArgVal.size() == 1 && "generic print only takes one argument!");\
164 assert(M->getParamTypes()[0].get()->getPrimitiveID() == Type::TYPEID);\
165 Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);\
166 return GenericValue();\
169 PRINT_TYPE_FUNC(SByte, SByteTyID)
170 PRINT_TYPE_FUNC(UByte, UByteTyID)
171 PRINT_TYPE_FUNC(Short, ShortTyID)
172 PRINT_TYPE_FUNC(UShort, UShortTyID)
173 PRINT_TYPE_FUNC(Int, IntTyID)
174 PRINT_TYPE_FUNC(UInt, UIntTyID)
175 PRINT_TYPE_FUNC(Long, LongTyID)
176 PRINT_TYPE_FUNC(ULong, ULongTyID)
177 PRINT_TYPE_FUNC(Float, FloatTyID)
178 PRINT_TYPE_FUNC(Double, DoubleTyID)
179 PRINT_TYPE_FUNC(Pointer, PointerTyID)
182 // void putchar(sbyte)
183 GenericValue lle_Vb_putchar(FunctionType *M, const vector<GenericValue> &Args) {
184 cout << Args[0].SByteVal;
185 return GenericValue();
189 GenericValue lle_ii_putchar(FunctionType *M, const vector<GenericValue> &Args) {
190 cout << ((char)Args[0].IntVal) << std::flush;
194 // void putchar(ubyte)
195 GenericValue lle_VB_putchar(FunctionType *M, const vector<GenericValue> &Args) {
196 cout << Args[0].SByteVal << std::flush;
201 GenericValue lle_V___main(FunctionType *M, const vector<GenericValue> &Args) {
202 return GenericValue();
206 GenericValue lle_X_exit(FunctionType *M, const vector<GenericValue> &Args) {
207 TheInterpreter->exitCalled(Args[0]);
208 return GenericValue();
212 GenericValue lle_X_abort(FunctionType *M, const vector<GenericValue> &Args) {
213 std::cerr << "***PROGRAM ABORTED***!\n";
216 TheInterpreter->exitCalled(GV);
217 return GenericValue();
220 // void *malloc(uint)
221 GenericValue lle_X_malloc(FunctionType *M, const vector<GenericValue> &Args) {
222 assert(Args.size() == 1 && "Malloc expects one argument!");
224 GV.PointerVal = (PointerTy)malloc(Args[0].UIntVal);
229 GenericValue lle_X_free(FunctionType *M, const vector<GenericValue> &Args) {
230 assert(Args.size() == 1);
231 free((void*)Args[0].PointerVal);
232 return GenericValue();
236 GenericValue lle_X_atoi(FunctionType *M, const vector<GenericValue> &Args) {
237 assert(Args.size() == 1);
239 GV.IntVal = atoi((char*)Args[0].PointerVal);
243 // double pow(double, double)
244 GenericValue lle_X_pow(FunctionType *M, const vector<GenericValue> &Args) {
245 assert(Args.size() == 2);
247 GV.DoubleVal = pow(Args[0].DoubleVal, Args[1].DoubleVal);
251 // double exp(double)
252 GenericValue lle_X_exp(FunctionType *M, const vector<GenericValue> &Args) {
253 assert(Args.size() == 1);
255 GV.DoubleVal = exp(Args[0].DoubleVal);
259 // double sqrt(double)
260 GenericValue lle_X_sqrt(FunctionType *M, const vector<GenericValue> &Args) {
261 assert(Args.size() == 1);
263 GV.DoubleVal = sqrt(Args[0].DoubleVal);
267 // double log(double)
268 GenericValue lle_X_log(FunctionType *M, const vector<GenericValue> &Args) {
269 assert(Args.size() == 1);
271 GV.DoubleVal = log(Args[0].DoubleVal);
275 // double floor(double)
276 GenericValue lle_X_floor(FunctionType *M, const vector<GenericValue> &Args) {
277 assert(Args.size() == 1);
279 GV.DoubleVal = floor(Args[0].DoubleVal);
284 GenericValue lle_X_drand48(FunctionType *M, const vector<GenericValue> &Args) {
285 assert(Args.size() == 0);
287 GV.DoubleVal = drand48();
292 GenericValue lle_X_lrand48(FunctionType *M, const vector<GenericValue> &Args) {
293 assert(Args.size() == 0);
295 GV.IntVal = lrand48();
299 // void srand48(long)
300 GenericValue lle_X_srand48(FunctionType *M, const vector<GenericValue> &Args) {
301 assert(Args.size() == 1);
302 srand48(Args[0].IntVal);
303 return GenericValue();
307 GenericValue lle_X_srand(FunctionType *M, const vector<GenericValue> &Args) {
308 assert(Args.size() == 1);
309 srand(Args[0].UIntVal);
310 return GenericValue();
313 // int sprintf(sbyte *, sbyte *, ...) - a very rough implementation to make
315 GenericValue lle_X_sprintf(FunctionType *M, const vector<GenericValue> &Args) {
316 char *OutputBuffer = (char *)Args[0].PointerVal;
317 const char *FmtStr = (const char *)Args[1].PointerVal;
320 // printf should return # chars printed. This is completely incorrect, but
321 // close enough for now.
322 GenericValue GV; GV.IntVal = strlen(FmtStr);
325 case 0: return GV; // Null terminator...
326 default: // Normal nonspecial character
327 sprintf(OutputBuffer++, "%c", *FmtStr++);
329 case '\\': { // Handle escape codes
330 sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
331 FmtStr += 2; OutputBuffer += 2;
334 case '%': { // Handle format specifiers
335 char FmtBuf[100] = "", Buffer[1000] = "";
338 char Last = *FB++ = *FmtStr++;
339 unsigned HowLong = 0;
340 while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
341 Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
342 Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
343 Last != 'p' && Last != 's' && Last != '%') {
344 if (Last == 'l' || Last == 'L') HowLong++; // Keep track of l's
345 Last = *FB++ = *FmtStr++;
351 sprintf(Buffer, FmtBuf); break;
353 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal); break;
359 // Make sure we use %lld with a 64 bit argument because we might be
360 // compiling LLI on a 32 bit compiler.
361 unsigned Size = strlen(FmtBuf);
362 FmtBuf[Size] = FmtBuf[Size-1];
364 FmtBuf[Size-1] = 'l';
366 sprintf(Buffer, FmtBuf, Args[ArgNo++].ULongVal);
368 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal); break;
369 case 'e': case 'E': case 'g': case 'G': case 'f':
370 sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
372 sprintf(Buffer, FmtBuf, (void*)Args[ArgNo++].PointerVal); break;
374 sprintf(Buffer, FmtBuf, (char*)Args[ArgNo++].PointerVal); break;
375 default: cout << "<unknown printf code '" << *FmtStr << "'!>";
378 strcpy(OutputBuffer, Buffer);
379 OutputBuffer += strlen(Buffer);
386 // int printf(sbyte *, ...) - a very rough implementation to make output useful.
387 GenericValue lle_X_printf(FunctionType *M, const vector<GenericValue> &Args) {
389 vector<GenericValue> NewArgs;
390 GenericValue GV; GV.PointerVal = (PointerTy)Buffer;
391 NewArgs.push_back(GV);
392 NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
393 GV = lle_X_sprintf(M, NewArgs);
398 // int sscanf(const char *format, ...);
399 GenericValue lle_X_sscanf(FunctionType *M, const vector<GenericValue> &args) {
400 assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
402 const char *Args[10];
403 for (unsigned i = 0; i < args.size(); ++i)
404 Args[i] = (const char*)args[i].PointerVal;
407 GV.IntVal = sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
408 Args[5], Args[6], Args[7], Args[8], Args[9]);
413 // int clock(void) - Profiling implementation
414 GenericValue lle_i_clock(FunctionType *M, const vector<GenericValue> &Args) {
415 extern int clock(void);
416 GenericValue GV; GV.IntVal = clock();
420 //===----------------------------------------------------------------------===//
422 //===----------------------------------------------------------------------===//
424 // getFILE - Turn a pointer in the host address space into a legit pointer in
425 // the interpreter address space. For the most part, this is an identity
426 // transformation, but if the program refers to stdio, stderr, stdin then they
427 // have pointers that are relative to the __iob array. If this is the case,
428 // change the FILE into the REAL stdio stream.
430 static FILE *getFILE(PointerTy Ptr) {
431 static Module *LastMod = 0;
432 static PointerTy IOBBase = 0;
433 static unsigned FILESize;
435 if (LastMod != TheInterpreter->getModule()) { // Module change or initialize?
436 Module *M = LastMod = TheInterpreter->getModule();
438 // Check to see if the currently loaded module contains an __iob symbol...
439 GlobalVariable *IOB = 0;
440 SymbolTable &ST = M->getSymbolTable();
441 for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I) {
442 SymbolTable::VarMap &M = I->second;
443 for (SymbolTable::VarMap::iterator J = M.begin(), E = M.end();
445 if (J->first == "__iob")
446 if ((IOB = dyn_cast<GlobalVariable>(J->second)))
451 // If we found an __iob symbol now, find out what the actual address it's
454 // Get the address the array lives in...
455 GlobalAddress *Address =
456 (GlobalAddress*)IOB->getOrCreateAnnotation(GlobalAddressAID);
457 IOBBase = (PointerTy)(GenericValue*)Address->Ptr;
459 // Figure out how big each element of the array is...
460 const ArrayType *AT =
461 dyn_cast<ArrayType>(IOB->getType()->getElementType());
463 FILESize = TD.getTypeSize(AT->getElementType());
465 FILESize = 16*8; // Default size
469 // Check to see if this is a reference to __iob...
471 unsigned FDNum = (Ptr-IOBBase)/FILESize;
484 // FILE *fopen(const char *filename, const char *mode);
485 GenericValue lle_X_fopen(FunctionType *M, const vector<GenericValue> &Args) {
486 assert(Args.size() == 2);
489 GV.PointerVal = (PointerTy)fopen((const char *)Args[0].PointerVal,
490 (const char *)Args[1].PointerVal);
494 // int fclose(FILE *F);
495 GenericValue lle_X_fclose(FunctionType *M, const vector<GenericValue> &Args) {
496 assert(Args.size() == 1);
499 GV.IntVal = fclose(getFILE(Args[0].PointerVal));
503 // int feof(FILE *stream);
504 GenericValue lle_X_feof(FunctionType *M, const vector<GenericValue> &Args) {
505 assert(Args.size() == 1);
508 GV.IntVal = feof(getFILE(Args[0].PointerVal));
512 // size_t fread(void *ptr, size_t size, size_t nitems, FILE *stream);
513 GenericValue lle_X_fread(FunctionType *M, const vector<GenericValue> &Args) {
514 assert(Args.size() == 4);
517 GV.UIntVal = fread((void*)Args[0].PointerVal, Args[1].UIntVal,
518 Args[2].UIntVal, getFILE(Args[3].PointerVal));
522 // size_t fwrite(const void *ptr, size_t size, size_t nitems, FILE *stream);
523 GenericValue lle_X_fwrite(FunctionType *M, const vector<GenericValue> &Args) {
524 assert(Args.size() == 4);
527 GV.UIntVal = fwrite((void*)Args[0].PointerVal, Args[1].UIntVal,
528 Args[2].UIntVal, getFILE(Args[3].PointerVal));
532 // char *fgets(char *s, int n, FILE *stream);
533 GenericValue lle_X_fgets(FunctionType *M, const vector<GenericValue> &Args) {
534 assert(Args.size() == 3);
537 GV.PointerVal = (PointerTy)fgets((char*)Args[0].PointerVal, Args[1].IntVal,
538 getFILE(Args[2].PointerVal));
542 // FILE *freopen(const char *path, const char *mode, FILE *stream);
543 GenericValue lle_X_freopen(FunctionType *M, const vector<GenericValue> &Args) {
544 assert(Args.size() == 3);
546 GV.PointerVal = (PointerTy)freopen((char*)Args[0].PointerVal,
547 (char*)Args[1].PointerVal,
548 getFILE(Args[2].PointerVal));
552 // int fflush(FILE *stream);
553 GenericValue lle_X_fflush(FunctionType *M, const vector<GenericValue> &Args) {
554 assert(Args.size() == 1);
556 GV.IntVal = fflush(getFILE(Args[0].PointerVal));
560 // int getc(FILE *stream);
561 GenericValue lle_X_getc(FunctionType *M, const vector<GenericValue> &Args) {
562 assert(Args.size() == 1);
564 GV.IntVal = getc(getFILE(Args[0].PointerVal));
568 // int fputc(int C, FILE *stream);
569 GenericValue lle_X_fputc(FunctionType *M, const vector<GenericValue> &Args) {
570 assert(Args.size() == 2);
572 GV.IntVal = fputc(Args[0].IntVal, getFILE(Args[1].PointerVal));
576 // int ungetc(int C, FILE *stream);
577 GenericValue lle_X_ungetc(FunctionType *M, const vector<GenericValue> &Args) {
578 assert(Args.size() == 2);
580 GV.IntVal = ungetc(Args[0].IntVal, getFILE(Args[1].PointerVal));
584 // int fprintf(FILE *,sbyte *, ...) - a very rough implementation to make output
586 GenericValue lle_X_fprintf(FunctionType *M, const vector<GenericValue> &Args) {
587 assert(Args.size() > 2);
589 vector<GenericValue> NewArgs;
590 GenericValue GV; GV.PointerVal = (PointerTy)Buffer;
591 NewArgs.push_back(GV);
592 NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end());
593 GV = lle_X_sprintf(M, NewArgs);
595 fputs(Buffer, getFILE(Args[0].PointerVal));
602 void Interpreter::initializeExternalMethods() {
603 FuncNames["lle_VP_printstr"] = lle_VP_printstr;
604 FuncNames["lle_X_print"] = lle_X_print;
605 FuncNames["lle_X_printVal"] = lle_X_printVal;
606 FuncNames["lle_X_printString"] = lle_X_printString;
607 FuncNames["lle_X_printUByte"] = lle_X_printUByte;
608 FuncNames["lle_X_printSByte"] = lle_X_printSByte;
609 FuncNames["lle_X_printUShort"] = lle_X_printUShort;
610 FuncNames["lle_X_printShort"] = lle_X_printShort;
611 FuncNames["lle_X_printInt"] = lle_X_printInt;
612 FuncNames["lle_X_printUInt"] = lle_X_printUInt;
613 FuncNames["lle_X_printLong"] = lle_X_printLong;
614 FuncNames["lle_X_printULong"] = lle_X_printULong;
615 FuncNames["lle_X_printFloat"] = lle_X_printFloat;
616 FuncNames["lle_X_printDouble"] = lle_X_printDouble;
617 FuncNames["lle_X_printPointer"] = lle_X_printPointer;
618 FuncNames["lle_Vb_putchar"] = lle_Vb_putchar;
619 FuncNames["lle_ii_putchar"] = lle_ii_putchar;
620 FuncNames["lle_VB_putchar"] = lle_VB_putchar;
621 FuncNames["lle_V___main"] = lle_V___main;
622 FuncNames["lle_X_exit"] = lle_X_exit;
623 FuncNames["lle_X_abort"] = lle_X_abort;
624 FuncNames["lle_X_malloc"] = lle_X_malloc;
625 FuncNames["lle_X_free"] = lle_X_free;
626 FuncNames["lle_X_atoi"] = lle_X_atoi;
627 FuncNames["lle_X_pow"] = lle_X_pow;
628 FuncNames["lle_X_exp"] = lle_X_exp;
629 FuncNames["lle_X_log"] = lle_X_log;
630 FuncNames["lle_X_floor"] = lle_X_floor;
631 FuncNames["lle_X_srand"] = lle_X_srand;
632 FuncNames["lle_X_drand48"] = lle_X_drand48;
633 FuncNames["lle_X_srand48"] = lle_X_srand48;
634 FuncNames["lle_X_lrand48"] = lle_X_lrand48;
635 FuncNames["lle_X_sqrt"] = lle_X_sqrt;
636 FuncNames["lle_X_printf"] = lle_X_printf;
637 FuncNames["lle_X_sprintf"] = lle_X_sprintf;
638 FuncNames["lle_X_sscanf"] = lle_X_sscanf;
639 FuncNames["lle_i_clock"] = lle_i_clock;
640 FuncNames["lle_X_fopen"] = lle_X_fopen;
641 FuncNames["lle_X_fclose"] = lle_X_fclose;
642 FuncNames["lle_X_feof"] = lle_X_feof;
643 FuncNames["lle_X_fread"] = lle_X_fread;
644 FuncNames["lle_X_fwrite"] = lle_X_fwrite;
645 FuncNames["lle_X_fgets"] = lle_X_fgets;
646 FuncNames["lle_X_fflush"] = lle_X_fflush;
647 FuncNames["lle_X_fgetc"] = lle_X_getc;
648 FuncNames["lle_X_getc"] = lle_X_getc;
649 FuncNames["lle_X_fputc"] = lle_X_fputc;
650 FuncNames["lle_X_ungetc"] = lle_X_ungetc;
651 FuncNames["lle_X_fprintf"] = lle_X_fprintf;
652 FuncNames["lle_X_freopen"] = lle_X_freopen;