Implement sqrt, implement printf better, simpler.
[oota-llvm.git] / lib / ExecutionEngine / Interpreter / ExternalFunctions.cpp
1 //===-- ExternalMethods.cpp - Implement External Methods ------------------===//
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 <link.h>
17 #include <math.h>
18 #include <stdio.h>
19
20 typedef GenericValue (*ExFunc)(MethodType *, const vector<GenericValue> &);
21 static map<const Method *, ExFunc> Functions;
22 static map<string, ExFunc> FuncNames;
23
24 static Interpreter *TheInterpreter;
25
26 // getCurrentExecutablePath() - Return the directory that the lli executable
27 // lives in.
28 //
29 string Interpreter::getCurrentExecutablePath() const {
30   Dl_info Info;
31   if (dladdr(&TheInterpreter, &Info) == 0) return "";
32   
33   string LinkAddr(Info.dli_fname);
34   unsigned SlashPos = LinkAddr.rfind('/');
35   if (SlashPos != string::npos)
36     LinkAddr.resize(SlashPos);    // Trim the executable name off...
37
38   return LinkAddr;
39 }
40
41
42 static char getTypeID(const Type *Ty) {
43   switch (Ty->getPrimitiveID()) {
44   case Type::VoidTyID:    return 'V';
45   case Type::BoolTyID:    return 'o';
46   case Type::UByteTyID:   return 'B';
47   case Type::SByteTyID:   return 'b';
48   case Type::UShortTyID:  return 'S';
49   case Type::ShortTyID:   return 's';
50   case Type::UIntTyID:    return 'I';
51   case Type::IntTyID:     return 'i';
52   case Type::ULongTyID:   return 'L';
53   case Type::LongTyID:    return 'l';
54   case Type::FloatTyID:   return 'F';
55   case Type::DoubleTyID:  return 'D';
56   case Type::PointerTyID: return 'P';
57   case Type::MethodTyID:  return 'M';
58   case Type::StructTyID:  return 'T';
59   case Type::ArrayTyID:   return 'A';
60   case Type::OpaqueTyID:  return 'O';
61   default: return 'U';
62   }
63 }
64
65 static ExFunc lookupMethod(const Method *M) {
66   // Function not found, look it up... start by figuring out what the
67   // composite function name should be.
68   string ExtName = "lle_";
69   const MethodType *MT = M->getMethodType();
70   for (unsigned i = 0; const Type *Ty = MT->getContainedType(i); ++i)
71     ExtName += getTypeID(Ty);
72   ExtName += "_" + M->getName();
73
74   //cout << "Tried: '" << ExtName << "'\n";
75   ExFunc FnPtr = FuncNames[ExtName];
76   if (FnPtr == 0)
77     FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ExtName.c_str());
78   if (FnPtr == 0)
79     FnPtr = FuncNames["lle_X_"+M->getName()];
80   if (FnPtr == 0)  // Try calling a generic function... if it exists...
81     FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ("lle_X_"+M->getName()).c_str());
82   if (FnPtr != 0)
83     Functions.insert(make_pair(M, FnPtr));  // Cache for later
84   return FnPtr;
85 }
86
87 GenericValue Interpreter::callExternalMethod(Method *M,
88                                          const vector<GenericValue> &ArgVals) {
89   TheInterpreter = this;
90
91   // Do a lookup to see if the method is in our cache... this should just be a
92   // defered annotation!
93   map<const Method *, ExFunc>::iterator FI = Functions.find(M);
94   ExFunc Fn = (FI == Functions.end()) ? lookupMethod(M) : FI->second;
95   if (Fn == 0) {
96     cout << "Tried to execute an unknown external method: "
97          << M->getType()->getDescription() << " " << M->getName() << endl;
98     return GenericValue();
99   }
100
101   // TODO: FIXME when types are not const!
102   GenericValue Result = Fn(const_cast<MethodType*>(M->getMethodType()),ArgVals);
103   return Result;
104 }
105
106
107 //===----------------------------------------------------------------------===//
108 //  Methods "exported" to the running application...
109 //
110 extern "C" {  // Don't add C++ manglings to llvm mangling :)
111
112 // Implement void printstr([ubyte {x N}] *)
113 GenericValue lle_VP_printstr(MethodType *M, const vector<GenericValue> &ArgVal){
114   assert(ArgVal.size() == 1 && "printstr only takes one argument!");
115   cout << (char*)ArgVal[0].PointerVal;
116   return GenericValue();
117 }
118
119 // Implement 'void print(X)' for every type...
120 GenericValue lle_X_print(MethodType *M, const vector<GenericValue> &ArgVals) {
121   assert(ArgVals.size() == 1 && "generic print only takes one argument!");
122
123   Interpreter::print(M->getParamTypes()[0], ArgVals[0]);
124   return GenericValue();
125 }
126
127 // Implement 'void printVal(X)' for every type...
128 GenericValue lle_X_printVal(MethodType *M, const vector<GenericValue> &ArgVal) {
129   assert(ArgVal.size() == 1 && "generic print only takes one argument!");
130
131   // Specialize print([ubyte {x N} ] *) and print(sbyte *)
132   if (PointerType *PTy = dyn_cast<PointerType>(M->getParamTypes()[0].get()))
133     if (PTy->getValueType() == Type::SByteTy ||
134         isa<ArrayType>(PTy->getValueType())) {
135       return lle_VP_printstr(M, ArgVal);
136     }
137
138   Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);
139   return GenericValue();
140 }
141
142 // Implement 'void printString(X)'
143 // Argument must be [ubyte {x N} ] * or sbyte *
144 GenericValue lle_X_printString(MethodType *M, const vector<GenericValue> &ArgVal) {
145   assert(ArgVal.size() == 1 && "generic print only takes one argument!");
146   return lle_VP_printstr(M, ArgVal);
147 }
148
149 // Implement 'void print<TYPE>(X)' for each primitive type or pointer type
150 #define PRINT_TYPE_FUNC(TYPENAME,TYPEID) \
151   GenericValue lle_X_print##TYPENAME(MethodType *M,\
152                                      const vector<GenericValue> &ArgVal) {\
153     assert(ArgVal.size() == 1 && "generic print only takes one argument!");\
154     assert(M->getParamTypes()[0].get()->getPrimitiveID() == Type::##TYPEID);\
155     Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);\
156     return GenericValue();\
157   }
158
159 PRINT_TYPE_FUNC(SByte,   SByteTyID)
160 PRINT_TYPE_FUNC(UByte,   UByteTyID)
161 PRINT_TYPE_FUNC(Short,   ShortTyID)
162 PRINT_TYPE_FUNC(UShort,  UShortTyID)
163 PRINT_TYPE_FUNC(Int,     IntTyID)
164 PRINT_TYPE_FUNC(UInt,    UIntTyID)
165 PRINT_TYPE_FUNC(Long,    LongTyID)
166 PRINT_TYPE_FUNC(ULong,   ULongTyID)
167 PRINT_TYPE_FUNC(Float,   FloatTyID)
168 PRINT_TYPE_FUNC(Double,  DoubleTyID)
169 PRINT_TYPE_FUNC(Pointer, PointerTyID)
170
171
172 // void "putchar"(sbyte)
173 GenericValue lle_Vb_putchar(MethodType *M, const vector<GenericValue> &Args) {
174   cout << Args[0].SByteVal;
175   return GenericValue();
176 }
177
178 // int "putchar"(int)
179 GenericValue lle_ii_putchar(MethodType *M, const vector<GenericValue> &Args) {
180   cout << ((char)Args[0].IntVal) << flush;
181   return Args[0];
182 }
183
184 // void "putchar"(ubyte)
185 GenericValue lle_VB_putchar(MethodType *M, const vector<GenericValue> &Args) {
186   cout << Args[0].SByteVal << flush;
187   return Args[0];
188 }
189
190 // void "__main"()
191 GenericValue lle_V___main(MethodType *M, const vector<GenericValue> &Args) {
192   return GenericValue();
193 }
194
195 // void "exit"(int)
196 GenericValue lle_X_exit(MethodType *M, const vector<GenericValue> &Args) {
197   TheInterpreter->exitCalled(Args[0]);
198   return GenericValue();
199 }
200
201 // void *malloc(uint)
202 GenericValue lle_X_malloc(MethodType *M, const vector<GenericValue> &Args) {
203   assert(Args.size() == 1 && "Malloc expects one argument!");
204   GenericValue GV;
205   GV.PointerVal = (uint64_t)malloc(Args[0].UIntVal);
206   return GV;
207 }
208
209 // void free(void *)
210 GenericValue lle_X_free(MethodType *M, const vector<GenericValue> &Args) {
211   assert(Args.size() == 1);
212   free((void*)Args[0].PointerVal);
213   return GenericValue();
214 }
215
216 // double pow(double, double)
217 GenericValue lle_X_pow(MethodType *M, const vector<GenericValue> &Args) {
218   assert(Args.size() == 2);
219   GenericValue GV;
220   GV.DoubleVal = pow(Args[0].DoubleVal, Args[1].DoubleVal);
221   return GV;
222 }
223
224 // double sqrt(double)
225 GenericValue lle_X_sqrt(MethodType *M, const vector<GenericValue> &Args) {
226   assert(Args.size() == 1);
227   GenericValue GV;
228   GV.DoubleVal = sqrt(Args[0].DoubleVal);
229   return GV;
230 }
231
232 // int printf(sbyte *, ...) - a very rough implementation to make output useful.
233 GenericValue lle_X_printf(MethodType *M, const vector<GenericValue> &Args) {
234   const char *FmtStr = (const char *)Args[0].PointerVal;
235   unsigned ArgNo = 1;
236
237   // printf should return # chars printed.  This is completely incorrect, but
238   // close enough for now.
239   GenericValue GV; GV.IntVal = strlen(FmtStr);
240   while (1) {
241     switch (*FmtStr) {
242     case 0: return GV;             // Null terminator...
243     default:                       // Normal nonspecial character
244       cout << *FmtStr++;
245       break;
246     case '\\': {                   // Handle escape codes
247       char Buffer[3];
248       Buffer[0] = *FmtStr++;
249       Buffer[1] = *FmtStr++;
250       Buffer[2] = 0;
251       cout << Buffer;
252       break;
253     }
254     case '%': {                    // Handle format specifiers
255       bool isLong = false;
256       ++FmtStr;
257       if (*FmtStr == 'l') {
258         isLong = true;
259         FmtStr++;
260       }
261
262       if (*FmtStr == '%') 
263         cout << *FmtStr;                  // %%
264       else {
265         char Fmt[] = "%d", Buffer[1000] = "";
266         Fmt[1] = *FmtStr;
267
268         switch (*FmtStr) {
269         case 'c':
270           sprintf(Buffer, Fmt, Args[ArgNo++].SByteVal); break;
271         case 'd': case 'i':
272         case 'u': case 'o':
273         case 'x': case 'X':
274           sprintf(Buffer, Fmt, Args[ArgNo++].IntVal); break;
275         case 'e': case 'E': case 'g': case 'G': case 'f':
276           sprintf(Buffer, Fmt, Args[ArgNo++].DoubleVal); break;
277         case 's': cout << (char*)Args[ArgNo++].PointerVal; break;     // %s
278         default:  cout << "<unknown printf code '" << *FmtStr << "'!>";
279           ArgNo++; break;
280         }
281         cout << Buffer;
282       }
283       ++FmtStr;
284       break;
285     }
286     }
287   }
288 }
289
290 } // End extern "C"
291
292
293 void Interpreter::initializeExternalMethods() {
294   FuncNames["lle_VP_printstr"] = lle_VP_printstr;
295   FuncNames["lle_X_print"] = lle_X_print;
296   FuncNames["lle_X_printVal"] = lle_X_printVal;
297   FuncNames["lle_X_printString"] = lle_X_printString;
298   FuncNames["lle_X_printUByte"] = lle_X_printUByte;
299   FuncNames["lle_X_printSByte"] = lle_X_printSByte;
300   FuncNames["lle_X_printUShort"] = lle_X_printUShort;
301   FuncNames["lle_X_printShort"] = lle_X_printShort;
302   FuncNames["lle_X_printInt"] = lle_X_printInt;
303   FuncNames["lle_X_printUInt"] = lle_X_printUInt;
304   FuncNames["lle_X_printLong"] = lle_X_printLong;
305   FuncNames["lle_X_printULong"] = lle_X_printULong;
306   FuncNames["lle_X_printFloat"] = lle_X_printFloat;
307   FuncNames["lle_X_printDouble"] = lle_X_printDouble;
308   FuncNames["lle_X_printPointer"] = lle_X_printPointer;
309   FuncNames["lle_Vb_putchar"]     = lle_Vb_putchar;
310   FuncNames["lle_ii_putchar"]     = lle_ii_putchar;
311   FuncNames["lle_VB_putchar"]     = lle_VB_putchar;
312   FuncNames["lle_V___main"]       = lle_V___main;
313   FuncNames["lle_X_exit"]         = lle_X_exit;
314   FuncNames["lle_X_malloc"]       = lle_X_malloc;
315   FuncNames["lle_X_free"]         = lle_X_free;
316   FuncNames["lle_X_pow"]          = lle_X_pow;
317   FuncNames["lle_X_sqrt"]         = lle_X_sqrt;
318   FuncNames["lle_X_printf"]       = lle_X_printf;
319 }