xref: /llvm-project/llvm/lib/ExecutionEngine/ExecutionEngine.cpp (revision 4fd528f213436ea6bbe42d95e1583603b4f4c5cf)
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.IntVal = APInt(32, 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).IntVal.getZExtValue();
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 function converts a Constant* into a GenericValue. The interesting
302 /// part is if C is a ConstantExpr.
303 /// @brief Get a GenericValue for a Constnat*
304 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
305   // If its undefined, return the garbage.
306   if (isa<UndefValue>(C))
307     return GenericValue();
308 
309   // If the value is a ConstantExpr
310   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
311     Constant *Op0 = CE->getOperand(0);
312     switch (CE->getOpcode()) {
313     case Instruction::GetElementPtr: {
314       // Compute the index
315       GenericValue Result = getConstantValue(Op0);
316       SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
317       uint64_t Offset =
318         TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
319 
320       char* tmp = (char*) Result.PointerVal;
321       Result = PTOGV(tmp + Offset);
322       return Result;
323     }
324     case Instruction::Trunc: {
325       GenericValue GV = getConstantValue(Op0);
326       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
327       GV.IntVal = GV.IntVal.trunc(BitWidth);
328       return GV;
329     }
330     case Instruction::ZExt: {
331       GenericValue GV = getConstantValue(Op0);
332       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
333       GV.IntVal = GV.IntVal.zext(BitWidth);
334       return GV;
335     }
336     case Instruction::SExt: {
337       GenericValue GV = getConstantValue(Op0);
338       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
339       GV.IntVal = GV.IntVal.sext(BitWidth);
340       return GV;
341     }
342     case Instruction::FPTrunc: {
343       GenericValue GV = getConstantValue(Op0);
344       GV.FloatVal = float(GV.DoubleVal);
345       return GV;
346     }
347     case Instruction::FPExt:{
348       GenericValue GV = getConstantValue(Op0);
349       GV.DoubleVal = double(GV.FloatVal);
350       return GV;
351     }
352     case Instruction::UIToFP: {
353       GenericValue GV = getConstantValue(Op0);
354       if (CE->getType() == Type::FloatTy)
355         GV.FloatVal = float(GV.IntVal.roundToDouble());
356       else
357         GV.DoubleVal = GV.IntVal.roundToDouble();
358       return GV;
359     }
360     case Instruction::SIToFP: {
361       GenericValue GV = getConstantValue(Op0);
362       if (CE->getType() == Type::FloatTy)
363         GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
364       else
365         GV.DoubleVal = GV.IntVal.signedRoundToDouble();
366       return GV;
367     }
368     case Instruction::FPToUI: // double->APInt conversion handles sign
369     case Instruction::FPToSI: {
370       GenericValue GV = getConstantValue(Op0);
371       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
372       if (Op0->getType() == Type::FloatTy)
373         GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
374       else
375         GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
376       return GV;
377     }
378     case Instruction::PtrToInt: {
379       GenericValue GV = getConstantValue(Op0);
380       uint32_t PtrWidth = TD->getPointerSizeInBits();
381       GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
382       return GV;
383     }
384     case Instruction::IntToPtr: {
385       GenericValue GV = getConstantValue(Op0);
386       uint32_t PtrWidth = TD->getPointerSizeInBits();
387       if (PtrWidth != GV.IntVal.getBitWidth())
388         GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
389       assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
390       GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
391       return GV;
392     }
393     case Instruction::BitCast: {
394       GenericValue GV = getConstantValue(Op0);
395       const Type* DestTy = CE->getType();
396       switch (Op0->getType()->getTypeID()) {
397         default: assert(0 && "Invalid bitcast operand");
398         case Type::IntegerTyID:
399           assert(DestTy->isFloatingPoint() && "invalid bitcast");
400           if (DestTy == Type::FloatTy)
401             GV.FloatVal = GV.IntVal.bitsToFloat();
402           else if (DestTy == Type::DoubleTy)
403             GV.DoubleVal = GV.IntVal.bitsToDouble();
404           break;
405         case Type::FloatTyID:
406           assert(DestTy == Type::Int32Ty && "Invalid bitcast");
407           GV.IntVal.floatToBits(GV.FloatVal);
408           break;
409         case Type::DoubleTyID:
410           assert(DestTy == Type::Int64Ty && "Invalid bitcast");
411           GV.IntVal.doubleToBits(GV.DoubleVal);
412           break;
413         case Type::PointerTyID:
414           assert(isa<PointerType>(DestTy) && "Invalid bitcast");
415           break; // getConstantValue(Op0)  above already converted it
416       }
417       return GV;
418     }
419     case Instruction::Add:
420     case Instruction::Sub:
421     case Instruction::Mul:
422     case Instruction::UDiv:
423     case Instruction::SDiv:
424     case Instruction::URem:
425     case Instruction::SRem:
426     case Instruction::And:
427     case Instruction::Or:
428     case Instruction::Xor: {
429       GenericValue LHS = getConstantValue(Op0);
430       GenericValue RHS = getConstantValue(CE->getOperand(1));
431       GenericValue GV;
432       switch (CE->getOperand(0)->getType()->getTypeID()) {
433       default: assert(0 && "Bad add type!"); abort();
434       case Type::IntegerTyID:
435         switch (CE->getOpcode()) {
436           default: assert(0 && "Invalid integer opcode");
437           case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
438           case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
439           case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
440           case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
441           case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
442           case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
443           case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
444           case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
445           case Instruction::Or:  GV.IntVal = LHS.IntVal | RHS.IntVal; break;
446           case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
447         }
448         break;
449       case Type::FloatTyID:
450         switch (CE->getOpcode()) {
451           default: assert(0 && "Invalid float opcode"); abort();
452           case Instruction::Add:
453             GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
454           case Instruction::Sub:
455             GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
456           case Instruction::Mul:
457             GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
458           case Instruction::FDiv:
459             GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
460           case Instruction::FRem:
461             GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
462         }
463         break;
464       case Type::DoubleTyID:
465         switch (CE->getOpcode()) {
466           default: assert(0 && "Invalid double opcode"); abort();
467           case Instruction::Add:
468             GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
469           case Instruction::Sub:
470             GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
471           case Instruction::Mul:
472             GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
473           case Instruction::FDiv:
474             GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
475           case Instruction::FRem:
476             GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
477         }
478         break;
479       }
480       return GV;
481     }
482     default:
483       break;
484     }
485     cerr << "ConstantExpr not handled: " << *CE << "\n";
486     abort();
487   }
488 
489   GenericValue Result;
490   switch (C->getType()->getTypeID()) {
491   case Type::FloatTyID:
492     Result.FloatVal = (float)cast<ConstantFP>(C)->getValue();
493     break;
494   case Type::DoubleTyID:
495     Result.DoubleVal = (double)cast<ConstantFP>(C)->getValue();
496     break;
497   case Type::IntegerTyID:
498     Result.IntVal = cast<ConstantInt>(C)->getValue();
499     break;
500   case Type::PointerTyID:
501     if (isa<ConstantPointerNull>(C))
502       Result.PointerVal = 0;
503     else if (const Function *F = dyn_cast<Function>(C))
504       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
505     else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
506       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
507     else
508       assert(0 && "Unknown constant pointer type!");
509     break;
510   default:
511     cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
512     abort();
513   }
514   return Result;
515 }
516 
517 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.  Ptr
518 /// is the address of the memory at which to store Val, cast to GenericValue *.
519 /// It is not a pointer to a GenericValue containing the address at which to
520 /// store Val.
521 ///
522 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
523                                          const Type *Ty) {
524   switch (Ty->getTypeID()) {
525   case Type::IntegerTyID: {
526     unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
527     GenericValue TmpVal = Val;
528     if (BitWidth <= 8)
529       *((uint8_t*)Ptr) = uint8_t(Val.IntVal.getZExtValue());
530     else if (BitWidth <= 16) {
531       *((uint16_t*)Ptr) = uint16_t(Val.IntVal.getZExtValue());
532     } else if (BitWidth <= 32) {
533       *((uint32_t*)Ptr) = uint32_t(Val.IntVal.getZExtValue());
534     } else if (BitWidth <= 64) {
535       *((uint64_t*)Ptr) = uint64_t(Val.IntVal.getZExtValue());
536     } else {
537       uint64_t *Dest = (uint64_t*)Ptr;
538       const uint64_t *Src = Val.IntVal.getRawData();
539       for (uint32_t i = 0; i < Val.IntVal.getNumWords(); ++i)
540         Dest[i] = Src[i];
541     }
542     break;
543   }
544   case Type::FloatTyID:
545     *((float*)Ptr) = Val.FloatVal;
546     break;
547   case Type::DoubleTyID:
548     *((double*)Ptr) = Val.DoubleVal;
549     break;
550   case Type::PointerTyID:
551     *((PointerTy*)Ptr) = Val.PointerVal;
552     break;
553   default:
554     cerr << "Cannot store value of type " << *Ty << "!\n";
555   }
556 }
557 
558 /// FIXME: document
559 ///
560 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
561                                                   GenericValue *Ptr,
562                                                   const Type *Ty) {
563   switch (Ty->getTypeID()) {
564   case Type::IntegerTyID: {
565     unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
566     if (BitWidth <= 8)
567       Result.IntVal = APInt(BitWidth, *((uint8_t*)Ptr));
568     else if (BitWidth <= 16) {
569       Result.IntVal = APInt(BitWidth, *((uint16_t*)Ptr));
570     } else if (BitWidth <= 32) {
571       Result.IntVal = APInt(BitWidth, *((uint32_t*)Ptr));
572     } else if (BitWidth <= 64) {
573       Result.IntVal = APInt(BitWidth, *((uint64_t*)Ptr));
574     } else
575       Result.IntVal = APInt(BitWidth, BitWidth/64, (uint64_t*)Ptr);
576     break;
577   }
578   case Type::FloatTyID:
579     Result.FloatVal = *((float*)Ptr);
580     break;
581   case Type::DoubleTyID:
582     Result.DoubleVal = *((double*)Ptr);
583     break;
584   case Type::PointerTyID:
585     Result.PointerVal = *((PointerTy*)Ptr);
586     break;
587   default:
588     cerr << "Cannot load value of type " << *Ty << "!\n";
589     abort();
590   }
591 }
592 
593 // InitializeMemory - Recursive function to apply a Constant value into the
594 // specified memory location...
595 //
596 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
597   if (isa<UndefValue>(Init)) {
598     return;
599   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
600     unsigned ElementSize =
601       getTargetData()->getTypeSize(CP->getType()->getElementType());
602     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
603       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
604     return;
605   } else if (Init->getType()->isFirstClassType()) {
606     GenericValue Val = getConstantValue(Init);
607     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
608     return;
609   } else if (isa<ConstantAggregateZero>(Init)) {
610     memset(Addr, 0, (size_t)getTargetData()->getTypeSize(Init->getType()));
611     return;
612   }
613 
614   switch (Init->getType()->getTypeID()) {
615   case Type::ArrayTyID: {
616     const ConstantArray *CPA = cast<ConstantArray>(Init);
617     unsigned ElementSize =
618       getTargetData()->getTypeSize(CPA->getType()->getElementType());
619     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
620       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
621     return;
622   }
623 
624   case Type::StructTyID: {
625     const ConstantStruct *CPS = cast<ConstantStruct>(Init);
626     const StructLayout *SL =
627       getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
628     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
629       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
630     return;
631   }
632 
633   default:
634     cerr << "Bad Type: " << *Init->getType() << "\n";
635     assert(0 && "Unknown constant type to initialize memory with!");
636   }
637 }
638 
639 /// EmitGlobals - Emit all of the global variables to memory, storing their
640 /// addresses into GlobalAddress.  This must make sure to copy the contents of
641 /// their initializers into the memory.
642 ///
643 void ExecutionEngine::emitGlobals() {
644   const TargetData *TD = getTargetData();
645 
646   // Loop over all of the global variables in the program, allocating the memory
647   // to hold them.  If there is more than one module, do a prepass over globals
648   // to figure out how the different modules should link together.
649   //
650   std::map<std::pair<std::string, const Type*>,
651            const GlobalValue*> LinkedGlobalsMap;
652 
653   if (Modules.size() != 1) {
654     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
655       Module &M = *Modules[m]->getModule();
656       for (Module::const_global_iterator I = M.global_begin(),
657            E = M.global_end(); I != E; ++I) {
658         const GlobalValue *GV = I;
659         if (GV->hasInternalLinkage() || GV->isDeclaration() ||
660             GV->hasAppendingLinkage() || !GV->hasName())
661           continue;// Ignore external globals and globals with internal linkage.
662 
663         const GlobalValue *&GVEntry =
664           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
665 
666         // If this is the first time we've seen this global, it is the canonical
667         // version.
668         if (!GVEntry) {
669           GVEntry = GV;
670           continue;
671         }
672 
673         // If the existing global is strong, never replace it.
674         if (GVEntry->hasExternalLinkage() ||
675             GVEntry->hasDLLImportLinkage() ||
676             GVEntry->hasDLLExportLinkage())
677           continue;
678 
679         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
680         // symbol.
681         if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
682           GVEntry = GV;
683       }
684     }
685   }
686 
687   std::vector<const GlobalValue*> NonCanonicalGlobals;
688   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
689     Module &M = *Modules[m]->getModule();
690     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
691          I != E; ++I) {
692       // In the multi-module case, see what this global maps to.
693       if (!LinkedGlobalsMap.empty()) {
694         if (const GlobalValue *GVEntry =
695               LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
696           // If something else is the canonical global, ignore this one.
697           if (GVEntry != &*I) {
698             NonCanonicalGlobals.push_back(I);
699             continue;
700           }
701         }
702       }
703 
704       if (!I->isDeclaration()) {
705         // Get the type of the global.
706         const Type *Ty = I->getType()->getElementType();
707 
708         // Allocate some memory for it!
709         unsigned Size = TD->getTypeSize(Ty);
710         addGlobalMapping(I, new char[Size]);
711       } else {
712         // External variable reference. Try to use the dynamic loader to
713         // get a pointer to it.
714         if (void *SymAddr =
715             sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
716           addGlobalMapping(I, SymAddr);
717         else {
718           cerr << "Could not resolve external global address: "
719                << I->getName() << "\n";
720           abort();
721         }
722       }
723     }
724 
725     // If there are multiple modules, map the non-canonical globals to their
726     // canonical location.
727     if (!NonCanonicalGlobals.empty()) {
728       for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
729         const GlobalValue *GV = NonCanonicalGlobals[i];
730         const GlobalValue *CGV =
731           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
732         void *Ptr = getPointerToGlobalIfAvailable(CGV);
733         assert(Ptr && "Canonical global wasn't codegen'd!");
734         addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
735       }
736     }
737 
738     // Now that all of the globals are set up in memory, loop through them all
739     // and initialize their contents.
740     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
741          I != E; ++I) {
742       if (!I->isDeclaration()) {
743         if (!LinkedGlobalsMap.empty()) {
744           if (const GlobalValue *GVEntry =
745                 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
746             if (GVEntry != &*I)  // Not the canonical variable.
747               continue;
748         }
749         EmitGlobalVariable(I);
750       }
751     }
752   }
753 }
754 
755 // EmitGlobalVariable - This method emits the specified global variable to the
756 // address specified in GlobalAddresses, or allocates new memory if it's not
757 // already in the map.
758 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
759   void *GA = getPointerToGlobalIfAvailable(GV);
760   DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
761 
762   const Type *ElTy = GV->getType()->getElementType();
763   size_t GVSize = (size_t)getTargetData()->getTypeSize(ElTy);
764   if (GA == 0) {
765     // If it's not already specified, allocate memory for the global.
766     GA = new char[GVSize];
767     addGlobalMapping(GV, GA);
768   }
769 
770   InitializeMemory(GV->getInitializer(), GA);
771   NumInitBytes += (unsigned)GVSize;
772   ++NumGlobals;
773 }
774