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