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