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/Module.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/SymbolTable.h"
18 #include "llvm/Target/TargetData.h"
27 typedef GenericValue (*ExFunc)(FunctionType *, const vector<GenericValue> &);
28 static std::map<const Function *, ExFunc> Functions;
29 static std::map<std::string, ExFunc> FuncNames;
31 static Interpreter *TheInterpreter;
33 // getCurrentExecutablePath() - Return the directory that the lli executable
36 std::string Interpreter::getCurrentExecutablePath() const {
38 if (dladdr(&TheInterpreter, &Info) == 0) return "";
40 std::string LinkAddr(Info.dli_fname);
41 unsigned SlashPos = LinkAddr.rfind('/');
42 if (SlashPos != std::string::npos)
43 LinkAddr.resize(SlashPos); // Trim the executable name off...
49 static char getTypeID(const Type *Ty) {
50 switch (Ty->getPrimitiveID()) {
51 case Type::VoidTyID: return 'V';
52 case Type::BoolTyID: return 'o';
53 case Type::UByteTyID: return 'B';
54 case Type::SByteTyID: return 'b';
55 case Type::UShortTyID: return 'S';
56 case Type::ShortTyID: return 's';
57 case Type::UIntTyID: return 'I';
58 case Type::IntTyID: return 'i';
59 case Type::ULongTyID: return 'L';
60 case Type::LongTyID: return 'l';
61 case Type::FloatTyID: return 'F';
62 case Type::DoubleTyID: return 'D';
63 case Type::PointerTyID: return 'P';
64 case Type::FunctionTyID: return 'M';
65 case Type::StructTyID: return 'T';
66 case Type::ArrayTyID: return 'A';
67 case Type::OpaqueTyID: return 'O';
72 static ExFunc lookupFunction(const Function *M) {
73 // Function not found, look it up... start by figuring out what the
74 // composite function name should be.
75 std::string ExtName = "lle_";
76 const FunctionType *MT = M->getFunctionType();
77 for (unsigned i = 0; const Type *Ty = MT->getContainedType(i); ++i)
78 ExtName += getTypeID(Ty);
79 ExtName += "_" + M->getName();
81 //cout << "Tried: '" << ExtName << "'\n";
82 ExFunc FnPtr = FuncNames[ExtName];
84 FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ExtName.c_str());
86 FnPtr = FuncNames["lle_X_"+M->getName()];
87 if (FnPtr == 0) // Try calling a generic function... if it exists...
88 FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ("lle_X_"+M->getName()).c_str());
90 Functions.insert(std::make_pair(M, FnPtr)); // Cache for later
94 GenericValue Interpreter::callExternalMethod(Function *M,
95 const vector<GenericValue> &ArgVals) {
96 TheInterpreter = this;
98 // Do a lookup to see if the function is in our cache... this should just be a
99 // defered annotation!
100 std::map<const Function *, ExFunc>::iterator FI = Functions.find(M);
101 ExFunc Fn = (FI == Functions.end()) ? lookupFunction(M) : FI->second;
103 cout << "Tried to execute an unknown external function: "
104 << M->getType()->getDescription() << " " << M->getName() << "\n";
105 return GenericValue();
108 // TODO: FIXME when types are not const!
109 GenericValue Result = Fn(const_cast<FunctionType*>(M->getFunctionType()),
115 //===----------------------------------------------------------------------===//
116 // Functions "exported" to the running application...
118 extern "C" { // Don't add C++ manglings to llvm mangling :)
120 // Implement void printstr([ubyte {x N}] *)
121 GenericValue lle_VP_printstr(FunctionType *M, const vector<GenericValue> &ArgVal){
122 assert(ArgVal.size() == 1 && "printstr only takes one argument!");
123 cout << (char*)ArgVal[0].PointerVal;
124 return GenericValue();
127 // Implement 'void print(X)' for every type...
128 GenericValue lle_X_print(FunctionType *M, const vector<GenericValue> &ArgVals) {
129 assert(ArgVals.size() == 1 && "generic print only takes one argument!");
131 Interpreter::print(M->getParamTypes()[0], ArgVals[0]);
132 return GenericValue();
135 // Implement 'void printVal(X)' for every type...
136 GenericValue lle_X_printVal(FunctionType *M, const vector<GenericValue> &ArgVal) {
137 assert(ArgVal.size() == 1 && "generic print only takes one argument!");
139 // Specialize print([ubyte {x N} ] *) and print(sbyte *)
140 if (const PointerType *PTy =
141 dyn_cast<PointerType>(M->getParamTypes()[0].get()))
142 if (PTy->getElementType() == Type::SByteTy ||
143 isa<ArrayType>(PTy->getElementType())) {
144 return lle_VP_printstr(M, ArgVal);
147 Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);
148 return GenericValue();
151 // Implement 'void printString(X)'
152 // Argument must be [ubyte {x N} ] * or sbyte *
153 GenericValue lle_X_printString(FunctionType *M, const vector<GenericValue> &ArgVal) {
154 assert(ArgVal.size() == 1 && "generic print only takes one argument!");
155 return lle_VP_printstr(M, ArgVal);
158 // Implement 'void print<TYPE>(X)' for each primitive type or pointer type
159 #define PRINT_TYPE_FUNC(TYPENAME,TYPEID) \
160 GenericValue lle_X_print##TYPENAME(FunctionType *M,\
161 const vector<GenericValue> &ArgVal) {\
162 assert(ArgVal.size() == 1 && "generic print only takes one argument!");\
163 assert(M->getParamTypes()[0].get()->getPrimitiveID() == Type::TYPEID);\
164 Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);\
165 return GenericValue();\
168 PRINT_TYPE_FUNC(SByte, SByteTyID)
169 PRINT_TYPE_FUNC(UByte, UByteTyID)
170 PRINT_TYPE_FUNC(Short, ShortTyID)
171 PRINT_TYPE_FUNC(UShort, UShortTyID)
172 PRINT_TYPE_FUNC(Int, IntTyID)
173 PRINT_TYPE_FUNC(UInt, UIntTyID)
174 PRINT_TYPE_FUNC(Long, LongTyID)
175 PRINT_TYPE_FUNC(ULong, ULongTyID)
176 PRINT_TYPE_FUNC(Float, FloatTyID)
177 PRINT_TYPE_FUNC(Double, DoubleTyID)
178 PRINT_TYPE_FUNC(Pointer, PointerTyID)
181 // void putchar(sbyte)
182 GenericValue lle_Vb_putchar(FunctionType *M, const vector<GenericValue> &Args) {
183 cout << Args[0].SByteVal;
184 return GenericValue();
188 GenericValue lle_ii_putchar(FunctionType *M, const vector<GenericValue> &Args) {
189 cout << ((char)Args[0].IntVal) << std::flush;
193 // void putchar(ubyte)
194 GenericValue lle_VB_putchar(FunctionType *M, const vector<GenericValue> &Args) {
195 cout << Args[0].SByteVal << std::flush;
200 GenericValue lle_V___main(FunctionType *M, const vector<GenericValue> &Args) {
201 return GenericValue();
205 GenericValue lle_X_exit(FunctionType *M, const vector<GenericValue> &Args) {
206 TheInterpreter->exitCalled(Args[0]);
207 return GenericValue();
211 GenericValue lle_X_abort(FunctionType *M, const vector<GenericValue> &Args) {
212 std::cerr << "***PROGRAM ABORTED***!\n";
215 TheInterpreter->exitCalled(GV);
216 return GenericValue();
219 // void *malloc(uint)
220 GenericValue lle_X_malloc(FunctionType *M, const vector<GenericValue> &Args) {
221 assert(Args.size() == 1 && "Malloc expects one argument!");
223 GV.PointerVal = (PointerTy)malloc(Args[0].UIntVal);
228 GenericValue lle_X_free(FunctionType *M, const vector<GenericValue> &Args) {
229 assert(Args.size() == 1);
230 free((void*)Args[0].PointerVal);
231 return GenericValue();
235 GenericValue lle_X_atoi(FunctionType *M, const vector<GenericValue> &Args) {
236 assert(Args.size() == 1);
238 GV.IntVal = atoi((char*)Args[0].PointerVal);
242 // double pow(double, double)
243 GenericValue lle_X_pow(FunctionType *M, const vector<GenericValue> &Args) {
244 assert(Args.size() == 2);
246 GV.DoubleVal = pow(Args[0].DoubleVal, Args[1].DoubleVal);
250 // double exp(double)
251 GenericValue lle_X_exp(FunctionType *M, const vector<GenericValue> &Args) {
252 assert(Args.size() == 1);
254 GV.DoubleVal = exp(Args[0].DoubleVal);
258 // double sqrt(double)
259 GenericValue lle_X_sqrt(FunctionType *M, const vector<GenericValue> &Args) {
260 assert(Args.size() == 1);
262 GV.DoubleVal = sqrt(Args[0].DoubleVal);
266 // double log(double)
267 GenericValue lle_X_log(FunctionType *M, const vector<GenericValue> &Args) {
268 assert(Args.size() == 1);
270 GV.DoubleVal = log(Args[0].DoubleVal);
274 // int isnan(double value);
275 GenericValue lle_X_isnan(FunctionType *F, const vector<GenericValue> &Args) {
276 assert(Args.size() == 1);
278 GV.IntVal = isnan(Args[0].DoubleVal);
282 // double floor(double)
283 GenericValue lle_X_floor(FunctionType *M, const vector<GenericValue> &Args) {
284 assert(Args.size() == 1);
286 GV.DoubleVal = floor(Args[0].DoubleVal);
291 GenericValue lle_X_drand48(FunctionType *M, const vector<GenericValue> &Args) {
292 assert(Args.size() == 0);
294 GV.DoubleVal = drand48();
299 GenericValue lle_X_lrand48(FunctionType *M, const vector<GenericValue> &Args) {
300 assert(Args.size() == 0);
302 GV.IntVal = lrand48();
306 // void srand48(long)
307 GenericValue lle_X_srand48(FunctionType *M, const vector<GenericValue> &Args) {
308 assert(Args.size() == 1);
309 srand48(Args[0].IntVal);
310 return GenericValue();
314 GenericValue lle_X_srand(FunctionType *M, const vector<GenericValue> &Args) {
315 assert(Args.size() == 1);
316 srand(Args[0].UIntVal);
317 return GenericValue();
320 // int sprintf(sbyte *, sbyte *, ...) - a very rough implementation to make
322 GenericValue lle_X_sprintf(FunctionType *M, const vector<GenericValue> &Args) {
323 char *OutputBuffer = (char *)Args[0].PointerVal;
324 const char *FmtStr = (const char *)Args[1].PointerVal;
327 // printf should return # chars printed. This is completely incorrect, but
328 // close enough for now.
329 GenericValue GV; GV.IntVal = strlen(FmtStr);
332 case 0: return GV; // Null terminator...
333 default: // Normal nonspecial character
334 sprintf(OutputBuffer++, "%c", *FmtStr++);
336 case '\\': { // Handle escape codes
337 sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
338 FmtStr += 2; OutputBuffer += 2;
341 case '%': { // Handle format specifiers
342 char FmtBuf[100] = "", Buffer[1000] = "";
345 char Last = *FB++ = *FmtStr++;
346 unsigned HowLong = 0;
347 while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
348 Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
349 Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
350 Last != 'p' && Last != 's' && Last != '%') {
351 if (Last == 'l' || Last == 'L') HowLong++; // Keep track of l's
352 Last = *FB++ = *FmtStr++;
358 sprintf(Buffer, FmtBuf); break;
360 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal); break;
366 // Make sure we use %lld with a 64 bit argument because we might be
367 // compiling LLI on a 32 bit compiler.
368 unsigned Size = strlen(FmtBuf);
369 FmtBuf[Size] = FmtBuf[Size-1];
371 FmtBuf[Size-1] = 'l';
373 sprintf(Buffer, FmtBuf, Args[ArgNo++].ULongVal);
375 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal); break;
376 case 'e': case 'E': case 'g': case 'G': case 'f':
377 sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
379 sprintf(Buffer, FmtBuf, (void*)Args[ArgNo++].PointerVal); break;
381 sprintf(Buffer, FmtBuf, (char*)Args[ArgNo++].PointerVal); break;
382 default: cout << "<unknown printf code '" << *FmtStr << "'!>";
385 strcpy(OutputBuffer, Buffer);
386 OutputBuffer += strlen(Buffer);
393 // int printf(sbyte *, ...) - a very rough implementation to make output useful.
394 GenericValue lle_X_printf(FunctionType *M, const vector<GenericValue> &Args) {
396 vector<GenericValue> NewArgs;
397 GenericValue GV; GV.PointerVal = (PointerTy)Buffer;
398 NewArgs.push_back(GV);
399 NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
400 GV = lle_X_sprintf(M, NewArgs);
405 // int sscanf(const char *format, ...);
406 GenericValue lle_X_sscanf(FunctionType *M, const vector<GenericValue> &args) {
407 assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
409 const char *Args[10];
410 for (unsigned i = 0; i < args.size(); ++i)
411 Args[i] = (const char*)args[i].PointerVal;
414 GV.IntVal = sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
415 Args[5], Args[6], Args[7], Args[8], Args[9]);
420 // int clock(void) - Profiling implementation
421 GenericValue lle_i_clock(FunctionType *M, const vector<GenericValue> &Args) {
422 extern int clock(void);
423 GenericValue GV; GV.IntVal = clock();
427 //===----------------------------------------------------------------------===//
429 //===----------------------------------------------------------------------===//
431 // getFILE - Turn a pointer in the host address space into a legit pointer in
432 // the interpreter address space. For the most part, this is an identity
433 // transformation, but if the program refers to stdio, stderr, stdin then they
434 // have pointers that are relative to the __iob array. If this is the case,
435 // change the FILE into the REAL stdio stream.
437 static FILE *getFILE(PointerTy Ptr) {
438 static Module *LastMod = 0;
439 static PointerTy IOBBase = 0;
440 static unsigned FILESize;
442 if (LastMod != &TheInterpreter->getModule()) { // Module change or initialize?
443 Module *M = LastMod = &TheInterpreter->getModule();
445 // Check to see if the currently loaded module contains an __iob symbol...
446 GlobalVariable *IOB = 0;
447 SymbolTable &ST = M->getSymbolTable();
448 for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I) {
449 SymbolTable::VarMap &M = I->second;
450 for (SymbolTable::VarMap::iterator J = M.begin(), E = M.end();
452 if (J->first == "__iob")
453 if ((IOB = dyn_cast<GlobalVariable>(J->second)))
458 #if 0 /// FIXME! __iob support for LLI
459 // If we found an __iob symbol now, find out what the actual address it's
462 // Get the address the array lives in...
463 GlobalAddress *Address =
464 (GlobalAddress*)IOB->getOrCreateAnnotation(GlobalAddressAID);
465 IOBBase = (PointerTy)(GenericValue*)Address->Ptr;
467 // Figure out how big each element of the array is...
468 const ArrayType *AT =
469 dyn_cast<ArrayType>(IOB->getType()->getElementType());
471 FILESize = TD.getTypeSize(AT->getElementType());
473 FILESize = 16*8; // Default size
478 // Check to see if this is a reference to __iob...
480 unsigned FDNum = (Ptr-IOBBase)/FILESize;
493 // FILE *fopen(const char *filename, const char *mode);
494 GenericValue lle_X_fopen(FunctionType *M, const vector<GenericValue> &Args) {
495 assert(Args.size() == 2);
498 GV.PointerVal = (PointerTy)fopen((const char *)Args[0].PointerVal,
499 (const char *)Args[1].PointerVal);
503 // int fclose(FILE *F);
504 GenericValue lle_X_fclose(FunctionType *M, const vector<GenericValue> &Args) {
505 assert(Args.size() == 1);
508 GV.IntVal = fclose(getFILE(Args[0].PointerVal));
512 // int feof(FILE *stream);
513 GenericValue lle_X_feof(FunctionType *M, const vector<GenericValue> &Args) {
514 assert(Args.size() == 1);
517 GV.IntVal = feof(getFILE(Args[0].PointerVal));
521 // size_t fread(void *ptr, size_t size, size_t nitems, FILE *stream);
522 GenericValue lle_X_fread(FunctionType *M, const vector<GenericValue> &Args) {
523 assert(Args.size() == 4);
526 GV.UIntVal = fread((void*)Args[0].PointerVal, Args[1].UIntVal,
527 Args[2].UIntVal, getFILE(Args[3].PointerVal));
531 // size_t fwrite(const void *ptr, size_t size, size_t nitems, FILE *stream);
532 GenericValue lle_X_fwrite(FunctionType *M, const vector<GenericValue> &Args) {
533 assert(Args.size() == 4);
536 GV.UIntVal = fwrite((void*)Args[0].PointerVal, Args[1].UIntVal,
537 Args[2].UIntVal, getFILE(Args[3].PointerVal));
541 // char *fgets(char *s, int n, FILE *stream);
542 GenericValue lle_X_fgets(FunctionType *M, const vector<GenericValue> &Args) {
543 assert(Args.size() == 3);
546 GV.PointerVal = (PointerTy)fgets((char*)Args[0].PointerVal, Args[1].IntVal,
547 getFILE(Args[2].PointerVal));
551 // FILE *freopen(const char *path, const char *mode, FILE *stream);
552 GenericValue lle_X_freopen(FunctionType *M, const vector<GenericValue> &Args) {
553 assert(Args.size() == 3);
555 GV.PointerVal = (PointerTy)freopen((char*)Args[0].PointerVal,
556 (char*)Args[1].PointerVal,
557 getFILE(Args[2].PointerVal));
561 // int fflush(FILE *stream);
562 GenericValue lle_X_fflush(FunctionType *M, const vector<GenericValue> &Args) {
563 assert(Args.size() == 1);
565 GV.IntVal = fflush(getFILE(Args[0].PointerVal));
569 // int getc(FILE *stream);
570 GenericValue lle_X_getc(FunctionType *M, const vector<GenericValue> &Args) {
571 assert(Args.size() == 1);
573 GV.IntVal = getc(getFILE(Args[0].PointerVal));
577 // int fputc(int C, FILE *stream);
578 GenericValue lle_X_fputc(FunctionType *M, const vector<GenericValue> &Args) {
579 assert(Args.size() == 2);
581 GV.IntVal = fputc(Args[0].IntVal, getFILE(Args[1].PointerVal));
585 // int ungetc(int C, FILE *stream);
586 GenericValue lle_X_ungetc(FunctionType *M, const vector<GenericValue> &Args) {
587 assert(Args.size() == 2);
589 GV.IntVal = ungetc(Args[0].IntVal, getFILE(Args[1].PointerVal));
593 // int fprintf(FILE *,sbyte *, ...) - a very rough implementation to make output
595 GenericValue lle_X_fprintf(FunctionType *M, const vector<GenericValue> &Args) {
596 assert(Args.size() > 2);
598 vector<GenericValue> NewArgs;
599 GenericValue GV; GV.PointerVal = (PointerTy)Buffer;
600 NewArgs.push_back(GV);
601 NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end());
602 GV = lle_X_sprintf(M, NewArgs);
604 fputs(Buffer, getFILE(Args[0].PointerVal));
611 void Interpreter::initializeExternalMethods() {
612 FuncNames["lle_VP_printstr"] = lle_VP_printstr;
613 FuncNames["lle_X_print"] = lle_X_print;
614 FuncNames["lle_X_printVal"] = lle_X_printVal;
615 FuncNames["lle_X_printString"] = lle_X_printString;
616 FuncNames["lle_X_printUByte"] = lle_X_printUByte;
617 FuncNames["lle_X_printSByte"] = lle_X_printSByte;
618 FuncNames["lle_X_printUShort"] = lle_X_printUShort;
619 FuncNames["lle_X_printShort"] = lle_X_printShort;
620 FuncNames["lle_X_printInt"] = lle_X_printInt;
621 FuncNames["lle_X_printUInt"] = lle_X_printUInt;
622 FuncNames["lle_X_printLong"] = lle_X_printLong;
623 FuncNames["lle_X_printULong"] = lle_X_printULong;
624 FuncNames["lle_X_printFloat"] = lle_X_printFloat;
625 FuncNames["lle_X_printDouble"] = lle_X_printDouble;
626 FuncNames["lle_X_printPointer"] = lle_X_printPointer;
627 FuncNames["lle_Vb_putchar"] = lle_Vb_putchar;
628 FuncNames["lle_ii_putchar"] = lle_ii_putchar;
629 FuncNames["lle_VB_putchar"] = lle_VB_putchar;
630 FuncNames["lle_V___main"] = lle_V___main;
631 FuncNames["lle_X_exit"] = lle_X_exit;
632 FuncNames["lle_X_abort"] = lle_X_abort;
633 FuncNames["lle_X_malloc"] = lle_X_malloc;
634 FuncNames["lle_X_free"] = lle_X_free;
635 FuncNames["lle_X_atoi"] = lle_X_atoi;
636 FuncNames["lle_X_pow"] = lle_X_pow;
637 FuncNames["lle_X_exp"] = lle_X_exp;
638 FuncNames["lle_X_log"] = lle_X_log;
639 FuncNames["lle_X_isnan"] = lle_X_isnan;
640 FuncNames["lle_X_floor"] = lle_X_floor;
641 FuncNames["lle_X_srand"] = lle_X_srand;
642 FuncNames["lle_X_drand48"] = lle_X_drand48;
643 FuncNames["lle_X_srand48"] = lle_X_srand48;
644 FuncNames["lle_X_lrand48"] = lle_X_lrand48;
645 FuncNames["lle_X_sqrt"] = lle_X_sqrt;
646 FuncNames["lle_X_printf"] = lle_X_printf;
647 FuncNames["lle_X_sprintf"] = lle_X_sprintf;
648 FuncNames["lle_X_sscanf"] = lle_X_sscanf;
649 FuncNames["lle_i_clock"] = lle_i_clock;
650 FuncNames["lle_X_fopen"] = lle_X_fopen;
651 FuncNames["lle_X_fclose"] = lle_X_fclose;
652 FuncNames["lle_X_feof"] = lle_X_feof;
653 FuncNames["lle_X_fread"] = lle_X_fread;
654 FuncNames["lle_X_fwrite"] = lle_X_fwrite;
655 FuncNames["lle_X_fgets"] = lle_X_fgets;
656 FuncNames["lle_X_fflush"] = lle_X_fflush;
657 FuncNames["lle_X_fgetc"] = lle_X_getc;
658 FuncNames["lle_X_getc"] = lle_X_getc;
659 FuncNames["lle_X_fputc"] = lle_X_fputc;
660 FuncNames["lle_X_ungetc"] = lle_X_ungetc;
661 FuncNames["lle_X_fprintf"] = lle_X_fprintf;
662 FuncNames["lle_X_freopen"] = lle_X_freopen;