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