92e0020ca8fc2bc139d4d3b590e8b3e5661f80c6
[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 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 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/ExecutionEngine/ExecutionEngine.h"
22 #include "llvm/ExecutionEngine/GenericValue.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/MutexGuard.h"
25 #include "llvm/System/DynamicLibrary.h"
26 #include "llvm/Target/TargetData.h"
27 using namespace llvm;
28
29 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
30 STATISTIC(NumGlobals  , "Number of global vars initialized");
31
32 ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
33 ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
34
35 ExecutionEngine::ExecutionEngine(ModuleProvider *P) {
36   LazyCompilationDisabled = false;
37   Modules.push_back(P);
38   assert(P && "ModuleProvider is null?");
39 }
40
41 ExecutionEngine::ExecutionEngine(Module *M) {
42   LazyCompilationDisabled = false;
43   assert(M && "Module is null?");
44   Modules.push_back(new ExistingModuleProvider(M));
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 /// FindFunctionNamed - Search all of the active modules to find the one that
54 /// defines FnName.  This is very slow operation and shouldn't be used for
55 /// general code.
56 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
57   for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
58     if (Function *F = Modules[i]->getModule()->getFunction(FnName))
59       return F;
60   }
61   return 0;
62 }
63
64
65 /// addGlobalMapping - Tell the execution engine that the specified global is
66 /// at the specified location.  This is used internally as functions are JIT'd
67 /// and as global variables are laid out in memory.  It can and should also be
68 /// used by clients of the EE that want to have an LLVM global overlay
69 /// existing data in memory.
70 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
71   MutexGuard locked(lock);
72   
73   void *&CurVal = state.getGlobalAddressMap(locked)[GV];
74   assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
75   CurVal = Addr;
76   
77   // If we are using the reverse mapping, add it too
78   if (!state.getGlobalAddressReverseMap(locked).empty()) {
79     const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
80     assert((V == 0 || GV == 0) && "GlobalMapping already established!");
81     V = GV;
82   }
83 }
84
85 /// clearAllGlobalMappings - Clear all global mappings and start over again
86 /// use in dynamic compilation scenarios when you want to move globals
87 void ExecutionEngine::clearAllGlobalMappings() {
88   MutexGuard locked(lock);
89   
90   state.getGlobalAddressMap(locked).clear();
91   state.getGlobalAddressReverseMap(locked).clear();
92 }
93
94 /// updateGlobalMapping - Replace an existing mapping for GV with a new
95 /// address.  This updates both maps as required.  If "Addr" is null, the
96 /// entry for the global is removed from the mappings.
97 void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
98   MutexGuard locked(lock);
99   
100   // Deleting from the mapping?
101   if (Addr == 0) {
102     state.getGlobalAddressMap(locked).erase(GV);
103     if (!state.getGlobalAddressReverseMap(locked).empty())
104       state.getGlobalAddressReverseMap(locked).erase(Addr);
105     return;
106   }
107   
108   void *&CurVal = state.getGlobalAddressMap(locked)[GV];
109   if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
110     state.getGlobalAddressReverseMap(locked).erase(CurVal);
111   CurVal = Addr;
112   
113   // If we are using the reverse mapping, add it too
114   if (!state.getGlobalAddressReverseMap(locked).empty()) {
115     const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
116     assert((V == 0 || GV == 0) && "GlobalMapping already established!");
117     V = GV;
118   }
119 }
120
121 /// getPointerToGlobalIfAvailable - This returns the address of the specified
122 /// global value if it is has already been codegen'd, otherwise it returns null.
123 ///
124 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
125   MutexGuard locked(lock);
126   
127   std::map<const GlobalValue*, void*>::iterator I =
128   state.getGlobalAddressMap(locked).find(GV);
129   return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
130 }
131
132 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
133 /// at the specified address.
134 ///
135 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
136   MutexGuard locked(lock);
137
138   // If we haven't computed the reverse mapping yet, do so first.
139   if (state.getGlobalAddressReverseMap(locked).empty()) {
140     for (std::map<const GlobalValue*, void *>::iterator
141          I = state.getGlobalAddressMap(locked).begin(),
142          E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
143       state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
144                                                                      I->first));
145   }
146
147   std::map<void *, const GlobalValue*>::iterator I =
148     state.getGlobalAddressReverseMap(locked).find(Addr);
149   return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
150 }
151
152 // CreateArgv - Turn a vector of strings into a nice argv style array of
153 // pointers to null terminated strings.
154 //
155 static void *CreateArgv(ExecutionEngine *EE,
156                         const std::vector<std::string> &InputArgv) {
157   unsigned PtrSize = EE->getTargetData()->getPointerSize();
158   char *Result = new char[(InputArgv.size()+1)*PtrSize];
159
160   DOUT << "ARGV = " << (void*)Result << "\n";
161   const Type *SBytePtr = PointerType::get(Type::Int8Ty);
162
163   for (unsigned i = 0; i != InputArgv.size(); ++i) {
164     unsigned Size = InputArgv[i].size()+1;
165     char *Dest = new char[Size];
166     DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
167
168     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
169     Dest[Size-1] = 0;
170
171     // Endian safe: Result[i] = (PointerTy)Dest;
172     EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
173                            SBytePtr);
174   }
175
176   // Null terminate it
177   EE->StoreValueToMemory(PTOGV(0),
178                          (GenericValue*)(Result+InputArgv.size()*PtrSize),
179                          SBytePtr);
180   return Result;
181 }
182
183
184 /// runStaticConstructorsDestructors - This method is used to execute all of
185 /// the static constructors or destructors for a program, depending on the
186 /// value of isDtors.
187 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
188   const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
189   
190   // Execute global ctors/dtors for each module in the program.
191   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
192     GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
193
194     // If this global has internal linkage, or if it has a use, then it must be
195     // an old-style (llvmgcc3) static ctor with __main linked in and in use.  If
196     // this is the case, don't execute any of the global ctors, __main will do
197     // it.
198     if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
199   
200     // Should be an array of '{ int, void ()* }' structs.  The first value is
201     // the init priority, which we ignore.
202     ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
203     if (!InitList) continue;
204     for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
205       if (ConstantStruct *CS = 
206           dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
207         if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
208       
209         Constant *FP = CS->getOperand(1);
210         if (FP->isNullValue())
211           break;  // Found a null terminator, exit.
212       
213         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
214           if (CE->isCast())
215             FP = CE->getOperand(0);
216         if (Function *F = dyn_cast<Function>(FP)) {
217           // Execute the ctor/dtor function!
218           runFunction(F, std::vector<GenericValue>());
219         }
220       }
221   }
222 }
223
224 /// runFunctionAsMain - This is a helper function which wraps runFunction to
225 /// handle the common task of starting up main with the specified argc, argv,
226 /// and envp parameters.
227 int ExecutionEngine::runFunctionAsMain(Function *Fn,
228                                        const std::vector<std::string> &argv,
229                                        const char * const * envp) {
230   std::vector<GenericValue> GVArgs;
231   GenericValue GVArgc;
232   GVArgc.Int32Val = argv.size();
233   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
234   if (NumArgs) {
235     GVArgs.push_back(GVArgc); // Arg #0 = argc.
236     if (NumArgs > 1) {
237       GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
238       assert(((char **)GVTOP(GVArgs[1]))[0] &&
239              "argv[0] was null after CreateArgv");
240       if (NumArgs > 2) {
241         std::vector<std::string> EnvVars;
242         for (unsigned i = 0; envp[i]; ++i)
243           EnvVars.push_back(envp[i]);
244         GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
245       }
246     }
247   }
248   return runFunction(Fn, GVArgs).Int32Val;
249 }
250
251 /// If possible, create a JIT, unless the caller specifically requests an
252 /// Interpreter or there's an error. If even an Interpreter cannot be created,
253 /// NULL is returned.
254 ///
255 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
256                                          bool ForceInterpreter,
257                                          std::string *ErrorStr) {
258   ExecutionEngine *EE = 0;
259
260   // Unless the interpreter was explicitly selected, try making a JIT.
261   if (!ForceInterpreter && JITCtor)
262     EE = JITCtor(MP, ErrorStr);
263
264   // If we can't make a JIT, make an interpreter instead.
265   if (EE == 0 && InterpCtor)
266     EE = InterpCtor(MP, ErrorStr);
267
268   if (EE) {
269     // Make sure we can resolve symbols in the program as well. The zero arg
270     // to the function tells DynamicLibrary to load the program, not a library.
271     try {
272       sys::DynamicLibrary::LoadLibraryPermanently(0);
273     } catch (...) {
274     }
275   }
276
277   return EE;
278 }
279
280 /// getPointerToGlobal - This returns the address of the specified global
281 /// value.  This may involve code generation if it's a function.
282 ///
283 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
284   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
285     return getPointerToFunction(F);
286
287   MutexGuard locked(lock);
288   void *p = state.getGlobalAddressMap(locked)[GV];
289   if (p)
290     return p;
291
292   // Global variable might have been added since interpreter started.
293   if (GlobalVariable *GVar =
294           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
295     EmitGlobalVariable(GVar);
296   else
297     assert(0 && "Global hasn't had an address allocated yet!");
298   return state.getGlobalAddressMap(locked)[GV];
299 }
300
301 /// This macro is used to handle a variety of situations involing integer
302 /// values where the action should be done to one of the GenericValue members.
303 /// THEINTTY is a const Type * for the integer type. ACTION1 comes before
304 /// the GenericValue, ACTION2 comes after.
305 #define DO_FOR_INTEGER(THEINTTY, ACTION) \
306    { \
307       unsigned BitWidth = cast<IntegerType>(THEINTTY)->getBitWidth(); \
308       if (BitWidth == 1) {\
309         ACTION(Int1Val); \
310       } else if (BitWidth <= 8) {\
311         ACTION(Int8Val); \
312       } else if (BitWidth <= 16) {\
313         ACTION(Int16Val); \
314       } else if (BitWidth <= 32) { \
315         ACTION(Int32Val); \
316       } else if (BitWidth <= 64) { \
317         ACTION(Int64Val); \
318       } else   {\
319         assert(0 && "Not implemented: integer types > 64 bits"); \
320       } \
321    }
322
323 /// This function converts a Constant* into a GenericValue. The interesting 
324 /// part is if C is a ConstantExpr.
325 /// @brief Get a GenericValue for a Constnat*
326 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
327   // Declare the result as garbage.
328   GenericValue Result;
329
330   // If its undefined, return the garbage.
331   if (isa<UndefValue>(C)) return Result;
332
333   // If the value is a ConstantExpr
334   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
335     switch (CE->getOpcode()) {
336     case Instruction::GetElementPtr: {
337       // Compute the index 
338       Result = getConstantValue(CE->getOperand(0));
339       SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
340       uint64_t Offset =
341         TD->getIndexedOffset(CE->getOperand(0)->getType(),
342                              &Indices[0], Indices.size());
343
344       if (getTargetData()->getPointerSize() == 4)
345         Result.Int32Val += Offset;
346       else
347         Result.Int64Val += Offset;
348       return Result;
349     }
350     case Instruction::Trunc:
351     case Instruction::ZExt:
352     case Instruction::SExt:
353     case Instruction::FPTrunc:
354     case Instruction::FPExt:
355     case Instruction::UIToFP:
356     case Instruction::SIToFP:
357     case Instruction::FPToUI:
358     case Instruction::FPToSI:
359       break;
360     case Instruction::PtrToInt: {
361       Constant *Op = CE->getOperand(0);
362       GenericValue GV = getConstantValue(Op);
363       return GV;
364     }
365     case Instruction::BitCast: {
366       // Bit casts are no-ops but we can only return the GV of the operand if
367       // they are the same basic type (pointer->pointer, packed->packed, etc.)
368       Constant *Op = CE->getOperand(0);
369       GenericValue GV = getConstantValue(Op);
370       if (Op->getType()->getTypeID() == C->getType()->getTypeID())
371         return GV;
372       break;
373     }
374     case Instruction::IntToPtr: {
375       // IntToPtr casts are just so special. Cast to intptr_t first.
376       Constant *Op = CE->getOperand(0);
377       GenericValue GV = getConstantValue(Op);
378 #define INT_TO_PTR_ACTION(FIELD) \
379         return PTOGV((void*)(uintptr_t)GV.FIELD)
380       DO_FOR_INTEGER(Op->getType(), INT_TO_PTR_ACTION)
381 #undef INT_TO_PTR_ACTION
382       break;
383     }
384     case Instruction::Add:
385       switch (CE->getOperand(0)->getType()->getTypeID()) {
386       default: assert(0 && "Bad add type!"); abort();
387       case Type::IntegerTyID:
388 #define ADD_ACTION(FIELD) \
389         Result.FIELD = getConstantValue(CE->getOperand(0)).FIELD + \
390                        getConstantValue(CE->getOperand(1)).FIELD;
391         DO_FOR_INTEGER(CE->getOperand(0)->getType(),ADD_ACTION);
392 #undef ADD_ACTION
393         break;
394       case Type::FloatTyID:
395         Result.FloatVal = getConstantValue(CE->getOperand(0)).FloatVal +
396                           getConstantValue(CE->getOperand(1)).FloatVal;
397         break;
398       case Type::DoubleTyID:
399         Result.DoubleVal = getConstantValue(CE->getOperand(0)).DoubleVal +
400                            getConstantValue(CE->getOperand(1)).DoubleVal;
401         break;
402       }
403       return Result;
404     default:
405       break;
406     }
407     cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
408     abort();
409   }
410
411   switch (C->getType()->getTypeID()) {
412 #define GET_CONST_VAL(TY, CTY, CLASS, GETMETH) \
413   case Type::TY##TyID: Result.TY##Val = (CTY)cast<CLASS>(C)->GETMETH(); break
414     GET_CONST_VAL(Float , float         , ConstantFP, getValue);
415     GET_CONST_VAL(Double, double        , ConstantFP, getValue);
416 #undef GET_CONST_VAL
417   case Type::IntegerTyID: {
418     unsigned BitWidth = cast<IntegerType>(C->getType())->getBitWidth();
419     if (BitWidth == 1)
420       Result.Int1Val = (bool)cast<ConstantInt>(C)->getZExtValue();
421     else if (BitWidth <= 8)
422       Result.Int8Val = (uint8_t )cast<ConstantInt>(C)->getZExtValue();
423     else if (BitWidth <= 16)
424       Result.Int16Val = (uint16_t )cast<ConstantInt>(C)->getZExtValue();
425     else if (BitWidth <= 32)
426       Result.Int32Val = (uint32_t )cast<ConstantInt>(C)->getZExtValue();
427     else if (BitWidth <= 64)
428       Result.Int64Val = (uint64_t )cast<ConstantInt>(C)->getZExtValue();
429     else
430       Result.APIntVal = const_cast<APInt*>(&cast<ConstantInt>(C)->getValue());
431     break;
432   }
433
434   case Type::PointerTyID:
435     if (isa<ConstantPointerNull>(C))
436       Result.PointerVal = 0;
437     else if (const Function *F = dyn_cast<Function>(C))
438       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
439     else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
440       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
441     else
442       assert(0 && "Unknown constant pointer type!");
443     break;
444   default:
445     cerr << "ERROR: Constant unimp for type: " << *C->getType() << "\n";
446     abort();
447   }
448   return Result;
449 }
450
451 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.  Ptr
452 /// is the address of the memory at which to store Val, cast to GenericValue *.
453 /// It is not a pointer to a GenericValue containing the address at which to
454 /// store Val.
455 ///
456 void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
457                                          const Type *Ty) {
458   if (getTargetData()->isLittleEndian()) {
459     switch (Ty->getTypeID()) {
460     case Type::IntegerTyID: {
461       unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
462       uint64_t BitMask = cast<IntegerType>(Ty)->getBitMask();
463       GenericValue TmpVal = Val;
464       if (BitWidth <= 8)
465         Ptr->Untyped[0] = Val.Int8Val & BitMask;
466       else if (BitWidth <= 16) {
467         TmpVal.Int16Val &= BitMask;
468         Ptr->Untyped[0] = TmpVal.Int16Val        & 255;
469         Ptr->Untyped[1] = (TmpVal.Int16Val >> 8) & 255;
470       } else if (BitWidth <= 32) {
471         TmpVal.Int32Val &= BitMask;
472         Ptr->Untyped[0] =  TmpVal.Int32Val        & 255;
473         Ptr->Untyped[1] = (TmpVal.Int32Val >>  8) & 255;
474         Ptr->Untyped[2] = (TmpVal.Int32Val >> 16) & 255;
475         Ptr->Untyped[3] = (TmpVal.Int32Val >> 24) & 255;
476       } else if (BitWidth <= 64) {
477         TmpVal.Int64Val &= BitMask;
478         Ptr->Untyped[0] = (unsigned char)(TmpVal.Int64Val      );
479         Ptr->Untyped[1] = (unsigned char)(TmpVal.Int64Val >>  8);
480         Ptr->Untyped[2] = (unsigned char)(TmpVal.Int64Val >> 16);
481         Ptr->Untyped[3] = (unsigned char)(TmpVal.Int64Val >> 24);
482         Ptr->Untyped[4] = (unsigned char)(TmpVal.Int64Val >> 32);
483         Ptr->Untyped[5] = (unsigned char)(TmpVal.Int64Val >> 40);
484         Ptr->Untyped[6] = (unsigned char)(TmpVal.Int64Val >> 48);
485         Ptr->Untyped[7] = (unsigned char)(TmpVal.Int64Val >> 56);
486       } else {
487         uint64_t *Dest = (uint64_t*)Ptr;
488         const uint64_t *Src = Val.APIntVal->getRawData();
489         for (uint32_t i = 0; i < Val.APIntVal->getNumWords(); ++i)
490           Dest[i] = Src[i];
491       }
492       break;
493     }
494 Store4BytesLittleEndian:
495     case Type::FloatTyID:
496       Ptr->Untyped[0] =  Val.Int32Val        & 255;
497       Ptr->Untyped[1] = (Val.Int32Val >>  8) & 255;
498       Ptr->Untyped[2] = (Val.Int32Val >> 16) & 255;
499       Ptr->Untyped[3] = (Val.Int32Val >> 24) & 255;
500       break;
501     case Type::PointerTyID: 
502       if (getTargetData()->getPointerSize() == 4)
503         goto Store4BytesLittleEndian;
504       /* FALL THROUGH */
505     case Type::DoubleTyID:
506       Ptr->Untyped[0] = (unsigned char)(Val.Int64Val      );
507       Ptr->Untyped[1] = (unsigned char)(Val.Int64Val >>  8);
508       Ptr->Untyped[2] = (unsigned char)(Val.Int64Val >> 16);
509       Ptr->Untyped[3] = (unsigned char)(Val.Int64Val >> 24);
510       Ptr->Untyped[4] = (unsigned char)(Val.Int64Val >> 32);
511       Ptr->Untyped[5] = (unsigned char)(Val.Int64Val >> 40);
512       Ptr->Untyped[6] = (unsigned char)(Val.Int64Val >> 48);
513       Ptr->Untyped[7] = (unsigned char)(Val.Int64Val >> 56);
514       break;
515     default:
516       cerr << "Cannot store value of type " << *Ty << "!\n";
517     }
518   } else {
519     switch (Ty->getTypeID()) {
520     case Type::IntegerTyID: {
521       unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
522       uint64_t BitMask = cast<IntegerType>(Ty)->getBitMask();
523       GenericValue TmpVal = Val;
524       if (BitWidth <= 8)
525         Ptr->Untyped[0] = Val.Int8Val & BitMask;
526       else if (BitWidth <= 16) {
527         TmpVal.Int16Val &= BitMask;
528         Ptr->Untyped[1] =  TmpVal.Int16Val       & 255;
529         Ptr->Untyped[0] = (TmpVal.Int16Val >> 8) & 255;
530       } else if (BitWidth <= 32) {
531         TmpVal.Int32Val &= BitMask;
532         Ptr->Untyped[3] =  TmpVal.Int32Val        & 255;
533         Ptr->Untyped[2] = (TmpVal.Int32Val >>  8) & 255;
534         Ptr->Untyped[1] = (TmpVal.Int32Val >> 16) & 255;
535         Ptr->Untyped[0] = (TmpVal.Int32Val >> 24) & 255;
536       } else if (BitWidth <= 64) {
537         TmpVal.Int64Val &= BitMask;
538         Ptr->Untyped[7] = (unsigned char)(TmpVal.Int64Val      );
539         Ptr->Untyped[6] = (unsigned char)(TmpVal.Int64Val >>  8);
540         Ptr->Untyped[5] = (unsigned char)(TmpVal.Int64Val >> 16);
541         Ptr->Untyped[4] = (unsigned char)(TmpVal.Int64Val >> 24);
542         Ptr->Untyped[3] = (unsigned char)(TmpVal.Int64Val >> 32);
543         Ptr->Untyped[2] = (unsigned char)(TmpVal.Int64Val >> 40);
544         Ptr->Untyped[1] = (unsigned char)(TmpVal.Int64Val >> 48);
545         Ptr->Untyped[0] = (unsigned char)(TmpVal.Int64Val >> 56);
546       } else {
547         uint64_t *Dest = (uint64_t*)Ptr;
548         const uint64_t *Src = Val.APIntVal->getRawData();
549         for (uint32_t i = 0; i < Val.APIntVal->getNumWords(); ++i)
550           Dest[i] = Src[i];
551       }
552       break;
553     }
554     Store4BytesBigEndian:
555     case Type::FloatTyID:
556       Ptr->Untyped[3] =  Val.Int32Val        & 255;
557       Ptr->Untyped[2] = (Val.Int32Val >>  8) & 255;
558       Ptr->Untyped[1] = (Val.Int32Val >> 16) & 255;
559       Ptr->Untyped[0] = (Val.Int32Val >> 24) & 255;
560       break;
561     case Type::PointerTyID: 
562       if (getTargetData()->getPointerSize() == 4)
563         goto Store4BytesBigEndian;
564       /* FALL THROUGH */
565     case Type::DoubleTyID:
566       Ptr->Untyped[7] = (unsigned char)(Val.Int64Val      );
567       Ptr->Untyped[6] = (unsigned char)(Val.Int64Val >>  8);
568       Ptr->Untyped[5] = (unsigned char)(Val.Int64Val >> 16);
569       Ptr->Untyped[4] = (unsigned char)(Val.Int64Val >> 24);
570       Ptr->Untyped[3] = (unsigned char)(Val.Int64Val >> 32);
571       Ptr->Untyped[2] = (unsigned char)(Val.Int64Val >> 40);
572       Ptr->Untyped[1] = (unsigned char)(Val.Int64Val >> 48);
573       Ptr->Untyped[0] = (unsigned char)(Val.Int64Val >> 56);
574       break;
575     default:
576       cerr << "Cannot store value of type " << *Ty << "!\n";
577     }
578   }
579 }
580
581 /// FIXME: document
582 ///
583 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result, 
584                                                   GenericValue *Ptr,
585                                                   const Type *Ty) {
586   if (getTargetData()->isLittleEndian()) {
587     switch (Ty->getTypeID()) {
588     case Type::IntegerTyID: {
589       unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
590       if (BitWidth <= 8)
591         Result.Int8Val  = Ptr->Untyped[0];
592       else if (BitWidth <= 16) {
593         Result.Int16Val =  (unsigned)Ptr->Untyped[0] |
594                           ((unsigned)Ptr->Untyped[1] << 8);
595       } else if (BitWidth <= 32) {
596         Result.Int32Val =  (unsigned)Ptr->Untyped[0] |
597                           ((unsigned)Ptr->Untyped[1] <<  8) |
598                           ((unsigned)Ptr->Untyped[2] << 16) |
599                           ((unsigned)Ptr->Untyped[3] << 24);
600       } else if (BitWidth <= 64) {
601         Result.Int64Val =  (uint64_t)Ptr->Untyped[0] |
602                           ((uint64_t)Ptr->Untyped[1] <<  8) |
603                           ((uint64_t)Ptr->Untyped[2] << 16) |
604                           ((uint64_t)Ptr->Untyped[3] << 24) |
605                           ((uint64_t)Ptr->Untyped[4] << 32) |
606                           ((uint64_t)Ptr->Untyped[5] << 40) |
607                           ((uint64_t)Ptr->Untyped[6] << 48) |
608                           ((uint64_t)Ptr->Untyped[7] << 56);
609       } else
610         *(Result.APIntVal) = APInt(BitWidth, BitWidth/64, (uint64_t*)Ptr);
611       break;
612     }
613     Load4BytesLittleEndian:
614     case Type::FloatTyID:
615       Result.Int32Val =  (unsigned)Ptr->Untyped[0] |
616                         ((unsigned)Ptr->Untyped[1] <<  8) |
617                         ((unsigned)Ptr->Untyped[2] << 16) |
618                         ((unsigned)Ptr->Untyped[3] << 24);
619       break;
620     case Type::PointerTyID: 
621       if (getTargetData()->getPointerSize() == 4)
622         goto Load4BytesLittleEndian;
623       /* FALL THROUGH */
624     case Type::DoubleTyID:
625       Result.Int64Val =  (uint64_t)Ptr->Untyped[0] |
626                         ((uint64_t)Ptr->Untyped[1] <<  8) |
627                         ((uint64_t)Ptr->Untyped[2] << 16) |
628                         ((uint64_t)Ptr->Untyped[3] << 24) |
629                         ((uint64_t)Ptr->Untyped[4] << 32) |
630                         ((uint64_t)Ptr->Untyped[5] << 40) |
631                         ((uint64_t)Ptr->Untyped[6] << 48) |
632                         ((uint64_t)Ptr->Untyped[7] << 56);
633        break;
634     default:
635       cerr << "Cannot load value of type " << *Ty << "!\n";
636       abort();
637     }
638   } else {
639     switch (Ty->getTypeID()) {
640     case Type::IntegerTyID: {
641       uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
642       if (BitWidth <= 8)
643         Result.Int8Val  = Ptr->Untyped[0];
644       else if (BitWidth <= 16) {
645         Result.Int16Val =  (unsigned)Ptr->Untyped[1] |
646                           ((unsigned)Ptr->Untyped[0] << 8);
647       } else if (BitWidth <= 32) {
648         Result.Int32Val =  (unsigned)Ptr->Untyped[3] |
649                           ((unsigned)Ptr->Untyped[2] <<  8) |
650                           ((unsigned)Ptr->Untyped[1] << 16) |
651                           ((unsigned)Ptr->Untyped[0] << 24);
652       } else if (BitWidth <= 64) {
653         Result.Int64Val =  (uint64_t)Ptr->Untyped[7] |
654                           ((uint64_t)Ptr->Untyped[6] <<  8) |
655                           ((uint64_t)Ptr->Untyped[5] << 16) |
656                           ((uint64_t)Ptr->Untyped[4] << 24) |
657                           ((uint64_t)Ptr->Untyped[3] << 32) |
658                           ((uint64_t)Ptr->Untyped[2] << 40) |
659                           ((uint64_t)Ptr->Untyped[1] << 48) |
660                           ((uint64_t)Ptr->Untyped[0] << 56);
661       } else
662         *(Result.APIntVal) = APInt(BitWidth, BitWidth/64, (uint64_t*)Ptr);
663       break;
664     }
665     Load4BytesBigEndian:
666     case Type::FloatTyID:
667       Result.Int32Val =  (unsigned)Ptr->Untyped[3] |
668                         ((unsigned)Ptr->Untyped[2] <<  8) |
669                         ((unsigned)Ptr->Untyped[1] << 16) |
670                         ((unsigned)Ptr->Untyped[0] << 24);
671                             break;
672     case Type::PointerTyID: 
673       if (getTargetData()->getPointerSize() == 4)
674         goto Load4BytesBigEndian;
675       /* FALL THROUGH */
676     case Type::DoubleTyID:
677       Result.Int64Val =  (uint64_t)Ptr->Untyped[7] |
678                         ((uint64_t)Ptr->Untyped[6] <<  8) |
679                         ((uint64_t)Ptr->Untyped[5] << 16) |
680                         ((uint64_t)Ptr->Untyped[4] << 24) |
681                         ((uint64_t)Ptr->Untyped[3] << 32) |
682                         ((uint64_t)Ptr->Untyped[2] << 40) |
683                         ((uint64_t)Ptr->Untyped[1] << 48) |
684                         ((uint64_t)Ptr->Untyped[0] << 56);
685       break;
686     default:
687       cerr << "Cannot load value of type " << *Ty << "!\n";
688       abort();
689     }
690   }
691 }
692
693 // InitializeMemory - Recursive function to apply a Constant value into the
694 // specified memory location...
695 //
696 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
697   if (isa<UndefValue>(Init)) {
698     return;
699   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
700     unsigned ElementSize =
701       getTargetData()->getTypeSize(CP->getType()->getElementType());
702     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
703       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
704     return;
705   } else if (Init->getType()->isFirstClassType()) {
706     GenericValue Val = getConstantValue(Init);
707     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
708     return;
709   } else if (isa<ConstantAggregateZero>(Init)) {
710     memset(Addr, 0, (size_t)getTargetData()->getTypeSize(Init->getType()));
711     return;
712   }
713
714   switch (Init->getType()->getTypeID()) {
715   case Type::ArrayTyID: {
716     const ConstantArray *CPA = cast<ConstantArray>(Init);
717     unsigned ElementSize =
718       getTargetData()->getTypeSize(CPA->getType()->getElementType());
719     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
720       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
721     return;
722   }
723
724   case Type::StructTyID: {
725     const ConstantStruct *CPS = cast<ConstantStruct>(Init);
726     const StructLayout *SL =
727       getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
728     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
729       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
730     return;
731   }
732
733   default:
734     cerr << "Bad Type: " << *Init->getType() << "\n";
735     assert(0 && "Unknown constant type to initialize memory with!");
736   }
737 }
738
739 /// EmitGlobals - Emit all of the global variables to memory, storing their
740 /// addresses into GlobalAddress.  This must make sure to copy the contents of
741 /// their initializers into the memory.
742 ///
743 void ExecutionEngine::emitGlobals() {
744   const TargetData *TD = getTargetData();
745
746   // Loop over all of the global variables in the program, allocating the memory
747   // to hold them.  If there is more than one module, do a prepass over globals
748   // to figure out how the different modules should link together.
749   //
750   std::map<std::pair<std::string, const Type*>,
751            const GlobalValue*> LinkedGlobalsMap;
752
753   if (Modules.size() != 1) {
754     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
755       Module &M = *Modules[m]->getModule();
756       for (Module::const_global_iterator I = M.global_begin(),
757            E = M.global_end(); I != E; ++I) {
758         const GlobalValue *GV = I;
759         if (GV->hasInternalLinkage() || GV->isDeclaration() ||
760             GV->hasAppendingLinkage() || !GV->hasName())
761           continue;// Ignore external globals and globals with internal linkage.
762           
763         const GlobalValue *&GVEntry = 
764           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
765
766         // If this is the first time we've seen this global, it is the canonical
767         // version.
768         if (!GVEntry) {
769           GVEntry = GV;
770           continue;
771         }
772         
773         // If the existing global is strong, never replace it.
774         if (GVEntry->hasExternalLinkage() ||
775             GVEntry->hasDLLImportLinkage() ||
776             GVEntry->hasDLLExportLinkage())
777           continue;
778         
779         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
780         // symbol.
781         if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
782           GVEntry = GV;
783       }
784     }
785   }
786   
787   std::vector<const GlobalValue*> NonCanonicalGlobals;
788   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
789     Module &M = *Modules[m]->getModule();
790     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
791          I != E; ++I) {
792       // In the multi-module case, see what this global maps to.
793       if (!LinkedGlobalsMap.empty()) {
794         if (const GlobalValue *GVEntry = 
795               LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
796           // If something else is the canonical global, ignore this one.
797           if (GVEntry != &*I) {
798             NonCanonicalGlobals.push_back(I);
799             continue;
800           }
801         }
802       }
803       
804       if (!I->isDeclaration()) {
805         // Get the type of the global.
806         const Type *Ty = I->getType()->getElementType();
807
808         // Allocate some memory for it!
809         unsigned Size = TD->getTypeSize(Ty);
810         addGlobalMapping(I, new char[Size]);
811       } else {
812         // External variable reference. Try to use the dynamic loader to
813         // get a pointer to it.
814         if (void *SymAddr =
815             sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
816           addGlobalMapping(I, SymAddr);
817         else {
818           cerr << "Could not resolve external global address: "
819                << I->getName() << "\n";
820           abort();
821         }
822       }
823     }
824     
825     // If there are multiple modules, map the non-canonical globals to their
826     // canonical location.
827     if (!NonCanonicalGlobals.empty()) {
828       for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
829         const GlobalValue *GV = NonCanonicalGlobals[i];
830         const GlobalValue *CGV =
831           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
832         void *Ptr = getPointerToGlobalIfAvailable(CGV);
833         assert(Ptr && "Canonical global wasn't codegen'd!");
834         addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
835       }
836     }
837     
838     // Now that all of the globals are set up in memory, loop through them all 
839     // and initialize their contents.
840     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
841          I != E; ++I) {
842       if (!I->isDeclaration()) {
843         if (!LinkedGlobalsMap.empty()) {
844           if (const GlobalValue *GVEntry = 
845                 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
846             if (GVEntry != &*I)  // Not the canonical variable.
847               continue;
848         }
849         EmitGlobalVariable(I);
850       }
851     }
852   }
853 }
854
855 // EmitGlobalVariable - This method emits the specified global variable to the
856 // address specified in GlobalAddresses, or allocates new memory if it's not
857 // already in the map.
858 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
859   void *GA = getPointerToGlobalIfAvailable(GV);
860   DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
861
862   const Type *ElTy = GV->getType()->getElementType();
863   size_t GVSize = (size_t)getTargetData()->getTypeSize(ElTy);
864   if (GA == 0) {
865     // If it's not already specified, allocate memory for the global.
866     GA = new char[GVSize];
867     addGlobalMapping(GV, GA);
868   }
869
870   InitializeMemory(GV->getInitializer(), GA);
871   NumInitBytes += (unsigned)GVSize;
872   ++NumGlobals;
873 }