Make ping more aggressive in finding nonlocal caching errors.
[oota-llvm.git] / lib / ExecutionEngine / ExecutionEngine.cpp
1 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
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 defines the common interface used by the various execution engine
11 // subclasses.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "jit"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Config/alloca.h"
22 #include "llvm/ExecutionEngine/ExecutionEngine.h"
23 #include "llvm/ExecutionEngine/GenericValue.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/MutexGuard.h"
26 #include "llvm/System/DynamicLibrary.h"
27 #include "llvm/System/Host.h"
28 #include "llvm/Target/TargetData.h"
29 #include <cmath>
30 #include <cstring>
31 using namespace llvm;
32
33 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
34 STATISTIC(NumGlobals  , "Number of global vars initialized");
35
36 ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
37 ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
38 ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
39
40
41 ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) {
42   LazyCompilationDisabled = false;
43   Modules.push_back(P);
44   assert(P && "ModuleProvider is null?");
45 }
46
47 ExecutionEngine::~ExecutionEngine() {
48   clearAllGlobalMappings();
49   for (unsigned i = 0, e = Modules.size(); i != e; ++i)
50     delete Modules[i];
51 }
52
53 /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
54 /// Release module from ModuleProvider.
55 Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P, 
56                                               std::string *ErrInfo) {
57   for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(), 
58         E = Modules.end(); I != E; ++I) {
59     ModuleProvider *MP = *I;
60     if (MP == P) {
61       Modules.erase(I);
62       clearGlobalMappingsFromModule(MP->getModule());
63       return MP->releaseModule(ErrInfo);
64     }
65   }
66   return NULL;
67 }
68
69 /// FindFunctionNamed - Search all of the active modules to find the one that
70 /// defines FnName.  This is very slow operation and shouldn't be used for
71 /// general code.
72 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
73   for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
74     if (Function *F = Modules[i]->getModule()->getFunction(FnName))
75       return F;
76   }
77   return 0;
78 }
79
80
81 /// addGlobalMapping - Tell the execution engine that the specified global is
82 /// at the specified location.  This is used internally as functions are JIT'd
83 /// and as global variables are laid out in memory.  It can and should also be
84 /// used by clients of the EE that want to have an LLVM global overlay
85 /// existing data in memory.
86 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
87   MutexGuard locked(lock);
88   
89   void *&CurVal = state.getGlobalAddressMap(locked)[GV];
90   assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
91   CurVal = Addr;
92   
93   // If we are using the reverse mapping, add it too
94   if (!state.getGlobalAddressReverseMap(locked).empty()) {
95     const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
96     assert((V == 0 || GV == 0) && "GlobalMapping already established!");
97     V = GV;
98   }
99 }
100
101 /// clearAllGlobalMappings - Clear all global mappings and start over again
102 /// use in dynamic compilation scenarios when you want to move globals
103 void ExecutionEngine::clearAllGlobalMappings() {
104   MutexGuard locked(lock);
105   
106   state.getGlobalAddressMap(locked).clear();
107   state.getGlobalAddressReverseMap(locked).clear();
108 }
109
110 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
111 /// particular module, because it has been removed from the JIT.
112 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
113   MutexGuard locked(lock);
114   
115   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
116     state.getGlobalAddressMap(locked).erase(FI);
117     state.getGlobalAddressReverseMap(locked).erase(FI);
118   }
119   for (Module::global_iterator GI = M->global_begin(), GE = M->global_end(); 
120        GI != GE; ++GI) {
121     state.getGlobalAddressMap(locked).erase(GI);
122     state.getGlobalAddressReverseMap(locked).erase(GI);
123   }
124 }
125
126 /// updateGlobalMapping - Replace an existing mapping for GV with a new
127 /// address.  This updates both maps as required.  If "Addr" is null, the
128 /// entry for the global is removed from the mappings.
129 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
130   MutexGuard locked(lock);
131
132   std::map<const GlobalValue*, void *> &Map = state.getGlobalAddressMap(locked);
133
134   // Deleting from the mapping?
135   if (Addr == 0) {
136     std::map<const GlobalValue*, void *>::iterator I = Map.find(GV);
137     void *OldVal;
138     if (I == Map.end())
139       OldVal = 0;
140     else {
141       OldVal = I->second;
142       Map.erase(I); 
143     }
144     
145     if (!state.getGlobalAddressReverseMap(locked).empty())
146       state.getGlobalAddressReverseMap(locked).erase(Addr);
147     return OldVal;
148   }
149   
150   void *&CurVal = Map[GV];
151   void *OldVal = CurVal;
152
153   if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
154     state.getGlobalAddressReverseMap(locked).erase(CurVal);
155   CurVal = Addr;
156   
157   // If we are using the reverse mapping, add it too
158   if (!state.getGlobalAddressReverseMap(locked).empty()) {
159     const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
160     assert((V == 0 || GV == 0) && "GlobalMapping already established!");
161     V = GV;
162   }
163   return OldVal;
164 }
165
166 /// getPointerToGlobalIfAvailable - This returns the address of the specified
167 /// global value if it is has already been codegen'd, otherwise it returns null.
168 ///
169 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
170   MutexGuard locked(lock);
171   
172   std::map<const GlobalValue*, void*>::iterator I =
173   state.getGlobalAddressMap(locked).find(GV);
174   return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
175 }
176
177 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
178 /// at the specified address.
179 ///
180 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
181   MutexGuard locked(lock);
182
183   // If we haven't computed the reverse mapping yet, do so first.
184   if (state.getGlobalAddressReverseMap(locked).empty()) {
185     for (std::map<const GlobalValue*, void *>::iterator
186          I = state.getGlobalAddressMap(locked).begin(),
187          E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
188       state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
189                                                                      I->first));
190   }
191
192   std::map<void *, const GlobalValue*>::iterator I =
193     state.getGlobalAddressReverseMap(locked).find(Addr);
194   return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
195 }
196
197 // CreateArgv - Turn a vector of strings into a nice argv style array of
198 // pointers to null terminated strings.
199 //
200 static void *CreateArgv(ExecutionEngine *EE,
201                         const std::vector<std::string> &InputArgv) {
202   unsigned PtrSize = EE->getTargetData()->getPointerSize();
203   char *Result = new char[(InputArgv.size()+1)*PtrSize];
204
205   DOUT << "ARGV = " << (void*)Result << "\n";
206   const Type *SBytePtr = PointerType::getUnqual(Type::Int8Ty);
207
208   for (unsigned i = 0; i != InputArgv.size(); ++i) {
209     unsigned Size = InputArgv[i].size()+1;
210     char *Dest = new char[Size];
211     DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
212
213     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
214     Dest[Size-1] = 0;
215
216     // Endian safe: Result[i] = (PointerTy)Dest;
217     EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
218                            SBytePtr);
219   }
220
221   // Null terminate it
222   EE->StoreValueToMemory(PTOGV(0),
223                          (GenericValue*)(Result+InputArgv.size()*PtrSize),
224                          SBytePtr);
225   return Result;
226 }
227
228
229 /// runStaticConstructorsDestructors - This method is used to execute all of
230 /// the static constructors or destructors for a program, depending on the
231 /// value of isDtors.
232 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
233   const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
234   
235   // Execute global ctors/dtors for each module in the program.
236   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
237     GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
238
239     // If this global has internal linkage, or if it has a use, then it must be
240     // an old-style (llvmgcc3) static ctor with __main linked in and in use.  If
241     // this is the case, don't execute any of the global ctors, __main will do
242     // it.
243     if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
244   
245     // Should be an array of '{ int, void ()* }' structs.  The first value is
246     // the init priority, which we ignore.
247     ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
248     if (!InitList) continue;
249     for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
250       if (ConstantStruct *CS = 
251           dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
252         if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
253       
254         Constant *FP = CS->getOperand(1);
255         if (FP->isNullValue())
256           break;  // Found a null terminator, exit.
257       
258         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
259           if (CE->isCast())
260             FP = CE->getOperand(0);
261         if (Function *F = dyn_cast<Function>(FP)) {
262           // Execute the ctor/dtor function!
263           runFunction(F, std::vector<GenericValue>());
264         }
265       }
266   }
267 }
268
269 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
270 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
271   unsigned PtrSize = EE->getTargetData()->getPointerSize();
272   for (unsigned i = 0; i < PtrSize; ++i)
273     if (*(i + (uint8_t*)Loc))
274       return false;
275   return true;
276 }
277
278 /// runFunctionAsMain - This is a helper function which wraps runFunction to
279 /// handle the common task of starting up main with the specified argc, argv,
280 /// and envp parameters.
281 int ExecutionEngine::runFunctionAsMain(Function *Fn,
282                                        const std::vector<std::string> &argv,
283                                        const char * const * envp) {
284   std::vector<GenericValue> GVArgs;
285   GenericValue GVArgc;
286   GVArgc.IntVal = APInt(32, argv.size());
287
288   // Check main() type
289   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
290   const FunctionType *FTy = Fn->getFunctionType();
291   const Type* PPInt8Ty = 
292     PointerType::getUnqual(PointerType::getUnqual(Type::Int8Ty));
293   switch (NumArgs) {
294   case 3:
295    if (FTy->getParamType(2) != PPInt8Ty) {
296      cerr << "Invalid type for third argument of main() supplied\n";
297      abort();
298    }
299    // FALLS THROUGH
300   case 2:
301    if (FTy->getParamType(1) != PPInt8Ty) {
302      cerr << "Invalid type for second argument of main() supplied\n";
303      abort();
304    }
305    // FALLS THROUGH
306   case 1:
307    if (FTy->getParamType(0) != Type::Int32Ty) {
308      cerr << "Invalid type for first argument of main() supplied\n";
309      abort();
310    }
311    // FALLS THROUGH
312   case 0:
313    if (FTy->getReturnType() != Type::Int32Ty &&
314        FTy->getReturnType() != Type::VoidTy) {
315      cerr << "Invalid return type of main() supplied\n";
316      abort();
317    }
318    break;
319   default:
320    cerr << "Invalid number of arguments of main() supplied\n";
321    abort();
322   }
323   
324   if (NumArgs) {
325     GVArgs.push_back(GVArgc); // Arg #0 = argc.
326     if (NumArgs > 1) {
327       GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
328       assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
329              "argv[0] was null after CreateArgv");
330       if (NumArgs > 2) {
331         std::vector<std::string> EnvVars;
332         for (unsigned i = 0; envp[i]; ++i)
333           EnvVars.push_back(envp[i]);
334         GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
335       }
336     }
337   }
338   return runFunction(Fn, GVArgs).IntVal.getZExtValue();
339 }
340
341 /// If possible, create a JIT, unless the caller specifically requests an
342 /// Interpreter or there's an error. If even an Interpreter cannot be created,
343 /// NULL is returned.
344 ///
345 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
346                                          bool ForceInterpreter,
347                                          std::string *ErrorStr) {
348   ExecutionEngine *EE = 0;
349
350   // Make sure we can resolve symbols in the program as well. The zero arg
351   // to the function tells DynamicLibrary to load the program, not a library.
352   if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
353     return 0;
354
355   // Unless the interpreter was explicitly selected, try making a JIT.
356   if (!ForceInterpreter && JITCtor)
357     EE = JITCtor(MP, ErrorStr);
358
359   // If we can't make a JIT, make an interpreter instead.
360   if (EE == 0 && InterpCtor)
361     EE = InterpCtor(MP, ErrorStr);
362
363   return EE;
364 }
365
366 ExecutionEngine *ExecutionEngine::create(Module *M) {
367   return create(new ExistingModuleProvider(M));
368 }
369
370 /// getPointerToGlobal - This returns the address of the specified global
371 /// value.  This may involve code generation if it's a function.
372 ///
373 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
374   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
375     return getPointerToFunction(F);
376
377   MutexGuard locked(lock);
378   void *p = state.getGlobalAddressMap(locked)[GV];
379   if (p)
380     return p;
381
382   // Global variable might have been added since interpreter started.
383   if (GlobalVariable *GVar =
384           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
385     EmitGlobalVariable(GVar);
386   else
387     assert(0 && "Global hasn't had an address allocated yet!");
388   return state.getGlobalAddressMap(locked)[GV];
389 }
390
391 /// This function converts a Constant* into a GenericValue. The interesting 
392 /// part is if C is a ConstantExpr.
393 /// @brief Get a GenericValue for a Constant*
394 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
395   // If its undefined, return the garbage.
396   if (isa<UndefValue>(C)) 
397     return GenericValue();
398
399   // If the value is a ConstantExpr
400   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
401     Constant *Op0 = CE->getOperand(0);
402     switch (CE->getOpcode()) {
403     case Instruction::GetElementPtr: {
404       // Compute the index 
405       GenericValue Result = getConstantValue(Op0);
406       SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
407       uint64_t Offset =
408         TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
409
410       char* tmp = (char*) Result.PointerVal;
411       Result = PTOGV(tmp + Offset);
412       return Result;
413     }
414     case Instruction::Trunc: {
415       GenericValue GV = getConstantValue(Op0);
416       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
417       GV.IntVal = GV.IntVal.trunc(BitWidth);
418       return GV;
419     }
420     case Instruction::ZExt: {
421       GenericValue GV = getConstantValue(Op0);
422       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
423       GV.IntVal = GV.IntVal.zext(BitWidth);
424       return GV;
425     }
426     case Instruction::SExt: {
427       GenericValue GV = getConstantValue(Op0);
428       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
429       GV.IntVal = GV.IntVal.sext(BitWidth);
430       return GV;
431     }
432     case Instruction::FPTrunc: {
433       // FIXME long double
434       GenericValue GV = getConstantValue(Op0);
435       GV.FloatVal = float(GV.DoubleVal);
436       return GV;
437     }
438     case Instruction::FPExt:{
439       // FIXME long double
440       GenericValue GV = getConstantValue(Op0);
441       GV.DoubleVal = double(GV.FloatVal);
442       return GV;
443     }
444     case Instruction::UIToFP: {
445       GenericValue GV = getConstantValue(Op0);
446       if (CE->getType() == Type::FloatTy)
447         GV.FloatVal = float(GV.IntVal.roundToDouble());
448       else if (CE->getType() == Type::DoubleTy)
449         GV.DoubleVal = GV.IntVal.roundToDouble();
450       else if (CE->getType() == Type::X86_FP80Ty) {
451         const uint64_t zero[] = {0, 0};
452         APFloat apf = APFloat(APInt(80, 2, zero));
453         (void)apf.convertFromAPInt(GV.IntVal, 
454                                    false,
455                                    APFloat::rmNearestTiesToEven);
456         GV.IntVal = apf.convertToAPInt();
457       }
458       return GV;
459     }
460     case Instruction::SIToFP: {
461       GenericValue GV = getConstantValue(Op0);
462       if (CE->getType() == Type::FloatTy)
463         GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
464       else if (CE->getType() == Type::DoubleTy)
465         GV.DoubleVal = GV.IntVal.signedRoundToDouble();
466       else if (CE->getType() == Type::X86_FP80Ty) {
467         const uint64_t zero[] = { 0, 0};
468         APFloat apf = APFloat(APInt(80, 2, zero));
469         (void)apf.convertFromAPInt(GV.IntVal, 
470                                    true,
471                                    APFloat::rmNearestTiesToEven);
472         GV.IntVal = apf.convertToAPInt();
473       }
474       return GV;
475     }
476     case Instruction::FPToUI: // double->APInt conversion handles sign
477     case Instruction::FPToSI: {
478       GenericValue GV = getConstantValue(Op0);
479       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
480       if (Op0->getType() == Type::FloatTy)
481         GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
482       else if (Op0->getType() == Type::DoubleTy)
483         GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
484       else if (Op0->getType() == Type::X86_FP80Ty) {
485         APFloat apf = APFloat(GV.IntVal);
486         uint64_t v;
487         (void)apf.convertToInteger(&v, BitWidth,
488                                    CE->getOpcode()==Instruction::FPToSI, 
489                                    APFloat::rmTowardZero);
490         GV.IntVal = v; // endian?
491       }
492       return GV;
493     }
494     case Instruction::PtrToInt: {
495       GenericValue GV = getConstantValue(Op0);
496       uint32_t PtrWidth = TD->getPointerSizeInBits();
497       GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
498       return GV;
499     }
500     case Instruction::IntToPtr: {
501       GenericValue GV = getConstantValue(Op0);
502       uint32_t PtrWidth = TD->getPointerSizeInBits();
503       if (PtrWidth != GV.IntVal.getBitWidth())
504         GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
505       assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
506       GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
507       return GV;
508     }
509     case Instruction::BitCast: {
510       GenericValue GV = getConstantValue(Op0);
511       const Type* DestTy = CE->getType();
512       switch (Op0->getType()->getTypeID()) {
513         default: assert(0 && "Invalid bitcast operand");
514         case Type::IntegerTyID:
515           assert(DestTy->isFloatingPoint() && "invalid bitcast");
516           if (DestTy == Type::FloatTy)
517             GV.FloatVal = GV.IntVal.bitsToFloat();
518           else if (DestTy == Type::DoubleTy)
519             GV.DoubleVal = GV.IntVal.bitsToDouble();
520           break;
521         case Type::FloatTyID: 
522           assert(DestTy == Type::Int32Ty && "Invalid bitcast");
523           GV.IntVal.floatToBits(GV.FloatVal);
524           break;
525         case Type::DoubleTyID:
526           assert(DestTy == Type::Int64Ty && "Invalid bitcast");
527           GV.IntVal.doubleToBits(GV.DoubleVal);
528           break;
529         case Type::PointerTyID:
530           assert(isa<PointerType>(DestTy) && "Invalid bitcast");
531           break; // getConstantValue(Op0)  above already converted it
532       }
533       return GV;
534     }
535     case Instruction::Add:
536     case Instruction::Sub:
537     case Instruction::Mul:
538     case Instruction::UDiv:
539     case Instruction::SDiv:
540     case Instruction::URem:
541     case Instruction::SRem:
542     case Instruction::And:
543     case Instruction::Or:
544     case Instruction::Xor: {
545       GenericValue LHS = getConstantValue(Op0);
546       GenericValue RHS = getConstantValue(CE->getOperand(1));
547       GenericValue GV;
548       switch (CE->getOperand(0)->getType()->getTypeID()) {
549       default: assert(0 && "Bad add type!"); abort();
550       case Type::IntegerTyID:
551         switch (CE->getOpcode()) {
552           default: assert(0 && "Invalid integer opcode");
553           case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
554           case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
555           case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
556           case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
557           case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
558           case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
559           case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
560           case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
561           case Instruction::Or:  GV.IntVal = LHS.IntVal | RHS.IntVal; break;
562           case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
563         }
564         break;
565       case Type::FloatTyID:
566         switch (CE->getOpcode()) {
567           default: assert(0 && "Invalid float opcode"); abort();
568           case Instruction::Add:  
569             GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
570           case Instruction::Sub:  
571             GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
572           case Instruction::Mul:  
573             GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
574           case Instruction::FDiv: 
575             GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
576           case Instruction::FRem: 
577             GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
578         }
579         break;
580       case Type::DoubleTyID:
581         switch (CE->getOpcode()) {
582           default: assert(0 && "Invalid double opcode"); abort();
583           case Instruction::Add:  
584             GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
585           case Instruction::Sub:  
586             GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
587           case Instruction::Mul:  
588             GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
589           case Instruction::FDiv: 
590             GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
591           case Instruction::FRem: 
592             GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
593         }
594         break;
595       case Type::X86_FP80TyID:
596       case Type::PPC_FP128TyID:
597       case Type::FP128TyID: {
598         APFloat apfLHS = APFloat(LHS.IntVal);
599         switch (CE->getOpcode()) {
600           default: assert(0 && "Invalid long double opcode"); abort();
601           case Instruction::Add:  
602             apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
603             GV.IntVal = apfLHS.convertToAPInt();
604             break;
605           case Instruction::Sub:  
606             apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
607             GV.IntVal = apfLHS.convertToAPInt();
608             break;
609           case Instruction::Mul:  
610             apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
611             GV.IntVal = apfLHS.convertToAPInt();
612             break;
613           case Instruction::FDiv: 
614             apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
615             GV.IntVal = apfLHS.convertToAPInt();
616             break;
617           case Instruction::FRem: 
618             apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
619             GV.IntVal = apfLHS.convertToAPInt();
620             break;
621           }
622         }
623         break;
624       }
625       return GV;
626     }
627     default:
628       break;
629     }
630     cerr << "ConstantExpr not handled: " << *CE << "\n";
631     abort();
632   }
633
634   GenericValue Result;
635   switch (C->getType()->getTypeID()) {
636   case Type::FloatTyID: 
637     Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat(); 
638     break;
639   case Type::DoubleTyID:
640     Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
641     break;
642   case Type::X86_FP80TyID:
643   case Type::FP128TyID:
644   case Type::PPC_FP128TyID:
645     Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt();
646     break;
647   case Type::IntegerTyID:
648     Result.IntVal = cast<ConstantInt>(C)->getValue();
649     break;
650   case Type::PointerTyID:
651     if (isa<ConstantPointerNull>(C))
652       Result.PointerVal = 0;
653     else if (const Function *F = dyn_cast<Function>(C))
654       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
655     else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
656       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
657     else
658       assert(0 && "Unknown constant pointer type!");
659     break;
660   default:
661     cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
662     abort();
663   }
664   return Result;
665 }
666
667 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
668 /// with the integer held in IntVal.
669 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
670                              unsigned StoreBytes) {
671   assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
672   uint8_t *Src = (uint8_t *)IntVal.getRawData();
673
674   if (sys::littleEndianHost())
675     // Little-endian host - the source is ordered from LSB to MSB.  Order the
676     // destination from LSB to MSB: Do a straight copy.
677     memcpy(Dst, Src, StoreBytes);
678   else {
679     // Big-endian host - the source is an array of 64 bit words ordered from
680     // LSW to MSW.  Each word is ordered from MSB to LSB.  Order the destination
681     // from MSB to LSB: Reverse the word order, but not the bytes in a word.
682     while (StoreBytes > sizeof(uint64_t)) {
683       StoreBytes -= sizeof(uint64_t);
684       // May not be aligned so use memcpy.
685       memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
686       Src += sizeof(uint64_t);
687     }
688
689     memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
690   }
691 }
692
693 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.  Ptr
694 /// is the address of the memory at which to store Val, cast to GenericValue *.
695 /// It is not a pointer to a GenericValue containing the address at which to
696 /// store Val.
697 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
698                                          const Type *Ty) {
699   const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
700
701   switch (Ty->getTypeID()) {
702   case Type::IntegerTyID:
703     StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
704     break;
705   case Type::FloatTyID:
706     *((float*)Ptr) = Val.FloatVal;
707     break;
708   case Type::DoubleTyID:
709     *((double*)Ptr) = Val.DoubleVal;
710     break;
711   case Type::X86_FP80TyID: {
712       uint16_t *Dest = (uint16_t*)Ptr;
713       const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
714       // This is endian dependent, but it will only work on x86 anyway.
715       Dest[0] = Src[4];
716       Dest[1] = Src[0];
717       Dest[2] = Src[1];
718       Dest[3] = Src[2];
719       Dest[4] = Src[3];
720       break;
721     }
722   case Type::PointerTyID:
723     // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
724     if (StoreBytes != sizeof(PointerTy))
725       memset(Ptr, 0, StoreBytes);
726
727     *((PointerTy*)Ptr) = Val.PointerVal;
728     break;
729   default:
730     cerr << "Cannot store value of type " << *Ty << "!\n";
731   }
732
733   if (sys::littleEndianHost() != getTargetData()->isLittleEndian())
734     // Host and target are different endian - reverse the stored bytes.
735     std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
736 }
737
738 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
739 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
740 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
741   assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
742   uint8_t *Dst = (uint8_t *)IntVal.getRawData();
743
744   if (sys::littleEndianHost())
745     // Little-endian host - the destination must be ordered from LSB to MSB.
746     // The source is ordered from LSB to MSB: Do a straight copy.
747     memcpy(Dst, Src, LoadBytes);
748   else {
749     // Big-endian - the destination is an array of 64 bit words ordered from
750     // LSW to MSW.  Each word must be ordered from MSB to LSB.  The source is
751     // ordered from MSB to LSB: Reverse the word order, but not the bytes in
752     // a word.
753     while (LoadBytes > sizeof(uint64_t)) {
754       LoadBytes -= sizeof(uint64_t);
755       // May not be aligned so use memcpy.
756       memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
757       Dst += sizeof(uint64_t);
758     }
759
760     memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
761   }
762 }
763
764 /// FIXME: document
765 ///
766 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
767                                           GenericValue *Ptr,
768                                           const Type *Ty) {
769   const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
770
771   if (sys::littleEndianHost() != getTargetData()->isLittleEndian()) {
772     // Host and target are different endian - reverse copy the stored
773     // bytes into a buffer, and load from that.
774     uint8_t *Src = (uint8_t*)Ptr;
775     uint8_t *Buf = (uint8_t*)alloca(LoadBytes);
776     std::reverse_copy(Src, Src + LoadBytes, Buf);
777     Ptr = (GenericValue*)Buf;
778   }
779
780   switch (Ty->getTypeID()) {
781   case Type::IntegerTyID:
782     // An APInt with all words initially zero.
783     Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
784     LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
785     break;
786   case Type::FloatTyID:
787     Result.FloatVal = *((float*)Ptr);
788     break;
789   case Type::DoubleTyID:
790     Result.DoubleVal = *((double*)Ptr);
791     break;
792   case Type::PointerTyID:
793     Result.PointerVal = *((PointerTy*)Ptr);
794     break;
795   case Type::X86_FP80TyID: {
796     // This is endian dependent, but it will only work on x86 anyway.
797     // FIXME: Will not trap if loading a signaling NaN.
798     uint16_t *p = (uint16_t*)Ptr;
799     union {
800       uint16_t x[8];
801       uint64_t y[2];
802     };
803     x[0] = p[1];
804     x[1] = p[2];
805     x[2] = p[3];
806     x[3] = p[4];
807     x[4] = p[0];
808     Result.IntVal = APInt(80, 2, y);
809     break;
810   }
811   default:
812     cerr << "Cannot load value of type " << *Ty << "!\n";
813     abort();
814   }
815 }
816
817 // InitializeMemory - Recursive function to apply a Constant value into the
818 // specified memory location...
819 //
820 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
821   if (isa<UndefValue>(Init)) {
822     return;
823   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
824     unsigned ElementSize =
825       getTargetData()->getABITypeSize(CP->getType()->getElementType());
826     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
827       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
828     return;
829   } else if (isa<ConstantAggregateZero>(Init)) {
830     memset(Addr, 0, (size_t)getTargetData()->getABITypeSize(Init->getType()));
831     return;
832   } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
833     unsigned ElementSize =
834       getTargetData()->getABITypeSize(CPA->getType()->getElementType());
835     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
836       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
837     return;
838   } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
839     const StructLayout *SL =
840       getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
841     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
842       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
843     return;
844   } else if (Init->getType()->isFirstClassType()) {
845     GenericValue Val = getConstantValue(Init);
846     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
847     return;
848   }
849
850   cerr << "Bad Type: " << *Init->getType() << "\n";
851   assert(0 && "Unknown constant type to initialize memory with!");
852 }
853
854 /// EmitGlobals - Emit all of the global variables to memory, storing their
855 /// addresses into GlobalAddress.  This must make sure to copy the contents of
856 /// their initializers into the memory.
857 ///
858 void ExecutionEngine::emitGlobals() {
859   const TargetData *TD = getTargetData();
860
861   // Loop over all of the global variables in the program, allocating the memory
862   // to hold them.  If there is more than one module, do a prepass over globals
863   // to figure out how the different modules should link together.
864   //
865   std::map<std::pair<std::string, const Type*>,
866            const GlobalValue*> LinkedGlobalsMap;
867
868   if (Modules.size() != 1) {
869     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
870       Module &M = *Modules[m]->getModule();
871       for (Module::const_global_iterator I = M.global_begin(),
872            E = M.global_end(); I != E; ++I) {
873         const GlobalValue *GV = I;
874         if (GV->hasInternalLinkage() || GV->isDeclaration() ||
875             GV->hasAppendingLinkage() || !GV->hasName())
876           continue;// Ignore external globals and globals with internal linkage.
877           
878         const GlobalValue *&GVEntry = 
879           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
880
881         // If this is the first time we've seen this global, it is the canonical
882         // version.
883         if (!GVEntry) {
884           GVEntry = GV;
885           continue;
886         }
887         
888         // If the existing global is strong, never replace it.
889         if (GVEntry->hasExternalLinkage() ||
890             GVEntry->hasDLLImportLinkage() ||
891             GVEntry->hasDLLExportLinkage())
892           continue;
893         
894         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
895         // symbol.  FIXME is this right for common?
896         if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
897           GVEntry = GV;
898       }
899     }
900   }
901   
902   std::vector<const GlobalValue*> NonCanonicalGlobals;
903   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
904     Module &M = *Modules[m]->getModule();
905     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
906          I != E; ++I) {
907       // In the multi-module case, see what this global maps to.
908       if (!LinkedGlobalsMap.empty()) {
909         if (const GlobalValue *GVEntry = 
910               LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
911           // If something else is the canonical global, ignore this one.
912           if (GVEntry != &*I) {
913             NonCanonicalGlobals.push_back(I);
914             continue;
915           }
916         }
917       }
918       
919       if (!I->isDeclaration()) {
920         // Get the type of the global.
921         const Type *Ty = I->getType()->getElementType();
922
923         // Allocate some memory for it!
924         unsigned Size = TD->getABITypeSize(Ty);
925         addGlobalMapping(I, new char[Size]);
926       } else {
927         // External variable reference. Try to use the dynamic loader to
928         // get a pointer to it.
929         if (void *SymAddr =
930             sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
931           addGlobalMapping(I, SymAddr);
932         else {
933           cerr << "Could not resolve external global address: "
934                << I->getName() << "\n";
935           abort();
936         }
937       }
938     }
939     
940     // If there are multiple modules, map the non-canonical globals to their
941     // canonical location.
942     if (!NonCanonicalGlobals.empty()) {
943       for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
944         const GlobalValue *GV = NonCanonicalGlobals[i];
945         const GlobalValue *CGV =
946           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
947         void *Ptr = getPointerToGlobalIfAvailable(CGV);
948         assert(Ptr && "Canonical global wasn't codegen'd!");
949         addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
950       }
951     }
952     
953     // Now that all of the globals are set up in memory, loop through them all 
954     // and initialize their contents.
955     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
956          I != E; ++I) {
957       if (!I->isDeclaration()) {
958         if (!LinkedGlobalsMap.empty()) {
959           if (const GlobalValue *GVEntry = 
960                 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
961             if (GVEntry != &*I)  // Not the canonical variable.
962               continue;
963         }
964         EmitGlobalVariable(I);
965       }
966     }
967   }
968 }
969
970 // EmitGlobalVariable - This method emits the specified global variable to the
971 // address specified in GlobalAddresses, or allocates new memory if it's not
972 // already in the map.
973 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
974   void *GA = getPointerToGlobalIfAvailable(GV);
975   DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
976
977   const Type *ElTy = GV->getType()->getElementType();
978   size_t GVSize = (size_t)getTargetData()->getABITypeSize(ElTy);
979   if (GA == 0) {
980     // If it's not already specified, allocate memory for the global.
981     GA = new char[GVSize];
982     addGlobalMapping(GV, GA);
983   }
984
985   InitializeMemory(GV->getInitializer(), GA);
986   NumInitBytes += (unsigned)GVSize;
987   ++NumGlobals;
988 }