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