ExecutionEngine.cpp revision 8fb0f190a90f34b9d94d027ed8daf5f537e4b891
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"
27using namespace llvm;
28
29STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
30STATISTIC(NumGlobals  , "Number of global vars initialized");
31
32ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
33ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
34
35ExecutionEngine::ExecutionEngine(ModuleProvider *P) {
36  LazyCompilationDisabled = false;
37  Modules.push_back(P);
38  assert(P && "ModuleProvider is null?");
39}
40
41ExecutionEngine::ExecutionEngine(Module *M) {
42  LazyCompilationDisabled = false;
43  assert(M && "Module is null?");
44  Modules.push_back(new ExistingModuleProvider(M));
45}
46
47ExecutionEngine::~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.
56Function *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.
70void 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
87void 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.
97void 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///
124void *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///
135const 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//
155static 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.
187void 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.
227int 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///
255ExecutionEngine *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///
283void *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*
304GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
305  // Declare the result as garbage.
306  GenericValue Result;
307
308  // If its undefined, return the garbage.
309  if (isa<UndefValue>(C)) return Result;
310
311  // If the value is a ConstantExpr
312  if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
313    switch (CE->getOpcode()) {
314    case Instruction::GetElementPtr: {
315      // Compute the index
316      Result = getConstantValue(CE->getOperand(0));
317      SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
318      uint64_t Offset =
319        TD->getIndexedOffset(CE->getOperand(0)->getType(),
320                             &Indices[0], Indices.size());
321
322      char* tmp = (char*) Result.PointerVal;
323      Result = PTOGV(tmp + Offset);
324      return Result;
325    }
326    case Instruction::Trunc:
327    case Instruction::ZExt:
328    case Instruction::SExt:
329    case Instruction::FPTrunc:
330    case Instruction::FPExt:
331    case Instruction::UIToFP:
332    case Instruction::SIToFP:
333    case Instruction::FPToUI:
334    case Instruction::FPToSI:
335      break;
336    case Instruction::PtrToInt: {
337      Constant *Op = CE->getOperand(0);
338      GenericValue GV = getConstantValue(Op);
339      return GV;
340    }
341    case Instruction::BitCast: {
342      // Bit casts are no-ops but we can only return the GV of the operand if
343      // they are the same basic type (pointer->pointer, packed->packed, etc.)
344      Constant *Op = CE->getOperand(0);
345      GenericValue GV = getConstantValue(Op);
346      if (Op->getType()->getTypeID() == C->getType()->getTypeID())
347        return GV;
348      break;
349    }
350    case Instruction::IntToPtr: {
351      // IntToPtr casts are just so special. Cast to intptr_t first.
352      Constant *Op = CE->getOperand(0);
353      GenericValue GV = getConstantValue(Op);
354      return PTOGV((void*)(uintptr_t)GV.IntVal.getZExtValue());
355      break;
356    }
357    case Instruction::Add:
358      switch (CE->getOperand(0)->getType()->getTypeID()) {
359      default: assert(0 && "Bad add type!"); abort();
360      case Type::IntegerTyID:
361        Result.IntVal = getConstantValue(CE->getOperand(0)).IntVal + \
362                        getConstantValue(CE->getOperand(1)).IntVal;
363        break;
364      case Type::FloatTyID:
365        Result.FloatVal = getConstantValue(CE->getOperand(0)).FloatVal +
366                          getConstantValue(CE->getOperand(1)).FloatVal;
367        break;
368      case Type::DoubleTyID:
369        Result.DoubleVal = getConstantValue(CE->getOperand(0)).DoubleVal +
370                           getConstantValue(CE->getOperand(1)).DoubleVal;
371        break;
372      }
373      return Result;
374    default:
375      break;
376    }
377    cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
378    abort();
379  }
380
381  switch (C->getType()->getTypeID()) {
382  case Type::FloatTyID:
383    Result.FloatVal = (float)cast<ConstantFP>(C)->getValue();
384    break;
385  case Type::DoubleTyID:
386    Result.DoubleVal = (double)cast<ConstantFP>(C)->getValue();
387    break;
388  case Type::IntegerTyID:
389    Result.IntVal = cast<ConstantInt>(C)->getValue();
390    break;
391  case Type::PointerTyID:
392    if (isa<ConstantPointerNull>(C))
393      Result.PointerVal = 0;
394    else if (const Function *F = dyn_cast<Function>(C))
395      Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
396    else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
397      Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
398    else
399      assert(0 && "Unknown constant pointer type!");
400    break;
401  default:
402    cerr << "ERROR: Constant unimp for type: " << *C->getType() << "\n";
403    abort();
404  }
405  return Result;
406}
407
408/// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.  Ptr
409/// is the address of the memory at which to store Val, cast to GenericValue *.
410/// It is not a pointer to a GenericValue containing the address at which to
411/// store Val.
412///
413void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
414                                         const Type *Ty) {
415  switch (Ty->getTypeID()) {
416  case Type::IntegerTyID: {
417    unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
418    GenericValue TmpVal = Val;
419    if (BitWidth <= 8)
420      *((uint8_t*)Ptr) = uint8_t(Val.IntVal.getZExtValue());
421    else if (BitWidth <= 16) {
422      *((uint16_t*)Ptr) = uint16_t(Val.IntVal.getZExtValue());
423    } else if (BitWidth <= 32) {
424      *((uint32_t*)Ptr) = uint32_t(Val.IntVal.getZExtValue());
425    } else if (BitWidth <= 64) {
426      *((uint64_t*)Ptr) = uint32_t(Val.IntVal.getZExtValue());
427    } else {
428      uint64_t *Dest = (uint64_t*)Ptr;
429      const uint64_t *Src = Val.IntVal.getRawData();
430      for (uint32_t i = 0; i < Val.IntVal.getNumWords(); ++i)
431        Dest[i] = Src[i];
432    }
433    break;
434  }
435  case Type::FloatTyID:
436    *((float*)Ptr) = Val.FloatVal;
437    break;
438  case Type::DoubleTyID:
439    *((double*)Ptr) = Val.DoubleVal;
440    break;
441  case Type::PointerTyID:
442    *((PointerTy*)Ptr) = Val.PointerVal;
443    break;
444  default:
445    cerr << "Cannot store value of type " << *Ty << "!\n";
446  }
447}
448
449/// FIXME: document
450///
451void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
452                                                  GenericValue *Ptr,
453                                                  const Type *Ty) {
454  switch (Ty->getTypeID()) {
455  case Type::IntegerTyID: {
456    unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
457    if (BitWidth <= 8)
458      Result.IntVal = APInt(BitWidth, *((uint8_t*)Ptr));
459    else if (BitWidth <= 16) {
460      Result.IntVal = APInt(BitWidth, *((uint16_t*)Ptr));
461    } else if (BitWidth <= 32) {
462      Result.IntVal = APInt(BitWidth, *((uint32_t*)Ptr));
463    } else if (BitWidth <= 64) {
464      Result.IntVal = APInt(BitWidth, *((uint64_t*)Ptr));
465    } else
466      Result.IntVal = APInt(BitWidth, BitWidth/64, (uint64_t*)Ptr);
467    break;
468  }
469  case Type::FloatTyID:
470    Result.FloatVal = *((float*)Ptr);
471    break;
472  case Type::DoubleTyID:
473    Result.DoubleVal = *((double*)Ptr);
474    break;
475  case Type::PointerTyID:
476    Result.PointerVal = *((PointerTy*)Ptr);
477    break;
478  default:
479    cerr << "Cannot load value of type " << *Ty << "!\n";
480    abort();
481  }
482}
483
484// InitializeMemory - Recursive function to apply a Constant value into the
485// specified memory location...
486//
487void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
488  if (isa<UndefValue>(Init)) {
489    return;
490  } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
491    unsigned ElementSize =
492      getTargetData()->getTypeSize(CP->getType()->getElementType());
493    for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
494      InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
495    return;
496  } else if (Init->getType()->isFirstClassType()) {
497    GenericValue Val = getConstantValue(Init);
498    StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
499    return;
500  } else if (isa<ConstantAggregateZero>(Init)) {
501    memset(Addr, 0, (size_t)getTargetData()->getTypeSize(Init->getType()));
502    return;
503  }
504
505  switch (Init->getType()->getTypeID()) {
506  case Type::ArrayTyID: {
507    const ConstantArray *CPA = cast<ConstantArray>(Init);
508    unsigned ElementSize =
509      getTargetData()->getTypeSize(CPA->getType()->getElementType());
510    for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
511      InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
512    return;
513  }
514
515  case Type::StructTyID: {
516    const ConstantStruct *CPS = cast<ConstantStruct>(Init);
517    const StructLayout *SL =
518      getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
519    for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
520      InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
521    return;
522  }
523
524  default:
525    cerr << "Bad Type: " << *Init->getType() << "\n";
526    assert(0 && "Unknown constant type to initialize memory with!");
527  }
528}
529
530/// EmitGlobals - Emit all of the global variables to memory, storing their
531/// addresses into GlobalAddress.  This must make sure to copy the contents of
532/// their initializers into the memory.
533///
534void ExecutionEngine::emitGlobals() {
535  const TargetData *TD = getTargetData();
536
537  // Loop over all of the global variables in the program, allocating the memory
538  // to hold them.  If there is more than one module, do a prepass over globals
539  // to figure out how the different modules should link together.
540  //
541  std::map<std::pair<std::string, const Type*>,
542           const GlobalValue*> LinkedGlobalsMap;
543
544  if (Modules.size() != 1) {
545    for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
546      Module &M = *Modules[m]->getModule();
547      for (Module::const_global_iterator I = M.global_begin(),
548           E = M.global_end(); I != E; ++I) {
549        const GlobalValue *GV = I;
550        if (GV->hasInternalLinkage() || GV->isDeclaration() ||
551            GV->hasAppendingLinkage() || !GV->hasName())
552          continue;// Ignore external globals and globals with internal linkage.
553
554        const GlobalValue *&GVEntry =
555          LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
556
557        // If this is the first time we've seen this global, it is the canonical
558        // version.
559        if (!GVEntry) {
560          GVEntry = GV;
561          continue;
562        }
563
564        // If the existing global is strong, never replace it.
565        if (GVEntry->hasExternalLinkage() ||
566            GVEntry->hasDLLImportLinkage() ||
567            GVEntry->hasDLLExportLinkage())
568          continue;
569
570        // Otherwise, we know it's linkonce/weak, replace it if this is a strong
571        // symbol.
572        if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
573          GVEntry = GV;
574      }
575    }
576  }
577
578  std::vector<const GlobalValue*> NonCanonicalGlobals;
579  for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
580    Module &M = *Modules[m]->getModule();
581    for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
582         I != E; ++I) {
583      // In the multi-module case, see what this global maps to.
584      if (!LinkedGlobalsMap.empty()) {
585        if (const GlobalValue *GVEntry =
586              LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
587          // If something else is the canonical global, ignore this one.
588          if (GVEntry != &*I) {
589            NonCanonicalGlobals.push_back(I);
590            continue;
591          }
592        }
593      }
594
595      if (!I->isDeclaration()) {
596        // Get the type of the global.
597        const Type *Ty = I->getType()->getElementType();
598
599        // Allocate some memory for it!
600        unsigned Size = TD->getTypeSize(Ty);
601        addGlobalMapping(I, new char[Size]);
602      } else {
603        // External variable reference. Try to use the dynamic loader to
604        // get a pointer to it.
605        if (void *SymAddr =
606            sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
607          addGlobalMapping(I, SymAddr);
608        else {
609          cerr << "Could not resolve external global address: "
610               << I->getName() << "\n";
611          abort();
612        }
613      }
614    }
615
616    // If there are multiple modules, map the non-canonical globals to their
617    // canonical location.
618    if (!NonCanonicalGlobals.empty()) {
619      for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
620        const GlobalValue *GV = NonCanonicalGlobals[i];
621        const GlobalValue *CGV =
622          LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
623        void *Ptr = getPointerToGlobalIfAvailable(CGV);
624        assert(Ptr && "Canonical global wasn't codegen'd!");
625        addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
626      }
627    }
628
629    // Now that all of the globals are set up in memory, loop through them all
630    // and initialize their contents.
631    for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
632         I != E; ++I) {
633      if (!I->isDeclaration()) {
634        if (!LinkedGlobalsMap.empty()) {
635          if (const GlobalValue *GVEntry =
636                LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
637            if (GVEntry != &*I)  // Not the canonical variable.
638              continue;
639        }
640        EmitGlobalVariable(I);
641      }
642    }
643  }
644}
645
646// EmitGlobalVariable - This method emits the specified global variable to the
647// address specified in GlobalAddresses, or allocates new memory if it's not
648// already in the map.
649void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
650  void *GA = getPointerToGlobalIfAvailable(GV);
651  DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
652
653  const Type *ElTy = GV->getType()->getElementType();
654  size_t GVSize = (size_t)getTargetData()->getTypeSize(ElTy);
655  if (GA == 0) {
656    // If it's not already specified, allocate memory for the global.
657    GA = new char[GVSize];
658    addGlobalMapping(GV, GA);
659  }
660
661  InitializeMemory(GV->getInitializer(), GA);
662  NumInitBytes += (unsigned)GVSize;
663  ++NumGlobals;
664}
665