1a28e46d8d08b43938e8fad437c81d1fbb9b87fc
[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 "ExecutionAnnotations.h"
15 #include "llvm/Module.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/SymbolTable.h"
18 #include "llvm/Target/TargetData.h"
19 #include <map>
20 #include "Config/dlfcn.h"
21 #include "Config/link.h"
22 #include <cmath>
23 #include "Config/stdio.h"
24 using std::vector;
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 static char getTypeID(const Type *Ty) {
33   switch (Ty->getPrimitiveID()) {
34   case Type::VoidTyID:    return 'V';
35   case Type::BoolTyID:    return 'o';
36   case Type::UByteTyID:   return 'B';
37   case Type::SByteTyID:   return 'b';
38   case Type::UShortTyID:  return 'S';
39   case Type::ShortTyID:   return 's';
40   case Type::UIntTyID:    return 'I';
41   case Type::IntTyID:     return 'i';
42   case Type::ULongTyID:   return 'L';
43   case Type::LongTyID:    return 'l';
44   case Type::FloatTyID:   return 'F';
45   case Type::DoubleTyID:  return 'D';
46   case Type::PointerTyID: return 'P';
47   case Type::FunctionTyID:  return 'M';
48   case Type::StructTyID:  return 'T';
49   case Type::ArrayTyID:   return 'A';
50   case Type::OpaqueTyID:  return 'O';
51   default: return 'U';
52   }
53 }
54
55 static ExFunc lookupFunction(const Function *M) {
56   // Function not found, look it up... start by figuring out what the
57   // composite function name should be.
58   std::string ExtName = "lle_";
59   const FunctionType *MT = M->getFunctionType();
60   for (unsigned i = 0; const Type *Ty = MT->getContainedType(i); ++i)
61     ExtName += getTypeID(Ty);
62   ExtName += "_" + M->getName();
63
64   //std::cout << "Tried: '" << ExtName << "'\n";
65   ExFunc FnPtr = FuncNames[ExtName];
66   if (FnPtr == 0)
67     FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ExtName.c_str());
68   if (FnPtr == 0)
69     FnPtr = FuncNames["lle_X_"+M->getName()];
70   if (FnPtr == 0)  // Try calling a generic function... if it exists...
71     FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ("lle_X_"+M->getName()).c_str());
72   if (FnPtr != 0)
73     Functions.insert(std::make_pair(M, FnPtr));  // Cache for later
74   return FnPtr;
75 }
76
77 GenericValue Interpreter::callExternalFunction(Function *M,
78                                      const std::vector<GenericValue> &ArgVals) {
79   TheInterpreter = this;
80
81   // Do a lookup to see if the function is in our cache... this should just be a
82   // defered annotation!
83   std::map<const Function *, ExFunc>::iterator FI = Functions.find(M);
84   ExFunc Fn = (FI == Functions.end()) ? lookupFunction(M) : FI->second;
85   if (Fn == 0) {
86     std::cout << "Tried to execute an unknown external function: "
87               << M->getType()->getDescription() << " " << M->getName() << "\n";
88     return GenericValue();
89   }
90
91   // TODO: FIXME when types are not const!
92   GenericValue Result = Fn(const_cast<FunctionType*>(M->getFunctionType()),
93                            ArgVals);
94   return Result;
95 }
96
97
98 //===----------------------------------------------------------------------===//
99 //  Functions "exported" to the running application...
100 //
101 extern "C" {  // Don't add C++ manglings to llvm mangling :)
102
103 // void putchar(sbyte)
104 GenericValue lle_Vb_putchar(FunctionType *M, const vector<GenericValue> &Args) {
105   std::cout << Args[0].SByteVal;
106   return GenericValue();
107 }
108
109 // int putchar(int)
110 GenericValue lle_ii_putchar(FunctionType *M, const vector<GenericValue> &Args) {
111   std::cout << ((char)Args[0].IntVal) << std::flush;
112   return Args[0];
113 }
114
115 // void putchar(ubyte)
116 GenericValue lle_VB_putchar(FunctionType *M, const vector<GenericValue> &Args) {
117   std::cout << Args[0].SByteVal << std::flush;
118   return Args[0];
119 }
120
121 // void atexit(Function*)
122 GenericValue lle_X_atexit(FunctionType *M, const vector<GenericValue> &Args) {
123   assert(Args.size() == 1);
124   TheInterpreter->addAtExitHandler((Function*)GVTOP(Args[0]));
125   GenericValue GV;
126   GV.IntVal = 0;
127   return GV;
128 }
129
130 // void exit(int)
131 GenericValue lle_X_exit(FunctionType *M, const vector<GenericValue> &Args) {
132   TheInterpreter->exitCalled(Args[0]);
133   return GenericValue();
134 }
135
136 // void abort(void)
137 GenericValue lle_X_abort(FunctionType *M, const vector<GenericValue> &Args) {
138   std::cerr << "***PROGRAM ABORTED***!\n";
139   GenericValue GV;
140   GV.IntVal = 1;
141   TheInterpreter->exitCalled(GV);
142   return GenericValue();
143 }
144
145 // void *malloc(uint)
146 GenericValue lle_X_malloc(FunctionType *M, const vector<GenericValue> &Args) {
147   assert(Args.size() == 1 && "Malloc expects one argument!");
148   return PTOGV(malloc(Args[0].UIntVal));
149 }
150
151 // void *calloc(uint, uint)
152 GenericValue lle_X_calloc(FunctionType *M, const vector<GenericValue> &Args) {
153   assert(Args.size() == 2 && "calloc expects two arguments!");
154   return PTOGV(calloc(Args[0].UIntVal, Args[1].UIntVal));
155 }
156
157 // void free(void *)
158 GenericValue lle_X_free(FunctionType *M, const vector<GenericValue> &Args) {
159   assert(Args.size() == 1);
160   free(GVTOP(Args[0]));
161   return GenericValue();
162 }
163
164 // int atoi(char *)
165 GenericValue lle_X_atoi(FunctionType *M, const vector<GenericValue> &Args) {
166   assert(Args.size() == 1);
167   GenericValue GV;
168   GV.IntVal = atoi((char*)GVTOP(Args[0]));
169   return GV;
170 }
171
172 // double pow(double, double)
173 GenericValue lle_X_pow(FunctionType *M, const vector<GenericValue> &Args) {
174   assert(Args.size() == 2);
175   GenericValue GV;
176   GV.DoubleVal = pow(Args[0].DoubleVal, Args[1].DoubleVal);
177   return GV;
178 }
179
180 // double exp(double)
181 GenericValue lle_X_exp(FunctionType *M, const vector<GenericValue> &Args) {
182   assert(Args.size() == 1);
183   GenericValue GV;
184   GV.DoubleVal = exp(Args[0].DoubleVal);
185   return GV;
186 }
187
188 // double sqrt(double)
189 GenericValue lle_X_sqrt(FunctionType *M, const vector<GenericValue> &Args) {
190   assert(Args.size() == 1);
191   GenericValue GV;
192   GV.DoubleVal = sqrt(Args[0].DoubleVal);
193   return GV;
194 }
195
196 // double log(double)
197 GenericValue lle_X_log(FunctionType *M, const vector<GenericValue> &Args) {
198   assert(Args.size() == 1);
199   GenericValue GV;
200   GV.DoubleVal = log(Args[0].DoubleVal);
201   return GV;
202 }
203
204 // double floor(double)
205 GenericValue lle_X_floor(FunctionType *M, const vector<GenericValue> &Args) {
206   assert(Args.size() == 1);
207   GenericValue GV;
208   GV.DoubleVal = floor(Args[0].DoubleVal);
209   return GV;
210 }
211
212 // double drand48()
213 GenericValue lle_X_drand48(FunctionType *M, const vector<GenericValue> &Args) {
214   assert(Args.size() == 0);
215   GenericValue GV;
216   GV.DoubleVal = drand48();
217   return GV;
218 }
219
220 // long lrand48()
221 GenericValue lle_X_lrand48(FunctionType *M, const vector<GenericValue> &Args) {
222   assert(Args.size() == 0);
223   GenericValue GV;
224   GV.IntVal = lrand48();
225   return GV;
226 }
227
228 // void srand48(long)
229 GenericValue lle_X_srand48(FunctionType *M, const vector<GenericValue> &Args) {
230   assert(Args.size() == 1);
231   srand48(Args[0].IntVal);
232   return GenericValue();
233 }
234
235 // void srand(uint)
236 GenericValue lle_X_srand(FunctionType *M, const vector<GenericValue> &Args) {
237   assert(Args.size() == 1);
238   srand(Args[0].UIntVal);
239   return GenericValue();
240 }
241
242 // int puts(const char*)
243 GenericValue lle_X_puts(FunctionType *M, const vector<GenericValue> &Args) {
244   assert(Args.size() == 1);
245   GenericValue GV;
246   GV.IntVal = puts((char*)GVTOP(Args[0]));
247   return GV;
248 }
249
250 // int sprintf(sbyte *, sbyte *, ...) - a very rough implementation to make
251 // output useful.
252 GenericValue lle_X_sprintf(FunctionType *M, const vector<GenericValue> &Args) {
253   char *OutputBuffer = (char *)GVTOP(Args[0]);
254   const char *FmtStr = (const char *)GVTOP(Args[1]);
255   unsigned ArgNo = 2;
256
257   // printf should return # chars printed.  This is completely incorrect, but
258   // close enough for now.
259   GenericValue GV; GV.IntVal = strlen(FmtStr);
260   while (1) {
261     switch (*FmtStr) {
262     case 0: return GV;             // Null terminator...
263     default:                       // Normal nonspecial character
264       sprintf(OutputBuffer++, "%c", *FmtStr++);
265       break;
266     case '\\': {                   // Handle escape codes
267       sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
268       FmtStr += 2; OutputBuffer += 2;
269       break;
270     }
271     case '%': {                    // Handle format specifiers
272       char FmtBuf[100] = "", Buffer[1000] = "";
273       char *FB = FmtBuf;
274       *FB++ = *FmtStr++;
275       char Last = *FB++ = *FmtStr++;
276       unsigned HowLong = 0;
277       while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
278              Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
279              Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
280              Last != 'p' && Last != 's' && Last != '%') {
281         if (Last == 'l' || Last == 'L') HowLong++;  // Keep track of l's
282         Last = *FB++ = *FmtStr++;
283       }
284       *FB = 0;
285       
286       switch (Last) {
287       case '%':
288         sprintf(Buffer, FmtBuf); break;
289       case 'c':
290         sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal); break;
291       case 'd': case 'i':
292       case 'u': case 'o':
293       case 'x': case 'X':
294         if (HowLong >= 1) {
295           if (HowLong == 1 &&
296               TheInterpreter->getModule().getPointerSize()==Module::Pointer64 &&
297               sizeof(long) < sizeof(long long)) {
298             // Make sure we use %lld with a 64 bit argument because we might be
299             // compiling LLI on a 32 bit compiler.
300             unsigned Size = strlen(FmtBuf);
301             FmtBuf[Size] = FmtBuf[Size-1];
302             FmtBuf[Size+1] = 0;
303             FmtBuf[Size-1] = 'l';
304           }
305           sprintf(Buffer, FmtBuf, Args[ArgNo++].ULongVal);
306         } else
307           sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal); break;
308       case 'e': case 'E': case 'g': case 'G': case 'f':
309         sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
310       case 'p':
311         sprintf(Buffer, FmtBuf, (void*)GVTOP(Args[ArgNo++])); break;
312       case 's': 
313         sprintf(Buffer, FmtBuf, (char*)GVTOP(Args[ArgNo++])); break;
314       default:  std::cout << "<unknown printf code '" << *FmtStr << "'!>";
315         ArgNo++; break;
316       }
317       strcpy(OutputBuffer, Buffer);
318       OutputBuffer += strlen(Buffer);
319       }
320       break;
321     }
322   }
323 }
324
325 // int printf(sbyte *, ...) - a very rough implementation to make output useful.
326 GenericValue lle_X_printf(FunctionType *M, const vector<GenericValue> &Args) {
327   char Buffer[10000];
328   vector<GenericValue> NewArgs;
329   NewArgs.push_back(PTOGV(Buffer));
330   NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
331   GenericValue GV = lle_X_sprintf(M, NewArgs);
332   std::cout << Buffer;
333   return GV;
334 }
335
336 static void ByteswapSCANFResults(const char *Fmt, void *Arg0, void *Arg1,
337                                  void *Arg2, void *Arg3, void *Arg4, void *Arg5,
338                                  void *Arg6, void *Arg7, void *Arg8) {
339   void *Args[] = { Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, 0 };
340
341   // Loop over the format string, munging read values as appropriate (performs
342   // byteswaps as necessary).
343   unsigned ArgNo = 0;
344   while (*Fmt) {
345     if (*Fmt++ == '%') {
346       // Read any flag characters that may be present...
347       bool Suppress = false;
348       bool Half = false;
349       bool Long = false;
350       bool LongLong = false;  // long long or long double
351
352       while (1) {
353         switch (*Fmt++) {
354         case '*': Suppress = true; break;
355         case 'a': /*Allocate = true;*/ break;  // We don't need to track this
356         case 'h': Half = true; break;
357         case 'l': Long = true; break;
358         case 'q':
359         case 'L': LongLong = true; break;
360         default:
361           if (Fmt[-1] > '9' || Fmt[-1] < '0')   // Ignore field width specs
362             goto Out;
363         }
364       }
365     Out:
366
367       // Read the conversion character
368       if (!Suppress && Fmt[-1] != '%') { // Nothing to do?
369         unsigned Size = 0;
370         const Type *Ty = 0;
371
372         switch (Fmt[-1]) {
373         case 'i': case 'o': case 'u': case 'x': case 'X': case 'n': case 'p':
374         case 'd':
375           if (Long || LongLong) {
376             Size = 8; Ty = Type::ULongTy;
377           } else if (Half) {
378             Size = 4; Ty = Type::UShortTy;
379           } else {
380             Size = 4; Ty = Type::UIntTy;
381           }
382           break;
383
384         case 'e': case 'g': case 'E':
385         case 'f':
386           if (Long || LongLong) {
387             Size = 8; Ty = Type::DoubleTy;
388           } else {
389             Size = 4; Ty = Type::FloatTy;
390           }
391           break;
392
393         case 's': case 'c': case '[':  // No byteswap needed
394           Size = 1;
395           Ty = Type::SByteTy;
396           break;
397
398         default: break;
399         }
400
401         if (Size) {
402           GenericValue GV;
403           void *Arg = Args[ArgNo++];
404           memcpy(&GV, Arg, Size);
405           TheInterpreter->StoreValueToMemory(GV, (GenericValue*)Arg, Ty);
406         }
407       }
408     }
409   }
410 }
411
412 // int sscanf(const char *format, ...);
413 GenericValue lle_X_sscanf(FunctionType *M, const vector<GenericValue> &args) {
414   assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
415
416   char *Args[10];
417   for (unsigned i = 0; i < args.size(); ++i)
418     Args[i] = (char*)GVTOP(args[i]);
419
420   GenericValue GV;
421   GV.IntVal = sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
422                      Args[5], Args[6], Args[7], Args[8], Args[9]);
423   ByteswapSCANFResults(Args[1], Args[2], Args[3], Args[4],
424                        Args[5], Args[6], Args[7], Args[8], Args[9], 0);
425   return GV;
426 }
427
428 // int scanf(const char *format, ...);
429 GenericValue lle_X_scanf(FunctionType *M, const vector<GenericValue> &args) {
430   assert(args.size() < 10 && "Only handle up to 10 args to scanf right now!");
431
432   char *Args[10];
433   for (unsigned i = 0; i < args.size(); ++i)
434     Args[i] = (char*)GVTOP(args[i]);
435
436   GenericValue GV;
437   GV.IntVal = scanf(Args[0], Args[1], Args[2], Args[3], Args[4],
438                     Args[5], Args[6], Args[7], Args[8], Args[9]);
439   ByteswapSCANFResults(Args[0], Args[1], Args[2], Args[3], Args[4],
440                        Args[5], Args[6], Args[7], Args[8], Args[9]);
441   return GV;
442 }
443
444
445 // int clock(void) - Profiling implementation
446 GenericValue lle_i_clock(FunctionType *M, const vector<GenericValue> &Args) {
447   extern int clock(void);
448   GenericValue GV; GV.IntVal = clock();
449   return GV;
450 }
451
452
453 //===----------------------------------------------------------------------===//
454 // String Functions...
455 //===----------------------------------------------------------------------===//
456
457 // int strcmp(const char *S1, const char *S2);
458 GenericValue lle_X_strcmp(FunctionType *M, const vector<GenericValue> &Args) {
459   assert(Args.size() == 2);
460   GenericValue Ret;
461   Ret.IntVal = strcmp((char*)GVTOP(Args[0]), (char*)GVTOP(Args[1]));
462   return Ret;
463 }
464
465 // char *strcat(char *Dest, const char *src);
466 GenericValue lle_X_strcat(FunctionType *M, const vector<GenericValue> &Args) {
467   assert(Args.size() == 2);
468   return PTOGV(strcat((char*)GVTOP(Args[0]), (char*)GVTOP(Args[1])));
469 }
470
471 // char *strcpy(char *Dest, const char *src);
472 GenericValue lle_X_strcpy(FunctionType *M, const vector<GenericValue> &Args) {
473   assert(Args.size() == 2);
474   return PTOGV(strcpy((char*)GVTOP(Args[0]), (char*)GVTOP(Args[1])));
475 }
476
477 // long strlen(const char *src);
478 GenericValue lle_X_strlen(FunctionType *M, const vector<GenericValue> &Args) {
479   assert(Args.size() == 1);
480   GenericValue Ret;
481   Ret.LongVal = strlen((char*)GVTOP(Args[0]));
482   return Ret;
483 }
484
485 // char *strdup(const char *src);
486 GenericValue lle_X_strdup(FunctionType *M, const vector<GenericValue> &Args) {
487   assert(Args.size() == 1);
488   return PTOGV(strdup((char*)GVTOP(Args[0])));
489 }
490
491 // char *__strdup(const char *src);
492 GenericValue lle_X___strdup(FunctionType *M, const vector<GenericValue> &Args) {
493   assert(Args.size() == 1);
494   return PTOGV(strdup((char*)GVTOP(Args[0])));
495 }
496
497 // void *memset(void *S, int C, size_t N)
498 GenericValue lle_X_memset(FunctionType *M, const vector<GenericValue> &Args) {
499   assert(Args.size() == 3);
500   return PTOGV(memset(GVTOP(Args[0]), Args[1].IntVal, Args[2].UIntVal));
501 }
502
503 // void *memcpy(void *Dest, void *src, size_t Size);
504 GenericValue lle_X_memcpy(FunctionType *M, const vector<GenericValue> &Args) {
505   assert(Args.size() == 3);
506   return PTOGV(memcpy((char*)GVTOP(Args[0]), (char*)GVTOP(Args[1]),
507                       Args[2].UIntVal));
508 }
509
510 //===----------------------------------------------------------------------===//
511 // IO Functions...
512 //===----------------------------------------------------------------------===//
513
514 // getFILE - Turn a pointer in the host address space into a legit pointer in
515 // the interpreter address space.  For the most part, this is an identity
516 // transformation, but if the program refers to stdio, stderr, stdin then they
517 // have pointers that are relative to the __iob array.  If this is the case,
518 // change the FILE into the REAL stdio stream.
519 // 
520 static FILE *getFILE(void *Ptr) {
521   static Module *LastMod = 0;
522   static PointerTy IOBBase = 0;
523   static unsigned FILESize;
524
525   if (LastMod != &TheInterpreter->getModule()) { // Module change or initialize?
526     Module *M = LastMod = &TheInterpreter->getModule();
527
528     // Check to see if the currently loaded module contains an __iob symbol...
529     GlobalVariable *IOB = 0;
530     SymbolTable &ST = M->getSymbolTable();
531     for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I) {
532       SymbolTable::VarMap &M = I->second;
533       for (SymbolTable::VarMap::iterator J = M.begin(), E = M.end();
534            J != E; ++J)
535         if (J->first == "__iob")
536           if ((IOB = dyn_cast<GlobalVariable>(J->second)))
537             break;
538       if (IOB) break;
539     }
540
541 #if 0   /// FIXME!  __iob support for LLI
542     // If we found an __iob symbol now, find out what the actual address it's
543     // held in is...
544     if (IOB) {
545       // Get the address the array lives in...
546       GlobalAddress *Address = 
547         (GlobalAddress*)IOB->getOrCreateAnnotation(GlobalAddressAID);
548       IOBBase = (PointerTy)(GenericValue*)Address->Ptr;
549
550       // Figure out how big each element of the array is...
551       const ArrayType *AT =
552         dyn_cast<ArrayType>(IOB->getType()->getElementType());
553       if (AT)
554         FILESize = TD.getTypeSize(AT->getElementType());
555       else
556         FILESize = 16*8;  // Default size
557     }
558 #endif
559   }
560
561   // Check to see if this is a reference to __iob...
562   if (IOBBase) {
563     unsigned FDNum = ((unsigned long)Ptr-IOBBase)/FILESize;
564     if (FDNum == 0)
565       return stdin;
566     else if (FDNum == 1)
567       return stdout;
568     else if (FDNum == 2)
569       return stderr;
570   }
571
572   return (FILE*)Ptr;
573 }
574
575
576 // FILE *fopen(const char *filename, const char *mode);
577 GenericValue lle_X_fopen(FunctionType *M, const vector<GenericValue> &Args) {
578   assert(Args.size() == 2);
579   return PTOGV(fopen((const char *)GVTOP(Args[0]),
580                      (const char *)GVTOP(Args[1])));
581 }
582
583 // int fclose(FILE *F);
584 GenericValue lle_X_fclose(FunctionType *M, const vector<GenericValue> &Args) {
585   assert(Args.size() == 1);
586   GenericValue GV;
587   GV.IntVal = fclose(getFILE(GVTOP(Args[0])));
588   return GV;
589 }
590
591 // int feof(FILE *stream);
592 GenericValue lle_X_feof(FunctionType *M, const vector<GenericValue> &Args) {
593   assert(Args.size() == 1);
594   GenericValue GV;
595
596   GV.IntVal = feof(getFILE(GVTOP(Args[0])));
597   return GV;
598 }
599
600 // size_t fread(void *ptr, size_t size, size_t nitems, FILE *stream);
601 GenericValue lle_X_fread(FunctionType *M, const vector<GenericValue> &Args) {
602   assert(Args.size() == 4);
603   GenericValue GV;
604
605   GV.UIntVal = fread((void*)GVTOP(Args[0]), Args[1].UIntVal,
606                      Args[2].UIntVal, getFILE(GVTOP(Args[3])));
607   return GV;
608 }
609
610 // size_t fwrite(const void *ptr, size_t size, size_t nitems, FILE *stream);
611 GenericValue lle_X_fwrite(FunctionType *M, const vector<GenericValue> &Args) {
612   assert(Args.size() == 4);
613   GenericValue GV;
614
615   GV.UIntVal = fwrite((void*)GVTOP(Args[0]), Args[1].UIntVal,
616                       Args[2].UIntVal, getFILE(GVTOP(Args[3])));
617   return GV;
618 }
619
620 // char *fgets(char *s, int n, FILE *stream);
621 GenericValue lle_X_fgets(FunctionType *M, const vector<GenericValue> &Args) {
622   assert(Args.size() == 3);
623   return GVTOP(fgets((char*)GVTOP(Args[0]), Args[1].IntVal,
624                      getFILE(GVTOP(Args[2]))));
625 }
626
627 // FILE *freopen(const char *path, const char *mode, FILE *stream);
628 GenericValue lle_X_freopen(FunctionType *M, const vector<GenericValue> &Args) {
629   assert(Args.size() == 3);
630   return PTOGV(freopen((char*)GVTOP(Args[0]), (char*)GVTOP(Args[1]),
631                        getFILE(GVTOP(Args[2]))));
632 }
633
634 // int fflush(FILE *stream);
635 GenericValue lle_X_fflush(FunctionType *M, const vector<GenericValue> &Args) {
636   assert(Args.size() == 1);
637   GenericValue GV;
638   GV.IntVal = fflush(getFILE(GVTOP(Args[0])));
639   return GV;
640 }
641
642 // int getc(FILE *stream);
643 GenericValue lle_X_getc(FunctionType *M, const vector<GenericValue> &Args) {
644   assert(Args.size() == 1);
645   GenericValue GV;
646   GV.IntVal = getc(getFILE(GVTOP(Args[0])));
647   return GV;
648 }
649
650 // int _IO_getc(FILE *stream);
651 GenericValue lle_X__IO_getc(FunctionType *F, const vector<GenericValue> &Args) {
652   return lle_X_getc(F, Args);
653 }
654
655 // int fputc(int C, FILE *stream);
656 GenericValue lle_X_fputc(FunctionType *M, const vector<GenericValue> &Args) {
657   assert(Args.size() == 2);
658   GenericValue GV;
659   GV.IntVal = fputc(Args[0].IntVal, getFILE(GVTOP(Args[1])));
660   return GV;
661 }
662
663 // int ungetc(int C, FILE *stream);
664 GenericValue lle_X_ungetc(FunctionType *M, const vector<GenericValue> &Args) {
665   assert(Args.size() == 2);
666   GenericValue GV;
667   GV.IntVal = ungetc(Args[0].IntVal, getFILE(GVTOP(Args[1])));
668   return GV;
669 }
670
671 // int fprintf(FILE *,sbyte *, ...) - a very rough implementation to make output
672 // useful.
673 GenericValue lle_X_fprintf(FunctionType *M, const vector<GenericValue> &Args) {
674   assert(Args.size() >= 2);
675   char Buffer[10000];
676   vector<GenericValue> NewArgs;
677   NewArgs.push_back(PTOGV(Buffer));
678   NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end());
679   GenericValue GV = lle_X_sprintf(M, NewArgs);
680
681   fputs(Buffer, getFILE(GVTOP(Args[0])));
682   return GV;
683 }
684
685 //===----------------------------------------------------------------------===//
686 // LLVM Intrinsic Functions...
687 //===----------------------------------------------------------------------===//
688
689 // void llvm.va_start(<va_list> *) - Implement the va_start operation...
690 GenericValue llvm_va_start(FunctionType *F, const vector<GenericValue> &Args) {
691   assert(Args.size() == 1);
692   GenericValue *VAListP = (GenericValue *)GVTOP(Args[0]);
693   GenericValue Val;
694   Val.UIntVal = 0;   // Start at the first '...' argument...
695   TheInterpreter->StoreValueToMemory(Val, VAListP, Type::UIntTy);
696   return GenericValue();
697 }
698
699 // void llvm.va_end(<va_list> *) - Implement the va_end operation...
700 GenericValue llvm_va_end(FunctionType *F, const vector<GenericValue> &Args) {
701   assert(Args.size() == 1);
702   return GenericValue();    // Noop!
703 }
704
705 // void llvm.va_copy(<va_list> *, <va_list>) - Implement the va_copy
706 // operation...
707 GenericValue llvm_va_copy(FunctionType *F, const vector<GenericValue> &Args) {
708   assert(Args.size() == 2);
709   GenericValue *DestVAList = (GenericValue*)GVTOP(Args[0]);
710   TheInterpreter->StoreValueToMemory(Args[1], DestVAList, Type::UIntTy);
711   return GenericValue();
712 }
713
714 } // End extern "C"
715
716
717 void Interpreter::initializeExternalFunctions() {
718   FuncNames["lle_Vb_putchar"]     = lle_Vb_putchar;
719   FuncNames["lle_ii_putchar"]     = lle_ii_putchar;
720   FuncNames["lle_VB_putchar"]     = lle_VB_putchar;
721   FuncNames["lle_X_exit"]         = lle_X_exit;
722   FuncNames["lle_X_abort"]        = lle_X_abort;
723   FuncNames["lle_X_malloc"]       = lle_X_malloc;
724   FuncNames["lle_X_calloc"]       = lle_X_calloc;
725   FuncNames["lle_X_free"]         = lle_X_free;
726   FuncNames["lle_X_atoi"]         = lle_X_atoi;
727   FuncNames["lle_X_pow"]          = lle_X_pow;
728   FuncNames["lle_X_exp"]          = lle_X_exp;
729   FuncNames["lle_X_log"]          = lle_X_log;
730   FuncNames["lle_X_floor"]        = lle_X_floor;
731   FuncNames["lle_X_srand"]        = lle_X_srand;
732   FuncNames["lle_X_drand48"]      = lle_X_drand48;
733   FuncNames["lle_X_srand48"]      = lle_X_srand48;
734   FuncNames["lle_X_lrand48"]      = lle_X_lrand48;
735   FuncNames["lle_X_sqrt"]         = lle_X_sqrt;
736   FuncNames["lle_X_puts"]         = lle_X_puts;
737   FuncNames["lle_X_printf"]       = lle_X_printf;
738   FuncNames["lle_X_sprintf"]      = lle_X_sprintf;
739   FuncNames["lle_X_sscanf"]       = lle_X_sscanf;
740   FuncNames["lle_X_scanf"]        = lle_X_scanf;
741   FuncNames["lle_i_clock"]        = lle_i_clock;
742
743   FuncNames["lle_X_strcmp"]       = lle_X_strcmp;
744   FuncNames["lle_X_strcat"]       = lle_X_strcat;
745   FuncNames["lle_X_strcpy"]       = lle_X_strcpy;
746   FuncNames["lle_X_strlen"]       = lle_X_strlen;
747   FuncNames["lle_X___strdup"]     = lle_X___strdup;
748   FuncNames["lle_X_memset"]       = lle_X_memset;
749   FuncNames["lle_X_memcpy"]       = lle_X_memcpy;
750
751   FuncNames["lle_X_fopen"]        = lle_X_fopen;
752   FuncNames["lle_X_fclose"]       = lle_X_fclose;
753   FuncNames["lle_X_feof"]         = lle_X_feof;
754   FuncNames["lle_X_fread"]        = lle_X_fread;
755   FuncNames["lle_X_fwrite"]       = lle_X_fwrite;
756   FuncNames["lle_X_fgets"]        = lle_X_fgets;
757   FuncNames["lle_X_fflush"]       = lle_X_fflush;
758   FuncNames["lle_X_fgetc"]        = lle_X_getc;
759   FuncNames["lle_X_getc"]         = lle_X_getc;
760   FuncNames["lle_X__IO_getc"]     = lle_X__IO_getc;
761   FuncNames["lle_X_fputc"]        = lle_X_fputc;
762   FuncNames["lle_X_ungetc"]       = lle_X_ungetc;
763   FuncNames["lle_X_fprintf"]      = lle_X_fprintf;
764   FuncNames["lle_X_freopen"]      = lle_X_freopen;
765
766   FuncNames["lle_X_llvm.va_start"]= llvm_va_start;
767   FuncNames["lle_X_llvm.va_end"]  = llvm_va_end;
768   FuncNames["lle_X_llvm.va_copy"] = llvm_va_copy;
769 }