efe2e8fe3284bf9685c1c6a1995f8dbc0cfcc12d
[oota-llvm.git] / lib / ExecutionEngine / Interpreter / ExternalFunctions.cpp
1 //===-- ExternalFunctions.cpp - Implement External Functions --------------===//
2 // 
3 //  This file contains both code to deal with invoking "external" functions, but
4 //  also contains code that implements "exported" external functions.
5 //
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
9 //  function call.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "Interpreter.h"
14 #include "llvm/DerivedTypes.h"
15 #include "../test/Libraries/libinstr/tracelib.h"
16 #include <map>
17 #include <dlfcn.h>
18 #include <iostream>
19 #include <link.h>
20 #include <math.h>
21 #include <stdio.h>
22 using std::vector;
23 using std::cout;
24
25
26 typedef GenericValue (*ExFunc)(FunctionType *, const vector<GenericValue> &);
27 static std::map<const Function *, ExFunc> Functions;
28 static std::map<std::string, ExFunc> FuncNames;
29
30 static Interpreter *TheInterpreter;
31
32 // getCurrentExecutablePath() - Return the directory that the lli executable
33 // lives in.
34 //
35 std::string Interpreter::getCurrentExecutablePath() const {
36   Dl_info Info;
37   if (dladdr(&TheInterpreter, &Info) == 0) return "";
38   
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...
43
44   return LinkAddr;
45 }
46
47
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';
67   default: return 'U';
68   }
69 }
70
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();
79
80   //cout << "Tried: '" << ExtName << "'\n";
81   ExFunc FnPtr = FuncNames[ExtName];
82   if (FnPtr == 0)
83     FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ExtName.c_str());
84   if (FnPtr == 0)
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());
88   if (FnPtr != 0)
89     Functions.insert(std::make_pair(M, FnPtr));  // Cache for later
90   return FnPtr;
91 }
92
93 GenericValue Interpreter::callExternalMethod(Function *M,
94                                          const vector<GenericValue> &ArgVals) {
95   TheInterpreter = this;
96
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;
101   if (Fn == 0) {
102     cout << "Tried to execute an unknown external function: "
103          << M->getType()->getDescription() << " " << M->getName() << "\n";
104     return GenericValue();
105   }
106
107   // TODO: FIXME when types are not const!
108   GenericValue Result = Fn(const_cast<FunctionType*>(M->getFunctionType()),
109                            ArgVals);
110   return Result;
111 }
112
113
114 //===----------------------------------------------------------------------===//
115 //  Functions "exported" to the running application...
116 //
117 extern "C" {  // Don't add C++ manglings to llvm mangling :)
118
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();
124 }
125
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!");
129
130   Interpreter::print(M->getParamTypes()[0], ArgVals[0]);
131   return GenericValue();
132 }
133
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!");
137
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);
143     }
144
145   Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);
146   return GenericValue();
147 }
148
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);
154 }
155
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();\
164   }
165
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)
177
178
179 // void "putchar"(sbyte)
180 GenericValue lle_Vb_putchar(FunctionType *M, const vector<GenericValue> &Args) {
181   cout << Args[0].SByteVal;
182   return GenericValue();
183 }
184
185 // int "putchar"(int)
186 GenericValue lle_ii_putchar(FunctionType *M, const vector<GenericValue> &Args) {
187   cout << ((char)Args[0].IntVal) << std::flush;
188   return Args[0];
189 }
190
191 // void "putchar"(ubyte)
192 GenericValue lle_VB_putchar(FunctionType *M, const vector<GenericValue> &Args) {
193   cout << Args[0].SByteVal << std::flush;
194   return Args[0];
195 }
196
197 // void "__main"()
198 GenericValue lle_V___main(FunctionType *M, const vector<GenericValue> &Args) {
199   return GenericValue();
200 }
201
202 // void "exit"(int)
203 GenericValue lle_X_exit(FunctionType *M, const vector<GenericValue> &Args) {
204   TheInterpreter->exitCalled(Args[0]);
205   return GenericValue();
206 }
207
208 // void *malloc(uint)
209 GenericValue lle_X_malloc(FunctionType *M, const vector<GenericValue> &Args) {
210   assert(Args.size() == 1 && "Malloc expects one argument!");
211   GenericValue GV;
212   GV.PointerVal = (PointerTy)malloc(Args[0].UIntVal);
213   return GV;
214 }
215
216 // void free(void *)
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();
221 }
222
223 // int atoi(char *)
224 GenericValue lle_X_atoi(FunctionType *M, const vector<GenericValue> &Args) {
225   assert(Args.size() == 1);
226   GenericValue GV;
227   GV.IntVal = atoi((char*)Args[0].PointerVal);
228   return GV;
229 }
230
231 // double pow(double, double)
232 GenericValue lle_X_pow(FunctionType *M, const vector<GenericValue> &Args) {
233   assert(Args.size() == 2);
234   GenericValue GV;
235   GV.DoubleVal = pow(Args[0].DoubleVal, Args[1].DoubleVal);
236   return GV;
237 }
238
239 // double exp(double)
240 GenericValue lle_X_exp(FunctionType *M, const vector<GenericValue> &Args) {
241   assert(Args.size() == 1);
242   GenericValue GV;
243   GV.DoubleVal = exp(Args[0].DoubleVal);
244   return GV;
245 }
246
247 // double sqrt(double)
248 GenericValue lle_X_sqrt(FunctionType *M, const vector<GenericValue> &Args) {
249   assert(Args.size() == 1);
250   GenericValue GV;
251   GV.DoubleVal = sqrt(Args[0].DoubleVal);
252   return GV;
253 }
254
255 // double log(double)
256 GenericValue lle_X_log(FunctionType *M, const vector<GenericValue> &Args) {
257   assert(Args.size() == 1);
258   GenericValue GV;
259   GV.DoubleVal = log(Args[0].DoubleVal);
260   return GV;
261 }
262
263 // double floor(double)
264 GenericValue lle_X_floor(FunctionType *M, const vector<GenericValue> &Args) {
265   assert(Args.size() == 1);
266   GenericValue GV;
267   GV.DoubleVal = floor(Args[0].DoubleVal);
268   return GV;
269 }
270
271 // double drand48()
272 GenericValue lle_X_drand48(FunctionType *M, const vector<GenericValue> &Args) {
273   assert(Args.size() == 0);
274   GenericValue GV;
275   GV.DoubleVal = drand48();
276   return GV;
277 }
278
279 // long lrand48()
280 GenericValue lle_X_lrand48(FunctionType *M, const vector<GenericValue> &Args) {
281   assert(Args.size() == 0);
282   GenericValue GV;
283   GV.IntVal = lrand48();
284   return GV;
285 }
286
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();
292 }
293
294 // void srand(uint)
295 GenericValue lle_X_srand(FunctionType *M, const vector<GenericValue> &Args) {
296   assert(Args.size() == 1);
297   srand(Args[0].UIntVal);
298   return GenericValue();
299 }
300
301 // int sprintf(sbyte *, sbyte *, ...) - a very rough implementation to make
302 // output useful.
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;
306   unsigned ArgNo = 2;
307
308   // printf should return # chars printed.  This is completely incorrect, but
309   // close enough for now.
310   GenericValue GV; GV.IntVal = strlen(FmtStr);
311   while (1) {
312     switch (*FmtStr) {
313     case 0: return GV;             // Null terminator...
314     default:                       // Normal nonspecial character
315       sprintf(OutputBuffer++, "%c", *FmtStr++);
316       break;
317     case '\\': {                   // Handle escape codes
318       sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
319       FmtStr += 2; OutputBuffer += 2;
320       break;
321     }
322     case '%': {                    // Handle format specifiers
323       char FmtBuf[100] = "", Buffer[1000] = "";
324       char *FB = FmtBuf;
325       *FB++ = *FmtStr++;
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++;
334       }
335       *FB = 0;
336       
337       switch (Last) {
338       case '%':
339         sprintf(Buffer, FmtBuf); break;
340       case 'c':
341         sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal); break;
342       case 'd': case 'i':
343       case 'u': case 'o':
344       case 'x': case 'X':
345         if (HowLong == 2)
346           sprintf(Buffer, FmtBuf, Args[ArgNo++].ULongVal);
347         else
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;
351       case 'p':
352         sprintf(Buffer, FmtBuf, (void*)Args[ArgNo++].PointerVal); break;
353       case 's': 
354         sprintf(Buffer, FmtBuf, (char*)Args[ArgNo++].PointerVal); break;
355       default:  cout << "<unknown printf code '" << *FmtStr << "'!>";
356         ArgNo++; break;
357       }
358       strcpy(OutputBuffer, Buffer);
359       OutputBuffer += strlen(Buffer);
360       }
361       break;
362     }
363   }
364 }
365
366 // int printf(sbyte *, ...) - a very rough implementation to make output useful.
367 GenericValue lle_X_printf(FunctionType *M, const vector<GenericValue> &Args) {
368   char Buffer[10000];
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);
374   cout << Buffer;
375   return GV;
376 }
377
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!");
381
382   const char *Args[10];
383   for (unsigned i = 0; i < args.size(); ++i)
384     Args[i] = (const char*)args[i].PointerVal;
385
386   GenericValue GV;
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]);
389   return GV;
390 }
391
392
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();
397   return GV;
398 }
399
400 //===----------------------------------------------------------------------===//
401 // IO Functions...
402 //===----------------------------------------------------------------------===//
403
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);
407   GenericValue GV;
408
409   GV.PointerVal = (PointerTy)fopen((const char *)Args[0].PointerVal,
410                                    (const char *)Args[1].PointerVal);
411   return GV;
412 }
413
414 // int fclose(FILE *F);
415 GenericValue lle_X_fclose(FunctionType *M, const vector<GenericValue> &Args) {
416   assert(Args.size() == 1);
417   GenericValue GV;
418
419   GV.IntVal = fclose((FILE *)Args[0].PointerVal);
420   return GV;
421 }
422
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);
426   GenericValue GV;
427
428   GV.UIntVal = fread((void*)Args[0].PointerVal, Args[1].UIntVal,
429                      Args[2].UIntVal, (FILE*)Args[3].PointerVal);
430   return GV;
431 }
432
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);
436   GenericValue GV;
437
438   GV.UIntVal = fwrite((void*)Args[0].PointerVal, Args[1].UIntVal,
439                       Args[2].UIntVal, (FILE*)Args[3].PointerVal);
440   return GV;
441 }
442
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);
446   GenericValue GV;
447
448   GV.PointerVal = (PointerTy)fgets((char*)Args[0].PointerVal, Args[1].IntVal,
449                                    (FILE*)Args[2].PointerVal);
450   return GV;
451 }
452
453 // int fflush(FILE *stream);
454 GenericValue lle_X_fflush(FunctionType *M, const vector<GenericValue> &Args) {
455   assert(Args.size() == 1);
456   GenericValue GV;
457
458   GV.IntVal = fflush((FILE*)Args[0].PointerVal);
459   return GV;
460 }
461
462 // unsigned int HashPointerToSeqNum(char* ptr)
463 GenericValue lle_X_HashPointerToSeqNum(FunctionType *M, const vector<GenericValue> &Args) {
464   assert(Args.size() == 1);
465   GenericValue GV;
466   
467   GV.UIntVal = HashPointerToSeqNum((char*) Args[0].PointerVal);
468   return GV;
469 }
470
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();
476 }
477
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();
483 }
484
485 // void PushPointerSet();
486 GenericValue lle_X_PushPointerSet(FunctionType *M, const vector<GenericValue> &Args) {
487   assert(Args.size() == 0);
488   PushPointerSet();
489   return GenericValue();
490 }
491
492 // void ReleaseRecordedPointers();
493 GenericValue lle_X_ReleasePointersPopSet(FunctionType *M, const vector<GenericValue> &Args) {
494   assert(Args.size() == 0);
495   ReleasePointersPopSet();
496   return GenericValue();
497 }
498
499 } // End extern "C"
500
501
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;
550 }