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