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