c8aa46a186e384f9cc69519fe2f8041426cb494b
[oota-llvm.git] / lib / ExecutionEngine / Interpreter / ExternalFunctions.cpp
1 //===-- ExternalMethods.cpp - Implement External Functions ----------------===//
2 // 
3 //  This file contains both code to deal with invoking "external" methods, but
4 //  also contains code that implements "exported" external methods. 
5 //
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.
9 //
10 //===----------------------------------------------------------------------===//
11
12 #include "Interpreter.h"
13 #include "llvm/DerivedTypes.h"
14 #include <map>
15 #include <dlfcn.h>
16 #include <iostream>
17 #include <link.h>
18 #include <math.h>
19 #include <stdio.h>
20 using std::vector;
21 using std::cout;
22
23 typedef GenericValue (*ExFunc)(FunctionType *, const vector<GenericValue> &);
24 static std::map<const Function *, ExFunc> Functions;
25 static std::map<std::string, ExFunc> FuncNames;
26
27 static Interpreter *TheInterpreter;
28
29 // getCurrentExecutablePath() - Return the directory that the lli executable
30 // lives in.
31 //
32 std::string Interpreter::getCurrentExecutablePath() const {
33   Dl_info Info;
34   if (dladdr(&TheInterpreter, &Info) == 0) return "";
35   
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...
40
41   return LinkAddr;
42 }
43
44
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';
64   default: return 'U';
65   }
66 }
67
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();
76
77   //cout << "Tried: '" << ExtName << "'\n";
78   ExFunc FnPtr = FuncNames[ExtName];
79   if (FnPtr == 0)
80     FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ExtName.c_str());
81   if (FnPtr == 0)
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());
85   if (FnPtr != 0)
86     Functions.insert(std::make_pair(M, FnPtr));  // Cache for later
87   return FnPtr;
88 }
89
90 GenericValue Interpreter::callExternalMethod(Function *M,
91                                          const vector<GenericValue> &ArgVals) {
92   TheInterpreter = this;
93
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;
98   if (Fn == 0) {
99     cout << "Tried to execute an unknown external method: "
100          << M->getType()->getDescription() << " " << M->getName() << "\n";
101     return GenericValue();
102   }
103
104   // TODO: FIXME when types are not const!
105   GenericValue Result = Fn(const_cast<FunctionType*>(M->getFunctionType()),ArgVals);
106   return Result;
107 }
108
109
110 //===----------------------------------------------------------------------===//
111 //  Functions "exported" to the running application...
112 //
113 extern "C" {  // Don't add C++ manglings to llvm mangling :)
114
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();
120 }
121
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!");
125
126   Interpreter::print(M->getParamTypes()[0], ArgVals[0]);
127   return GenericValue();
128 }
129
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!");
133
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);
139     }
140
141   Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);
142   return GenericValue();
143 }
144
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);
150 }
151
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();\
160   }
161
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)
173
174
175 // void "putchar"(sbyte)
176 GenericValue lle_Vb_putchar(FunctionType *M, const vector<GenericValue> &Args) {
177   cout << Args[0].SByteVal;
178   return GenericValue();
179 }
180
181 // int "putchar"(int)
182 GenericValue lle_ii_putchar(FunctionType *M, const vector<GenericValue> &Args) {
183   cout << ((char)Args[0].IntVal) << std::flush;
184   return Args[0];
185 }
186
187 // void "putchar"(ubyte)
188 GenericValue lle_VB_putchar(FunctionType *M, const vector<GenericValue> &Args) {
189   cout << Args[0].SByteVal << std::flush;
190   return Args[0];
191 }
192
193 // void "__main"()
194 GenericValue lle_V___main(FunctionType *M, const vector<GenericValue> &Args) {
195   return GenericValue();
196 }
197
198 // void "exit"(int)
199 GenericValue lle_X_exit(FunctionType *M, const vector<GenericValue> &Args) {
200   TheInterpreter->exitCalled(Args[0]);
201   return GenericValue();
202 }
203
204 // void *malloc(uint)
205 GenericValue lle_X_malloc(FunctionType *M, const vector<GenericValue> &Args) {
206   assert(Args.size() == 1 && "Malloc expects one argument!");
207   GenericValue GV;
208   GV.PointerVal = (PointerTy)malloc(Args[0].UIntVal);
209   return GV;
210 }
211
212 // void free(void *)
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();
217 }
218
219 // int atoi(char *)
220 GenericValue lle_X_atoi(FunctionType *M, const vector<GenericValue> &Args) {
221   assert(Args.size() == 1);
222   GenericValue GV;
223   GV.IntVal = atoi((char*)Args[0].PointerVal);
224   return GV;
225 }
226
227 // double pow(double, double)
228 GenericValue lle_X_pow(FunctionType *M, const vector<GenericValue> &Args) {
229   assert(Args.size() == 2);
230   GenericValue GV;
231   GV.DoubleVal = pow(Args[0].DoubleVal, Args[1].DoubleVal);
232   return GV;
233 }
234
235 // double exp(double)
236 GenericValue lle_X_exp(FunctionType *M, const vector<GenericValue> &Args) {
237   assert(Args.size() == 1);
238   GenericValue GV;
239   GV.DoubleVal = exp(Args[0].DoubleVal);
240   return GV;
241 }
242
243 // double sqrt(double)
244 GenericValue lle_X_sqrt(FunctionType *M, const vector<GenericValue> &Args) {
245   assert(Args.size() == 1);
246   GenericValue GV;
247   GV.DoubleVal = sqrt(Args[0].DoubleVal);
248   return GV;
249 }
250
251 // double log(double)
252 GenericValue lle_X_log(FunctionType *M, const vector<GenericValue> &Args) {
253   assert(Args.size() == 1);
254   GenericValue GV;
255   GV.DoubleVal = log(Args[0].DoubleVal);
256   return GV;
257 }
258
259 // double floor(double)
260 GenericValue lle_X_floor(FunctionType *M, const vector<GenericValue> &Args) {
261   assert(Args.size() == 1);
262   GenericValue GV;
263   GV.DoubleVal = floor(Args[0].DoubleVal);
264   return GV;
265 }
266
267 // double drand48()
268 GenericValue lle_X_drand48(FunctionType *M, const vector<GenericValue> &Args) {
269   assert(Args.size() == 0);
270   GenericValue GV;
271   GV.DoubleVal = drand48();
272   return GV;
273 }
274
275 // long lrand48()
276 GenericValue lle_X_lrand48(FunctionType *M, const vector<GenericValue> &Args) {
277   assert(Args.size() == 0);
278   GenericValue GV;
279   GV.IntVal = lrand48();
280   return GV;
281 }
282
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();
288 }
289
290 // void srand(uint)
291 GenericValue lle_X_srand(FunctionType *M, const vector<GenericValue> &Args) {
292   assert(Args.size() == 1);
293   srand(Args[0].UIntVal);
294   return GenericValue();
295 }
296
297 // int sprintf(sbyte *, sbyte *, ...) - a very rough implementation to make
298 // output useful.
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;
302   unsigned ArgNo = 2;
303
304   // printf should return # chars printed.  This is completely incorrect, but
305   // close enough for now.
306   GenericValue GV; GV.IntVal = strlen(FmtStr);
307   while (1) {
308     switch (*FmtStr) {
309     case 0: return GV;             // Null terminator...
310     default:                       // Normal nonspecial character
311       sprintf(OutputBuffer++, "%c", *FmtStr++);
312       break;
313     case '\\': {                   // Handle escape codes
314       sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
315       FmtStr += 2; OutputBuffer += 2;
316       break;
317     }
318     case '%': {                    // Handle format specifiers
319       char FmtBuf[100] = "", Buffer[1000] = "";
320       char *FB = FmtBuf;
321       *FB++ = *FmtStr++;
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++;
330       }
331       *FB = 0;
332       
333       switch (Last) {
334       case '%':
335         sprintf(Buffer, FmtBuf); break;
336       case 'c':
337         sprintf(Buffer, FmtBuf, Args[ArgNo++].SByteVal); break;
338       case 'd': case 'i':
339       case 'u': case 'o':
340       case 'x': case 'X':
341         if (HowLong == 2)
342           sprintf(Buffer, FmtBuf, Args[ArgNo++].ULongVal);
343         else
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;
347       case 'p':
348         sprintf(Buffer, FmtBuf, (void*)Args[ArgNo++].PointerVal); break;
349       case 's': 
350         sprintf(Buffer, FmtBuf, (char*)Args[ArgNo++].PointerVal); break;
351       default:  cout << "<unknown printf code '" << *FmtStr << "'!>";
352         ArgNo++; break;
353       }
354       strcpy(OutputBuffer, Buffer);
355       OutputBuffer += strlen(Buffer);
356       }
357       break;
358     }
359   }
360 }
361
362 // int printf(sbyte *, ...) - a very rough implementation to make output useful.
363 GenericValue lle_X_printf(FunctionType *M, const vector<GenericValue> &Args) {
364   char Buffer[10000];
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);
370   cout << Buffer;
371   return GV;
372 }
373
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!");
377
378   const char *Args[10];
379   for (unsigned i = 0; i < args.size(); ++i)
380     Args[i] = (const char*)args[i].PointerVal;
381
382   GenericValue GV;
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]);
385   return GV;
386 }
387
388
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();
393   return GV;
394 }
395
396 //===----------------------------------------------------------------------===//
397 // IO Functions...
398 //===----------------------------------------------------------------------===//
399
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);
403   GenericValue GV;
404
405   GV.PointerVal = (PointerTy)fopen((const char *)Args[0].PointerVal,
406                                    (const char *)Args[1].PointerVal);
407   return GV;
408 }
409
410 // int fclose(FILE *F);
411 GenericValue lle_X_fclose(FunctionType *M, const vector<GenericValue> &Args) {
412   assert(Args.size() == 1);
413   GenericValue GV;
414
415   GV.IntVal = fclose((FILE *)Args[0].PointerVal);
416   return GV;
417 }
418
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);
422   GenericValue GV;
423
424   GV.UIntVal = fread((void*)Args[0].PointerVal, Args[1].UIntVal,
425                      Args[2].UIntVal, (FILE*)Args[3].PointerVal);
426   return GV;
427 }
428
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);
432   GenericValue GV;
433
434   GV.UIntVal = fwrite((void*)Args[0].PointerVal, Args[1].UIntVal,
435                       Args[2].UIntVal, (FILE*)Args[3].PointerVal);
436   return GV;
437 }
438
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);
442   GenericValue GV;
443
444   GV.PointerVal = (PointerTy)fgets((char*)Args[0].PointerVal, Args[1].IntVal,
445                                    (FILE*)Args[2].PointerVal);
446   return GV;
447 }
448
449 // int fflush(FILE *stream);
450 GenericValue lle_X_fflush(FunctionType *M, const vector<GenericValue> &Args) {
451   assert(Args.size() == 1);
452   GenericValue GV;
453
454   GV.IntVal = fflush((FILE*)Args[0].PointerVal);
455   return GV;
456 }
457
458 } // End extern "C"
459
460
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;
504 }