Teach the interpreter to handle global variables that are added to a module after
[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 "Interpreter/Interpreter.h"
17 #include "JIT/JIT.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Module.h"
21 #include "llvm/ModuleProvider.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/IntrinsicLowering.h"
24 #include "llvm/ExecutionEngine/ExecutionEngine.h"
25 #include "llvm/ExecutionEngine/GenericValue.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/System/DynamicLibrary.h"
28 #include "llvm/Target/TargetData.h"
29 using namespace llvm;
30
31 namespace {
32   Statistic<> NumInitBytes("lli", "Number of bytes of global vars initialized");
33   Statistic<> NumGlobals  ("lli", "Number of global vars initialized");
34 }
35
36 ExecutionEngine::ExecutionEngine(ModuleProvider *P) :
37   CurMod(*P->getModule()), MP(P) {
38   assert(P && "ModuleProvider is null?");
39 }
40
41 ExecutionEngine::ExecutionEngine(Module *M) : CurMod(*M), MP(0) {
42   assert(M && "Module is null?");
43 }
44
45 ExecutionEngine::~ExecutionEngine() {
46   delete MP;
47 }
48
49 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
50 /// at the specified address.
51 ///
52 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
53   MutexGuard locked(lock);
54
55   // If we haven't computed the reverse mapping yet, do so first.
56   if (state.getGlobalAddressReverseMap(locked).empty()) {
57     for (std::map<const GlobalValue*, void *>::iterator I =
58            state.getGlobalAddressMap(locked).begin(), E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
59       state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second, I->first));
60   }
61
62   std::map<void *, const GlobalValue*>::iterator I =
63     state.getGlobalAddressReverseMap(locked).find(Addr);
64   return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
65 }
66
67 // CreateArgv - Turn a vector of strings into a nice argv style array of
68 // pointers to null terminated strings.
69 //
70 static void *CreateArgv(ExecutionEngine *EE,
71                         const std::vector<std::string> &InputArgv) {
72   unsigned PtrSize = EE->getTargetData().getPointerSize();
73   char *Result = new char[(InputArgv.size()+1)*PtrSize];
74
75   DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n");
76   const Type *SBytePtr = PointerType::get(Type::SByteTy);
77
78   for (unsigned i = 0; i != InputArgv.size(); ++i) {
79     unsigned Size = InputArgv[i].size()+1;
80     char *Dest = new char[Size];
81     DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n");
82
83     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
84     Dest[Size-1] = 0;
85
86     // Endian safe: Result[i] = (PointerTy)Dest;
87     EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
88                            SBytePtr);
89   }
90
91   // Null terminate it
92   EE->StoreValueToMemory(PTOGV(0),
93                          (GenericValue*)(Result+InputArgv.size()*PtrSize),
94                          SBytePtr);
95   return Result;
96 }
97
98 /// runFunctionAsMain - This is a helper function which wraps runFunction to
99 /// handle the common task of starting up main with the specified argc, argv,
100 /// and envp parameters.
101 int ExecutionEngine::runFunctionAsMain(Function *Fn,
102                                        const std::vector<std::string> &argv,
103                                        const char * const * envp) {
104   std::vector<GenericValue> GVArgs;
105   GenericValue GVArgc;
106   GVArgc.IntVal = argv.size();
107   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
108   if (NumArgs) {
109     GVArgs.push_back(GVArgc); // Arg #0 = argc.
110     if (NumArgs > 1) {
111       GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
112       assert(((char **)GVTOP(GVArgs[1]))[0] &&
113              "argv[0] was null after CreateArgv");
114       if (NumArgs > 2) {
115         std::vector<std::string> EnvVars;
116         for (unsigned i = 0; envp[i]; ++i)
117           EnvVars.push_back(envp[i]);
118         GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
119       }
120     }
121   }
122   return runFunction(Fn, GVArgs).IntVal;
123 }
124
125
126
127 /// If possible, create a JIT, unless the caller specifically requests an
128 /// Interpreter or there's an error. If even an Interpreter cannot be created,
129 /// NULL is returned.
130 ///
131 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
132                                          bool ForceInterpreter,
133                                          IntrinsicLowering *IL) {
134   ExecutionEngine *EE = 0;
135
136   // Unless the interpreter was explicitly selected, try making a JIT.
137   if (!ForceInterpreter)
138     EE = JIT::create(MP, IL);
139
140   // If we can't make a JIT, make an interpreter instead.
141   if (EE == 0) {
142     try {
143       Module *M = MP->materializeModule();
144       try {
145         EE = Interpreter::create(M, IL);
146       } catch (...) {
147         std::cerr << "Error creating the interpreter!\n";
148       }
149     } catch (std::string& errmsg) {
150       std::cerr << "Error reading the bytecode file: " << errmsg << "\n";
151     } catch (...) {
152       std::cerr << "Error reading the bytecode file!\n";
153     }
154   }
155
156   if (EE == 0)
157     delete IL;
158   else
159     // Make sure we can resolve symbols in the program as well. The zero arg
160     // to the function tells DynamicLibrary to load the program, not a library.
161     sys::DynamicLibrary::LoadLibraryPermanently(0);
162
163   return EE;
164 }
165
166 /// getPointerToGlobal - This returns the address of the specified global
167 /// value.  This may involve code generation if it's a function.
168 ///
169 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
170   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
171     return getPointerToFunction(F);
172
173   MutexGuard locked(lock);
174   void *p = state.getGlobalAddressMap(locked)[GV];
175   if (p)
176     return p;
177
178   // Global variable might have been added since interpreter started.
179   if (GlobalVariable *GVar =
180           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
181     EmitGlobalVariable(GVar);
182   else
183     assert("Global hasn't had an address allocated yet!");
184   return state.getGlobalAddressMap(locked)[GV];
185 }
186
187 /// FIXME: document
188 ///
189 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
190   GenericValue Result;
191   if (isa<UndefValue>(C)) return Result;
192
193   if (ConstantExpr *CE = const_cast<ConstantExpr*>(dyn_cast<ConstantExpr>(C))) {
194     switch (CE->getOpcode()) {
195     case Instruction::GetElementPtr: {
196       Result = getConstantValue(CE->getOperand(0));
197       std::vector<Value*> Indexes(CE->op_begin()+1, CE->op_end());
198       uint64_t Offset =
199         TD->getIndexedOffset(CE->getOperand(0)->getType(), Indexes);
200
201       if (getTargetData().getPointerSize() == 4)
202         Result.IntVal += Offset;
203       else
204         Result.LongVal += Offset;
205       return Result;
206     }
207     case Instruction::Cast: {
208       // We only need to handle a few cases here.  Almost all casts will
209       // automatically fold, just the ones involving pointers won't.
210       //
211       Constant *Op = CE->getOperand(0);
212       GenericValue GV = getConstantValue(Op);
213
214       // Handle cast of pointer to pointer...
215       if (Op->getType()->getTypeID() == C->getType()->getTypeID())
216         return GV;
217
218       // Handle a cast of pointer to any integral type...
219       if (isa<PointerType>(Op->getType()) && C->getType()->isIntegral())
220         return GV;
221
222       // Handle cast of integer to a pointer...
223       if (isa<PointerType>(C->getType()) && Op->getType()->isIntegral())
224         switch (Op->getType()->getTypeID()) {
225         case Type::BoolTyID:    return PTOGV((void*)(uintptr_t)GV.BoolVal);
226         case Type::SByteTyID:   return PTOGV((void*)( intptr_t)GV.SByteVal);
227         case Type::UByteTyID:   return PTOGV((void*)(uintptr_t)GV.UByteVal);
228         case Type::ShortTyID:   return PTOGV((void*)( intptr_t)GV.ShortVal);
229         case Type::UShortTyID:  return PTOGV((void*)(uintptr_t)GV.UShortVal);
230         case Type::IntTyID:     return PTOGV((void*)( intptr_t)GV.IntVal);
231         case Type::UIntTyID:    return PTOGV((void*)(uintptr_t)GV.UIntVal);
232         case Type::LongTyID:    return PTOGV((void*)( intptr_t)GV.LongVal);
233         case Type::ULongTyID:   return PTOGV((void*)(uintptr_t)GV.ULongVal);
234         default: assert(0 && "Unknown integral type!");
235         }
236       break;
237     }
238
239     case Instruction::Add:
240       switch (CE->getOperand(0)->getType()->getTypeID()) {
241       default: assert(0 && "Bad add type!"); abort();
242       case Type::LongTyID:
243       case Type::ULongTyID:
244         Result.LongVal = getConstantValue(CE->getOperand(0)).LongVal +
245                          getConstantValue(CE->getOperand(1)).LongVal;
246         break;
247       case Type::IntTyID:
248       case Type::UIntTyID:
249         Result.IntVal = getConstantValue(CE->getOperand(0)).IntVal +
250                         getConstantValue(CE->getOperand(1)).IntVal;
251         break;
252       case Type::ShortTyID:
253       case Type::UShortTyID:
254         Result.ShortVal = getConstantValue(CE->getOperand(0)).ShortVal +
255                           getConstantValue(CE->getOperand(1)).ShortVal;
256         break;
257       case Type::SByteTyID:
258       case Type::UByteTyID:
259         Result.SByteVal = getConstantValue(CE->getOperand(0)).SByteVal +
260                           getConstantValue(CE->getOperand(1)).SByteVal;
261         break;
262       case Type::FloatTyID:
263         Result.FloatVal = getConstantValue(CE->getOperand(0)).FloatVal +
264                           getConstantValue(CE->getOperand(1)).FloatVal;
265         break;
266       case Type::DoubleTyID:
267         Result.DoubleVal = getConstantValue(CE->getOperand(0)).DoubleVal +
268                            getConstantValue(CE->getOperand(1)).DoubleVal;
269         break;
270       }
271       return Result;
272     default:
273       break;
274     }
275     std::cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
276     abort();
277   }
278
279   switch (C->getType()->getTypeID()) {
280 #define GET_CONST_VAL(TY, CTY, CLASS) \
281   case Type::TY##TyID: Result.TY##Val = (CTY)cast<CLASS>(C)->getValue(); break
282     GET_CONST_VAL(Bool   , bool          , ConstantBool);
283     GET_CONST_VAL(UByte  , unsigned char , ConstantUInt);
284     GET_CONST_VAL(SByte  , signed char   , ConstantSInt);
285     GET_CONST_VAL(UShort , unsigned short, ConstantUInt);
286     GET_CONST_VAL(Short  , signed short  , ConstantSInt);
287     GET_CONST_VAL(UInt   , unsigned int  , ConstantUInt);
288     GET_CONST_VAL(Int    , signed int    , ConstantSInt);
289     GET_CONST_VAL(ULong  , uint64_t      , ConstantUInt);
290     GET_CONST_VAL(Long   , int64_t       , ConstantSInt);
291     GET_CONST_VAL(Float  , float         , ConstantFP);
292     GET_CONST_VAL(Double , double        , ConstantFP);
293 #undef GET_CONST_VAL
294   case Type::PointerTyID:
295     if (isa<ConstantPointerNull>(C))
296       Result.PointerVal = 0;
297     else if (const Function *F = dyn_cast<Function>(C))
298       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
299     else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
300       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
301     else
302       assert(0 && "Unknown constant pointer type!");
303     break;
304   default:
305     std::cout << "ERROR: Constant unimp for type: " << *C->getType() << "\n";
306     abort();
307   }
308   return Result;
309 }
310
311 /// FIXME: document
312 ///
313 void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
314                                          const Type *Ty) {
315   if (getTargetData().isLittleEndian()) {
316     switch (Ty->getTypeID()) {
317     case Type::BoolTyID:
318     case Type::UByteTyID:
319     case Type::SByteTyID:   Ptr->Untyped[0] = Val.UByteVal; break;
320     case Type::UShortTyID:
321     case Type::ShortTyID:   Ptr->Untyped[0] = Val.UShortVal & 255;
322                             Ptr->Untyped[1] = (Val.UShortVal >> 8) & 255;
323                             break;
324     Store4BytesLittleEndian:
325     case Type::FloatTyID:
326     case Type::UIntTyID:
327     case Type::IntTyID:     Ptr->Untyped[0] =  Val.UIntVal        & 255;
328                             Ptr->Untyped[1] = (Val.UIntVal >>  8) & 255;
329                             Ptr->Untyped[2] = (Val.UIntVal >> 16) & 255;
330                             Ptr->Untyped[3] = (Val.UIntVal >> 24) & 255;
331                             break;
332     case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
333                               goto Store4BytesLittleEndian;
334     case Type::DoubleTyID:
335     case Type::ULongTyID:
336     case Type::LongTyID:
337       Ptr->Untyped[0] = (unsigned char)(Val.ULongVal      );
338       Ptr->Untyped[1] = (unsigned char)(Val.ULongVal >>  8);
339       Ptr->Untyped[2] = (unsigned char)(Val.ULongVal >> 16);
340       Ptr->Untyped[3] = (unsigned char)(Val.ULongVal >> 24);
341       Ptr->Untyped[4] = (unsigned char)(Val.ULongVal >> 32);
342       Ptr->Untyped[5] = (unsigned char)(Val.ULongVal >> 40);
343       Ptr->Untyped[6] = (unsigned char)(Val.ULongVal >> 48);
344       Ptr->Untyped[7] = (unsigned char)(Val.ULongVal >> 56);
345       break;
346     default:
347       std::cout << "Cannot store value of type " << *Ty << "!\n";
348     }
349   } else {
350     switch (Ty->getTypeID()) {
351     case Type::BoolTyID:
352     case Type::UByteTyID:
353     case Type::SByteTyID:   Ptr->Untyped[0] = Val.UByteVal; break;
354     case Type::UShortTyID:
355     case Type::ShortTyID:   Ptr->Untyped[1] = Val.UShortVal & 255;
356                             Ptr->Untyped[0] = (Val.UShortVal >> 8) & 255;
357                             break;
358     Store4BytesBigEndian:
359     case Type::FloatTyID:
360     case Type::UIntTyID:
361     case Type::IntTyID:     Ptr->Untyped[3] =  Val.UIntVal        & 255;
362                             Ptr->Untyped[2] = (Val.UIntVal >>  8) & 255;
363                             Ptr->Untyped[1] = (Val.UIntVal >> 16) & 255;
364                             Ptr->Untyped[0] = (Val.UIntVal >> 24) & 255;
365                             break;
366     case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
367                               goto Store4BytesBigEndian;
368     case Type::DoubleTyID:
369     case Type::ULongTyID:
370     case Type::LongTyID:
371       Ptr->Untyped[7] = (unsigned char)(Val.ULongVal      );
372       Ptr->Untyped[6] = (unsigned char)(Val.ULongVal >>  8);
373       Ptr->Untyped[5] = (unsigned char)(Val.ULongVal >> 16);
374       Ptr->Untyped[4] = (unsigned char)(Val.ULongVal >> 24);
375       Ptr->Untyped[3] = (unsigned char)(Val.ULongVal >> 32);
376       Ptr->Untyped[2] = (unsigned char)(Val.ULongVal >> 40);
377       Ptr->Untyped[1] = (unsigned char)(Val.ULongVal >> 48);
378       Ptr->Untyped[0] = (unsigned char)(Val.ULongVal >> 56);
379       break;
380     default:
381       std::cout << "Cannot store value of type " << *Ty << "!\n";
382     }
383   }
384 }
385
386 /// FIXME: document
387 ///
388 GenericValue ExecutionEngine::LoadValueFromMemory(GenericValue *Ptr,
389                                                   const Type *Ty) {
390   GenericValue Result;
391   if (getTargetData().isLittleEndian()) {
392     switch (Ty->getTypeID()) {
393     case Type::BoolTyID:
394     case Type::UByteTyID:
395     case Type::SByteTyID:   Result.UByteVal = Ptr->Untyped[0]; break;
396     case Type::UShortTyID:
397     case Type::ShortTyID:   Result.UShortVal = (unsigned)Ptr->Untyped[0] |
398                                               ((unsigned)Ptr->Untyped[1] << 8);
399                             break;
400     Load4BytesLittleEndian:
401     case Type::FloatTyID:
402     case Type::UIntTyID:
403     case Type::IntTyID:     Result.UIntVal = (unsigned)Ptr->Untyped[0] |
404                                             ((unsigned)Ptr->Untyped[1] <<  8) |
405                                             ((unsigned)Ptr->Untyped[2] << 16) |
406                                             ((unsigned)Ptr->Untyped[3] << 24);
407                             break;
408     case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
409                               goto Load4BytesLittleEndian;
410     case Type::DoubleTyID:
411     case Type::ULongTyID:
412     case Type::LongTyID:    Result.ULongVal = (uint64_t)Ptr->Untyped[0] |
413                                              ((uint64_t)Ptr->Untyped[1] <<  8) |
414                                              ((uint64_t)Ptr->Untyped[2] << 16) |
415                                              ((uint64_t)Ptr->Untyped[3] << 24) |
416                                              ((uint64_t)Ptr->Untyped[4] << 32) |
417                                              ((uint64_t)Ptr->Untyped[5] << 40) |
418                                              ((uint64_t)Ptr->Untyped[6] << 48) |
419                                              ((uint64_t)Ptr->Untyped[7] << 56);
420                             break;
421     default:
422       std::cout << "Cannot load value of type " << *Ty << "!\n";
423       abort();
424     }
425   } else {
426     switch (Ty->getTypeID()) {
427     case Type::BoolTyID:
428     case Type::UByteTyID:
429     case Type::SByteTyID:   Result.UByteVal = Ptr->Untyped[0]; break;
430     case Type::UShortTyID:
431     case Type::ShortTyID:   Result.UShortVal = (unsigned)Ptr->Untyped[1] |
432                                               ((unsigned)Ptr->Untyped[0] << 8);
433                             break;
434     Load4BytesBigEndian:
435     case Type::FloatTyID:
436     case Type::UIntTyID:
437     case Type::IntTyID:     Result.UIntVal = (unsigned)Ptr->Untyped[3] |
438                                             ((unsigned)Ptr->Untyped[2] <<  8) |
439                                             ((unsigned)Ptr->Untyped[1] << 16) |
440                                             ((unsigned)Ptr->Untyped[0] << 24);
441                             break;
442     case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
443                               goto Load4BytesBigEndian;
444     case Type::DoubleTyID:
445     case Type::ULongTyID:
446     case Type::LongTyID:    Result.ULongVal = (uint64_t)Ptr->Untyped[7] |
447                                              ((uint64_t)Ptr->Untyped[6] <<  8) |
448                                              ((uint64_t)Ptr->Untyped[5] << 16) |
449                                              ((uint64_t)Ptr->Untyped[4] << 24) |
450                                              ((uint64_t)Ptr->Untyped[3] << 32) |
451                                              ((uint64_t)Ptr->Untyped[2] << 40) |
452                                              ((uint64_t)Ptr->Untyped[1] << 48) |
453                                              ((uint64_t)Ptr->Untyped[0] << 56);
454                             break;
455     default:
456       std::cout << "Cannot load value of type " << *Ty << "!\n";
457       abort();
458     }
459   }
460   return Result;
461 }
462
463 // InitializeMemory - Recursive function to apply a Constant value into the
464 // specified memory location...
465 //
466 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
467   if (isa<UndefValue>(Init)) {
468     return;
469   } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(Init)) {
470     unsigned ElementSize =
471       getTargetData().getTypeSize(CP->getType()->getElementType());
472     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
473       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
474     return;
475   } else if (Init->getType()->isFirstClassType()) {
476     GenericValue Val = getConstantValue(Init);
477     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
478     return;
479   } else if (isa<ConstantAggregateZero>(Init)) {
480     memset(Addr, 0, (size_t)getTargetData().getTypeSize(Init->getType()));
481     return;
482   }
483
484   switch (Init->getType()->getTypeID()) {
485   case Type::ArrayTyID: {
486     const ConstantArray *CPA = cast<ConstantArray>(Init);
487     unsigned ElementSize =
488       getTargetData().getTypeSize(CPA->getType()->getElementType());
489     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
490       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
491     return;
492   }
493
494   case Type::StructTyID: {
495     const ConstantStruct *CPS = cast<ConstantStruct>(Init);
496     const StructLayout *SL =
497       getTargetData().getStructLayout(cast<StructType>(CPS->getType()));
498     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
499       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->MemberOffsets[i]);
500     return;
501   }
502
503   default:
504     std::cerr << "Bad Type: " << *Init->getType() << "\n";
505     assert(0 && "Unknown constant type to initialize memory with!");
506   }
507 }
508
509 /// EmitGlobals - Emit all of the global variables to memory, storing their
510 /// addresses into GlobalAddress.  This must make sure to copy the contents of
511 /// their initializers into the memory.
512 ///
513 void ExecutionEngine::emitGlobals() {
514   const TargetData &TD = getTargetData();
515
516   // Loop over all of the global variables in the program, allocating the memory
517   // to hold them.
518   Module &M = getModule();
519   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
520        I != E; ++I)
521     if (!I->isExternal()) {
522       // Get the type of the global...
523       const Type *Ty = I->getType()->getElementType();
524
525       // Allocate some memory for it!
526       unsigned Size = TD.getTypeSize(Ty);
527       addGlobalMapping(I, new char[Size]);
528     } else {
529       // External variable reference. Try to use the dynamic loader to
530       // get a pointer to it.
531       if (void *SymAddr = sys::DynamicLibrary::SearchForAddressOfSymbol(
532                             I->getName().c_str()))
533         addGlobalMapping(I, SymAddr);
534       else {
535         std::cerr << "Could not resolve external global address: "
536                   << I->getName() << "\n";
537         abort();
538       }
539     }
540
541   // Now that all of the globals are set up in memory, loop through them all and
542   // initialize their contents.
543   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
544        I != E; ++I)
545     if (!I->isExternal())
546       EmitGlobalVariable(I);
547 }
548
549 // EmitGlobalVariable - This method emits the specified global variable to the
550 // address specified in GlobalAddresses, or allocates new memory if it's not
551 // already in the map.
552 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
553   void *GA = getPointerToGlobalIfAvailable(GV);
554   DEBUG(std::cerr << "Global '" << GV->getName() << "' -> " << GA << "\n");
555
556   const Type *ElTy = GV->getType()->getElementType();
557   size_t GVSize = (size_t)getTargetData().getTypeSize(ElTy);
558   if (GA == 0) {
559     // If it's not already specified, allocate memory for the global.
560     GA = new char[GVSize];
561     addGlobalMapping(GV, GA);
562   }
563
564   InitializeMemory(GV->getInitializer(), GA);
565   NumInitBytes += (unsigned)GVSize;
566   ++NumGlobals;
567 }