1193323Sed//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This file defines the common interface used by the various execution engine
11193323Sed// subclasses.
12193323Sed//
13193323Sed//===----------------------------------------------------------------------===//
14193323Sed
15193323Sed#define DEBUG_TYPE "jit"
16198090Srdivacky#include "llvm/ExecutionEngine/ExecutionEngine.h"
17263509Sdim#include "llvm/ExecutionEngine/JITMemoryManager.h"
18263509Sdim#include "llvm/ExecutionEngine/ObjectCache.h"
19218893Sdim#include "llvm/ADT/SmallString.h"
20193323Sed#include "llvm/ADT/Statistic.h"
21252723Sdim#include "llvm/ExecutionEngine/GenericValue.h"
22252723Sdim#include "llvm/IR/Constants.h"
23252723Sdim#include "llvm/IR/DataLayout.h"
24252723Sdim#include "llvm/IR/DerivedTypes.h"
25252723Sdim#include "llvm/IR/Module.h"
26252723Sdim#include "llvm/IR/Operator.h"
27193323Sed#include "llvm/Support/Debug.h"
28252723Sdim#include "llvm/Support/DynamicLibrary.h"
29198090Srdivacky#include "llvm/Support/ErrorHandling.h"
30252723Sdim#include "llvm/Support/Host.h"
31193323Sed#include "llvm/Support/MutexGuard.h"
32252723Sdim#include "llvm/Support/TargetRegistry.h"
33198090Srdivacky#include "llvm/Support/ValueHandle.h"
34198090Srdivacky#include "llvm/Support/raw_ostream.h"
35223017Sdim#include "llvm/Target/TargetMachine.h"
36193323Sed#include <cmath>
37193323Sed#include <cstring>
38193323Sedusing namespace llvm;
39193323Sed
40193323SedSTATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
41193323SedSTATISTIC(NumGlobals  , "Number of global vars initialized");
42193323Sed
43263509Sdim// Pin the vtable to this file.
44263509Sdimvoid ObjectCache::anchor() {}
45263509Sdimvoid ObjectBuffer::anchor() {}
46263509Sdimvoid ObjectBufferStream::anchor() {}
47263509Sdim
48203954SrdivackyExecutionEngine *(*ExecutionEngine::JITCtor)(
49203954Srdivacky  Module *M,
50203954Srdivacky  std::string *ErrorStr,
51203954Srdivacky  JITMemoryManager *JMM,
52203954Srdivacky  bool GVsWithCode,
53223017Sdim  TargetMachine *TM) = 0;
54218893SdimExecutionEngine *(*ExecutionEngine::MCJITCtor)(
55218893Sdim  Module *M,
56218893Sdim  std::string *ErrorStr,
57263509Sdim  RTDyldMemoryManager *MCJMM,
58218893Sdim  bool GVsWithCode,
59223017Sdim  TargetMachine *TM) = 0;
60203954SrdivackyExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
61198090Srdivacky                                                std::string *ErrorStr) = 0;
62193323Sed
63203954SrdivackyExecutionEngine::ExecutionEngine(Module *M)
64198090Srdivacky  : EEState(*this),
65263509Sdim    LazyFunctionCreator(0) {
66198892Srdivacky  CompilingLazily         = false;
67193323Sed  GVCompilationDisabled   = false;
68193323Sed  SymbolSearchingDisabled = false;
69203954Srdivacky  Modules.push_back(M);
70203954Srdivacky  assert(M && "Module is null?");
71193323Sed}
72193323Sed
73193323SedExecutionEngine::~ExecutionEngine() {
74193323Sed  clearAllGlobalMappings();
75193323Sed  for (unsigned i = 0, e = Modules.size(); i != e; ++i)
76193323Sed    delete Modules[i];
77193323Sed}
78193323Sed
79206083Srdivackynamespace {
80218893Sdim/// \brief Helper class which uses a value handler to automatically deletes the
81218893Sdim/// memory block when the GlobalVariable is destroyed.
82206083Srdivackyclass GVMemoryBlock : public CallbackVH {
83206083Srdivacky  GVMemoryBlock(const GlobalVariable *GV)
84206083Srdivacky    : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
85206083Srdivacky
86206083Srdivackypublic:
87218893Sdim  /// \brief Returns the address the GlobalVariable should be written into.  The
88218893Sdim  /// GVMemoryBlock object prefixes that.
89245431Sdim  static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
90226890Sdim    Type *ElTy = GV->getType()->getElementType();
91206083Srdivacky    size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
92206083Srdivacky    void *RawMemory = ::operator new(
93245431Sdim      DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock),
94206083Srdivacky                                   TD.getPreferredAlignment(GV))
95206083Srdivacky      + GVSize);
96206083Srdivacky    new(RawMemory) GVMemoryBlock(GV);
97206083Srdivacky    return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
98206083Srdivacky  }
99206083Srdivacky
100206083Srdivacky  virtual void deleted() {
101206083Srdivacky    // We allocated with operator new and with some extra memory hanging off the
102206083Srdivacky    // end, so don't just delete this.  I'm not sure if this is actually
103206083Srdivacky    // required.
104206083Srdivacky    this->~GVMemoryBlock();
105206083Srdivacky    ::operator delete(this);
106206083Srdivacky  }
107206083Srdivacky};
108206083Srdivacky}  // anonymous namespace
109206083Srdivacky
110218893Sdimchar *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
111245431Sdim  return GVMemoryBlock::Create(GV, *getDataLayout());
112193323Sed}
113193323Sed
114203954Srdivackybool ExecutionEngine::removeModule(Module *M) {
115263509Sdim  for(SmallVectorImpl<Module *>::iterator I = Modules.begin(),
116193323Sed        E = Modules.end(); I != E; ++I) {
117203954Srdivacky    Module *Found = *I;
118203954Srdivacky    if (Found == M) {
119193323Sed      Modules.erase(I);
120203954Srdivacky      clearGlobalMappingsFromModule(M);
121203954Srdivacky      return true;
122193323Sed    }
123193323Sed  }
124203954Srdivacky  return false;
125193323Sed}
126193323Sed
127193323SedFunction *ExecutionEngine::FindFunctionNamed(const char *FnName) {
128193323Sed  for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
129203954Srdivacky    if (Function *F = Modules[i]->getFunction(FnName))
130193323Sed      return F;
131193323Sed  }
132193323Sed  return 0;
133193323Sed}
134193323Sed
135193323Sed
136218893Sdimvoid *ExecutionEngineState::RemoveMapping(const MutexGuard &,
137218893Sdim                                          const GlobalValue *ToUnmap) {
138198892Srdivacky  GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
139198090Srdivacky  void *OldVal;
140218893Sdim
141218893Sdim  // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
142218893Sdim  // GlobalAddressMap.
143198090Srdivacky  if (I == GlobalAddressMap.end())
144198090Srdivacky    OldVal = 0;
145198090Srdivacky  else {
146198090Srdivacky    OldVal = I->second;
147198090Srdivacky    GlobalAddressMap.erase(I);
148198090Srdivacky  }
149198090Srdivacky
150198090Srdivacky  GlobalAddressReverseMap.erase(OldVal);
151198090Srdivacky  return OldVal;
152198090Srdivacky}
153198090Srdivacky
154193323Sedvoid ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
155193323Sed  MutexGuard locked(lock);
156193323Sed
157218893Sdim  DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
158198090Srdivacky        << "\' to [" << Addr << "]\n";);
159198892Srdivacky  void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
160193323Sed  assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
161193323Sed  CurVal = Addr;
162218893Sdim
163218893Sdim  // If we are using the reverse mapping, add it too.
164198090Srdivacky  if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
165198090Srdivacky    AssertingVH<const GlobalValue> &V =
166198090Srdivacky      EEState.getGlobalAddressReverseMap(locked)[Addr];
167193323Sed    assert((V == 0 || GV == 0) && "GlobalMapping already established!");
168193323Sed    V = GV;
169193323Sed  }
170193323Sed}
171193323Sed
172193323Sedvoid ExecutionEngine::clearAllGlobalMappings() {
173193323Sed  MutexGuard locked(lock);
174218893Sdim
175198090Srdivacky  EEState.getGlobalAddressMap(locked).clear();
176198090Srdivacky  EEState.getGlobalAddressReverseMap(locked).clear();
177193323Sed}
178193323Sed
179193323Sedvoid ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
180193323Sed  MutexGuard locked(lock);
181218893Sdim
182218893Sdim  for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
183198090Srdivacky    EEState.RemoveMapping(locked, FI);
184218893Sdim  for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
185218893Sdim       GI != GE; ++GI)
186198090Srdivacky    EEState.RemoveMapping(locked, GI);
187193323Sed}
188193323Sed
189193323Sedvoid *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
190193323Sed  MutexGuard locked(lock);
191193323Sed
192198892Srdivacky  ExecutionEngineState::GlobalAddressMapTy &Map =
193198090Srdivacky    EEState.getGlobalAddressMap(locked);
194193323Sed
195193323Sed  // Deleting from the mapping?
196218893Sdim  if (Addr == 0)
197198090Srdivacky    return EEState.RemoveMapping(locked, GV);
198218893Sdim
199198892Srdivacky  void *&CurVal = Map[GV];
200193323Sed  void *OldVal = CurVal;
201193323Sed
202198090Srdivacky  if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
203198090Srdivacky    EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
204193323Sed  CurVal = Addr;
205218893Sdim
206218893Sdim  // If we are using the reverse mapping, add it too.
207198090Srdivacky  if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
208198090Srdivacky    AssertingVH<const GlobalValue> &V =
209198090Srdivacky      EEState.getGlobalAddressReverseMap(locked)[Addr];
210193323Sed    assert((V == 0 || GV == 0) && "GlobalMapping already established!");
211193323Sed    V = GV;
212193323Sed  }
213193323Sed  return OldVal;
214193323Sed}
215193323Sed
216193323Sedvoid *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
217193323Sed  MutexGuard locked(lock);
218218893Sdim
219198892Srdivacky  ExecutionEngineState::GlobalAddressMapTy::iterator I =
220198892Srdivacky    EEState.getGlobalAddressMap(locked).find(GV);
221198090Srdivacky  return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
222193323Sed}
223193323Sed
224193323Sedconst GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
225193323Sed  MutexGuard locked(lock);
226193323Sed
227193323Sed  // If we haven't computed the reverse mapping yet, do so first.
228198090Srdivacky  if (EEState.getGlobalAddressReverseMap(locked).empty()) {
229198892Srdivacky    for (ExecutionEngineState::GlobalAddressMapTy::iterator
230198090Srdivacky         I = EEState.getGlobalAddressMap(locked).begin(),
231198090Srdivacky         E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
232218893Sdim      EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
233218893Sdim                                                          I->second, I->first));
234193323Sed  }
235193323Sed
236198090Srdivacky  std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
237198090Srdivacky    EEState.getGlobalAddressReverseMap(locked).find(Addr);
238198090Srdivacky  return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
239193323Sed}
240193323Sed
241206083Srdivackynamespace {
242206083Srdivackyclass ArgvArray {
243206083Srdivacky  char *Array;
244206083Srdivacky  std::vector<char*> Values;
245206083Srdivackypublic:
246206083Srdivacky  ArgvArray() : Array(NULL) {}
247206083Srdivacky  ~ArgvArray() { clear(); }
248206083Srdivacky  void clear() {
249206083Srdivacky    delete[] Array;
250206083Srdivacky    Array = NULL;
251206083Srdivacky    for (size_t I = 0, E = Values.size(); I != E; ++I) {
252206083Srdivacky      delete[] Values[I];
253206083Srdivacky    }
254206083Srdivacky    Values.clear();
255206083Srdivacky  }
256206083Srdivacky  /// Turn a vector of strings into a nice argv style array of pointers to null
257206083Srdivacky  /// terminated strings.
258206083Srdivacky  void *reset(LLVMContext &C, ExecutionEngine *EE,
259206083Srdivacky              const std::vector<std::string> &InputArgv);
260206083Srdivacky};
261206083Srdivacky}  // anonymous namespace
262206083Srdivackyvoid *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
263206083Srdivacky                       const std::vector<std::string> &InputArgv) {
264206083Srdivacky  clear();  // Free the old contents.
265245431Sdim  unsigned PtrSize = EE->getDataLayout()->getPointerSize();
266206083Srdivacky  Array = new char[(InputArgv.size()+1)*PtrSize];
267193323Sed
268206083Srdivacky  DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
269226890Sdim  Type *SBytePtr = Type::getInt8PtrTy(C);
270193323Sed
271193323Sed  for (unsigned i = 0; i != InputArgv.size(); ++i) {
272193323Sed    unsigned Size = InputArgv[i].size()+1;
273193323Sed    char *Dest = new char[Size];
274206083Srdivacky    Values.push_back(Dest);
275202375Srdivacky    DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
276193323Sed
277193323Sed    std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
278193323Sed    Dest[Size-1] = 0;
279193323Sed
280206083Srdivacky    // Endian safe: Array[i] = (PointerTy)Dest;
281206083Srdivacky    EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
282193323Sed                           SBytePtr);
283193323Sed  }
284193323Sed
285193323Sed  // Null terminate it
286193323Sed  EE->StoreValueToMemory(PTOGV(0),
287206083Srdivacky                         (GenericValue*)(Array+InputArgv.size()*PtrSize),
288193323Sed                         SBytePtr);
289206083Srdivacky  return Array;
290193323Sed}
291193323Sed
292198090Srdivackyvoid ExecutionEngine::runStaticConstructorsDestructors(Module *module,
293198090Srdivacky                                                       bool isDtors) {
294193323Sed  const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
295218893Sdim  GlobalVariable *GV = module->getNamedGlobal(Name);
296193323Sed
297218893Sdim  // If this global has internal linkage, or if it has a use, then it must be
298218893Sdim  // an old-style (llvmgcc3) static ctor with __main linked in and in use.  If
299218893Sdim  // this is the case, don't execute any of the global ctors, __main will do
300218893Sdim  // it.
301218893Sdim  if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
302218893Sdim
303221345Sdim  // Should be an array of '{ i32, void ()* }' structs.  The first value is
304218893Sdim  // the init priority, which we ignore.
305235633Sdim  ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
306235633Sdim  if (InitList == 0)
307221345Sdim    return;
308218893Sdim  for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
309235633Sdim    ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
310235633Sdim    if (CS == 0) continue;
311218893Sdim
312218893Sdim    Constant *FP = CS->getOperand(1);
313218893Sdim    if (FP->isNullValue())
314221345Sdim      continue;  // Found a sentinal value, ignore.
315218893Sdim
316218893Sdim    // Strip off constant expression casts.
317218893Sdim    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
318218893Sdim      if (CE->isCast())
319218893Sdim        FP = CE->getOperand(0);
320218893Sdim
321218893Sdim    // Execute the ctor/dtor function!
322218893Sdim    if (Function *F = dyn_cast<Function>(FP))
323218893Sdim      runFunction(F, std::vector<GenericValue>());
324218893Sdim
325218893Sdim    // FIXME: It is marginally lame that we just do nothing here if we see an
326218893Sdim    // entry we don't recognize. It might not be unreasonable for the verifier
327218893Sdim    // to not even allow this and just assert here.
328218893Sdim  }
329193323Sed}
330193323Sed
331193323Sedvoid ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
332193323Sed  // Execute global ctors/dtors for each module in the program.
333218893Sdim  for (unsigned i = 0, e = Modules.size(); i != e; ++i)
334218893Sdim    runStaticConstructorsDestructors(Modules[i], isDtors);
335193323Sed}
336193323Sed
337193323Sed#ifndef NDEBUG
338193323Sed/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
339193323Sedstatic bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
340245431Sdim  unsigned PtrSize = EE->getDataLayout()->getPointerSize();
341193323Sed  for (unsigned i = 0; i < PtrSize; ++i)
342193323Sed    if (*(i + (uint8_t*)Loc))
343193323Sed      return false;
344193323Sed  return true;
345193323Sed}
346193323Sed#endif
347193323Sed
348193323Sedint ExecutionEngine::runFunctionAsMain(Function *Fn,
349193323Sed                                       const std::vector<std::string> &argv,
350193323Sed                                       const char * const * envp) {
351193323Sed  std::vector<GenericValue> GVArgs;
352193323Sed  GenericValue GVArgc;
353193323Sed  GVArgc.IntVal = APInt(32, argv.size());
354193323Sed
355193323Sed  // Check main() type
356193323Sed  unsigned NumArgs = Fn->getFunctionType()->getNumParams();
357226890Sdim  FunctionType *FTy = Fn->getFunctionType();
358226890Sdim  Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
359218893Sdim
360218893Sdim  // Check the argument types.
361218893Sdim  if (NumArgs > 3)
362218893Sdim    report_fatal_error("Invalid number of arguments of main() supplied");
363218893Sdim  if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
364218893Sdim    report_fatal_error("Invalid type for third argument of main() supplied");
365218893Sdim  if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
366218893Sdim    report_fatal_error("Invalid type for second argument of main() supplied");
367218893Sdim  if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
368218893Sdim    report_fatal_error("Invalid type for first argument of main() supplied");
369218893Sdim  if (!FTy->getReturnType()->isIntegerTy() &&
370218893Sdim      !FTy->getReturnType()->isVoidTy())
371218893Sdim    report_fatal_error("Invalid return type of main() supplied");
372218893Sdim
373206083Srdivacky  ArgvArray CArgv;
374206083Srdivacky  ArgvArray CEnv;
375193323Sed  if (NumArgs) {
376193323Sed    GVArgs.push_back(GVArgc); // Arg #0 = argc.
377193323Sed    if (NumArgs > 1) {
378198090Srdivacky      // Arg #1 = argv.
379206083Srdivacky      GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
380193323Sed      assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
381193323Sed             "argv[0] was null after CreateArgv");
382193323Sed      if (NumArgs > 2) {
383193323Sed        std::vector<std::string> EnvVars;
384193323Sed        for (unsigned i = 0; envp[i]; ++i)
385193323Sed          EnvVars.push_back(envp[i]);
386198090Srdivacky        // Arg #2 = envp.
387206083Srdivacky        GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
388193323Sed      }
389193323Sed    }
390193323Sed  }
391218893Sdim
392193323Sed  return runFunction(Fn, GVArgs).IntVal.getZExtValue();
393193323Sed}
394193323Sed
395203954SrdivackyExecutionEngine *ExecutionEngine::create(Module *M,
396193323Sed                                         bool ForceInterpreter,
397193323Sed                                         std::string *ErrorStr,
398198090Srdivacky                                         CodeGenOpt::Level OptLevel,
399198090Srdivacky                                         bool GVsWithCode) {
400235633Sdim  EngineBuilder EB =  EngineBuilder(M)
401198090Srdivacky      .setEngineKind(ForceInterpreter
402198090Srdivacky                     ? EngineKind::Interpreter
403198090Srdivacky                     : EngineKind::JIT)
404198090Srdivacky      .setErrorStr(ErrorStr)
405198090Srdivacky      .setOptLevel(OptLevel)
406235633Sdim      .setAllocateGVsWithCode(GVsWithCode);
407235633Sdim
408235633Sdim  return EB.create();
409198090Srdivacky}
410193323Sed
411223017Sdim/// createJIT - This is the factory method for creating a JIT for the current
412223017Sdim/// machine, it does not fall back to the interpreter.  This takes ownership
413223017Sdim/// of the module.
414223017SdimExecutionEngine *ExecutionEngine::createJIT(Module *M,
415223017Sdim                                            std::string *ErrorStr,
416223017Sdim                                            JITMemoryManager *JMM,
417235633Sdim                                            CodeGenOpt::Level OL,
418223017Sdim                                            bool GVsWithCode,
419226890Sdim                                            Reloc::Model RM,
420223017Sdim                                            CodeModel::Model CMM) {
421223017Sdim  if (ExecutionEngine::JITCtor == 0) {
422223017Sdim    if (ErrorStr)
423223017Sdim      *ErrorStr = "JIT has not been linked in.";
424223017Sdim    return 0;
425223017Sdim  }
426223017Sdim
427223017Sdim  // Use the defaults for extra parameters.  Users can use EngineBuilder to
428223017Sdim  // set them.
429235633Sdim  EngineBuilder EB(M);
430235633Sdim  EB.setEngineKind(EngineKind::JIT);
431235633Sdim  EB.setErrorStr(ErrorStr);
432235633Sdim  EB.setRelocationModel(RM);
433235633Sdim  EB.setCodeModel(CMM);
434235633Sdim  EB.setAllocateGVsWithCode(GVsWithCode);
435235633Sdim  EB.setOptLevel(OL);
436235633Sdim  EB.setJITMemoryManager(JMM);
437223017Sdim
438235633Sdim  // TODO: permit custom TargetOptions here
439235633Sdim  TargetMachine *TM = EB.selectTarget();
440223017Sdim  if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
441223017Sdim
442235633Sdim  return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
443223017Sdim}
444223017Sdim
445235633SdimExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
446235633Sdim  OwningPtr<TargetMachine> TheTM(TM); // Take ownership.
447235633Sdim
448193323Sed  // Make sure we can resolve symbols in the program as well. The zero arg
449193323Sed  // to the function tells DynamicLibrary to load the program, not a library.
450193323Sed  if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
451193323Sed    return 0;
452193323Sed
453263509Sdim  assert(!(JMM && MCJMM));
454263509Sdim
455198090Srdivacky  // If the user specified a memory manager but didn't specify which engine to
456198090Srdivacky  // create, we assume they only want the JIT, and we fail if they only want
457198090Srdivacky  // the interpreter.
458263509Sdim  if (JMM || MCJMM) {
459198090Srdivacky    if (WhichEngine & EngineKind::JIT)
460198090Srdivacky      WhichEngine = EngineKind::JIT;
461198090Srdivacky    else {
462198090Srdivacky      if (ErrorStr)
463198090Srdivacky        *ErrorStr = "Cannot create an interpreter with a memory manager.";
464198090Srdivacky      return 0;
465198090Srdivacky    }
466198090Srdivacky  }
467263509Sdim
468263509Sdim  if (MCJMM && ! UseMCJIT) {
469263509Sdim    if (ErrorStr)
470263509Sdim      *ErrorStr =
471263509Sdim        "Cannot create a legacy JIT with a runtime dyld memory "
472263509Sdim        "manager.";
473263509Sdim    return 0;
474263509Sdim  }
475193323Sed
476198090Srdivacky  // Unless the interpreter was explicitly selected or the JIT is not linked,
477198090Srdivacky  // try making a JIT.
478235633Sdim  if ((WhichEngine & EngineKind::JIT) && TheTM) {
479235633Sdim    Triple TT(M->getTargetTriple());
480235633Sdim    if (!TM->getTarget().hasJIT()) {
481235633Sdim      errs() << "WARNING: This target JIT is not designed for the host"
482235633Sdim             << " you are running.  If bad things happen, please choose"
483235633Sdim             << " a different -march switch.\n";
484198090Srdivacky    }
485235633Sdim
486235633Sdim    if (UseMCJIT && ExecutionEngine::MCJITCtor) {
487235633Sdim      ExecutionEngine *EE =
488263509Sdim        ExecutionEngine::MCJITCtor(M, ErrorStr, MCJMM ? MCJMM : JMM,
489235633Sdim                                   AllocateGVsWithCode, TheTM.take());
490235633Sdim      if (EE) return EE;
491235633Sdim    } else if (ExecutionEngine::JITCtor) {
492235633Sdim      ExecutionEngine *EE =
493235633Sdim        ExecutionEngine::JITCtor(M, ErrorStr, JMM,
494235633Sdim                                 AllocateGVsWithCode, TheTM.take());
495235633Sdim      if (EE) return EE;
496235633Sdim    }
497198090Srdivacky  }
498193323Sed
499198090Srdivacky  // If we can't make a JIT and we didn't request one specifically, try making
500198090Srdivacky  // an interpreter instead.
501198090Srdivacky  if (WhichEngine & EngineKind::Interpreter) {
502198090Srdivacky    if (ExecutionEngine::InterpCtor)
503203954Srdivacky      return ExecutionEngine::InterpCtor(M, ErrorStr);
504198090Srdivacky    if (ErrorStr)
505198090Srdivacky      *ErrorStr = "Interpreter has not been linked in.";
506198090Srdivacky    return 0;
507198090Srdivacky  }
508193323Sed
509245431Sdim  if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0 &&
510245431Sdim      ExecutionEngine::MCJITCtor == 0) {
511198090Srdivacky    if (ErrorStr)
512198090Srdivacky      *ErrorStr = "JIT has not been linked in.";
513218893Sdim  }
514218893Sdim
515198090Srdivacky  return 0;
516193323Sed}
517193323Sed
518193323Sedvoid *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
519193323Sed  if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
520193323Sed    return getPointerToFunction(F);
521193323Sed
522193323Sed  MutexGuard locked(lock);
523218893Sdim  if (void *P = EEState.getGlobalAddressMap(locked)[GV])
524218893Sdim    return P;
525193323Sed
526193323Sed  // Global variable might have been added since interpreter started.
527193323Sed  if (GlobalVariable *GVar =
528193323Sed          const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
529193323Sed    EmitGlobalVariable(GVar);
530193323Sed  else
531198090Srdivacky    llvm_unreachable("Global hasn't had an address allocated yet!");
532218893Sdim
533198892Srdivacky  return EEState.getGlobalAddressMap(locked)[GV];
534193323Sed}
535193323Sed
536218893Sdim/// \brief Converts a Constant* into a GenericValue, including handling of
537218893Sdim/// ConstantExpr values.
538193323SedGenericValue ExecutionEngine::getConstantValue(const Constant *C) {
539193323Sed  // If its undefined, return the garbage.
540202375Srdivacky  if (isa<UndefValue>(C)) {
541202375Srdivacky    GenericValue Result;
542202375Srdivacky    switch (C->getType()->getTypeID()) {
543252723Sdim    default:
544252723Sdim      break;
545202375Srdivacky    case Type::IntegerTyID:
546202375Srdivacky    case Type::X86_FP80TyID:
547202375Srdivacky    case Type::FP128TyID:
548202375Srdivacky    case Type::PPC_FP128TyID:
549202375Srdivacky      // Although the value is undefined, we still have to construct an APInt
550202375Srdivacky      // with the correct bit width.
551202375Srdivacky      Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
552202375Srdivacky      break;
553263509Sdim    case Type::StructTyID: {
554263509Sdim      // if the whole struct is 'undef' just reserve memory for the value.
555263509Sdim      if(StructType *STy = dyn_cast<StructType>(C->getType())) {
556263509Sdim        unsigned int elemNum = STy->getNumElements();
557263509Sdim        Result.AggregateVal.resize(elemNum);
558263509Sdim        for (unsigned int i = 0; i < elemNum; ++i) {
559263509Sdim          Type *ElemTy = STy->getElementType(i);
560263509Sdim          if (ElemTy->isIntegerTy())
561263509Sdim            Result.AggregateVal[i].IntVal =
562263509Sdim              APInt(ElemTy->getPrimitiveSizeInBits(), 0);
563263509Sdim          else if (ElemTy->isAggregateType()) {
564263509Sdim              const Constant *ElemUndef = UndefValue::get(ElemTy);
565263509Sdim              Result.AggregateVal[i] = getConstantValue(ElemUndef);
566263509Sdim            }
567263509Sdim          }
568263509Sdim        }
569263509Sdim      }
570263509Sdim      break;
571252723Sdim    case Type::VectorTyID:
572252723Sdim      // if the whole vector is 'undef' just reserve memory for the value.
573252723Sdim      const VectorType* VTy = dyn_cast<VectorType>(C->getType());
574252723Sdim      const Type *ElemTy = VTy->getElementType();
575252723Sdim      unsigned int elemNum = VTy->getNumElements();
576252723Sdim      Result.AggregateVal.resize(elemNum);
577252723Sdim      if (ElemTy->isIntegerTy())
578252723Sdim        for (unsigned int i = 0; i < elemNum; ++i)
579263509Sdim          Result.AggregateVal[i].IntVal =
580252723Sdim            APInt(ElemTy->getPrimitiveSizeInBits(), 0);
581202375Srdivacky      break;
582202375Srdivacky    }
583202375Srdivacky    return Result;
584202375Srdivacky  }
585193323Sed
586218893Sdim  // Otherwise, if the value is a ConstantExpr...
587193323Sed  if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
588193323Sed    Constant *Op0 = CE->getOperand(0);
589193323Sed    switch (CE->getOpcode()) {
590193323Sed    case Instruction::GetElementPtr: {
591218893Sdim      // Compute the index
592193323Sed      GenericValue Result = getConstantValue(Op0);
593252723Sdim      APInt Offset(TD->getPointerSizeInBits(), 0);
594252723Sdim      cast<GEPOperator>(CE)->accumulateConstantOffset(*TD, Offset);
595193323Sed
596193323Sed      char* tmp = (char*) Result.PointerVal;
597252723Sdim      Result = PTOGV(tmp + Offset.getSExtValue());
598193323Sed      return Result;
599193323Sed    }
600193323Sed    case Instruction::Trunc: {
601193323Sed      GenericValue GV = getConstantValue(Op0);
602193323Sed      uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
603193323Sed      GV.IntVal = GV.IntVal.trunc(BitWidth);
604193323Sed      return GV;
605193323Sed    }
606193323Sed    case Instruction::ZExt: {
607193323Sed      GenericValue GV = getConstantValue(Op0);
608193323Sed      uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
609193323Sed      GV.IntVal = GV.IntVal.zext(BitWidth);
610193323Sed      return GV;
611193323Sed    }
612193323Sed    case Instruction::SExt: {
613193323Sed      GenericValue GV = getConstantValue(Op0);
614193323Sed      uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
615193323Sed      GV.IntVal = GV.IntVal.sext(BitWidth);
616193323Sed      return GV;
617193323Sed    }
618193323Sed    case Instruction::FPTrunc: {
619193323Sed      // FIXME long double
620193323Sed      GenericValue GV = getConstantValue(Op0);
621193323Sed      GV.FloatVal = float(GV.DoubleVal);
622193323Sed      return GV;
623193323Sed    }
624193323Sed    case Instruction::FPExt:{
625193323Sed      // FIXME long double
626193323Sed      GenericValue GV = getConstantValue(Op0);
627193323Sed      GV.DoubleVal = double(GV.FloatVal);
628193323Sed      return GV;
629193323Sed    }
630193323Sed    case Instruction::UIToFP: {
631193323Sed      GenericValue GV = getConstantValue(Op0);
632198090Srdivacky      if (CE->getType()->isFloatTy())
633193323Sed        GV.FloatVal = float(GV.IntVal.roundToDouble());
634198090Srdivacky      else if (CE->getType()->isDoubleTy())
635193323Sed        GV.DoubleVal = GV.IntVal.roundToDouble();
636198090Srdivacky      else if (CE->getType()->isX86_FP80Ty()) {
637218893Sdim        APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
638218893Sdim        (void)apf.convertFromAPInt(GV.IntVal,
639193323Sed                                   false,
640193323Sed                                   APFloat::rmNearestTiesToEven);
641193323Sed        GV.IntVal = apf.bitcastToAPInt();
642193323Sed      }
643193323Sed      return GV;
644193323Sed    }
645193323Sed    case Instruction::SIToFP: {
646193323Sed      GenericValue GV = getConstantValue(Op0);
647198090Srdivacky      if (CE->getType()->isFloatTy())
648193323Sed        GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
649198090Srdivacky      else if (CE->getType()->isDoubleTy())
650193323Sed        GV.DoubleVal = GV.IntVal.signedRoundToDouble();
651198090Srdivacky      else if (CE->getType()->isX86_FP80Ty()) {
652218893Sdim        APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
653218893Sdim        (void)apf.convertFromAPInt(GV.IntVal,
654193323Sed                                   true,
655193323Sed                                   APFloat::rmNearestTiesToEven);
656193323Sed        GV.IntVal = apf.bitcastToAPInt();
657193323Sed      }
658193323Sed      return GV;
659193323Sed    }
660193323Sed    case Instruction::FPToUI: // double->APInt conversion handles sign
661193323Sed    case Instruction::FPToSI: {
662193323Sed      GenericValue GV = getConstantValue(Op0);
663193323Sed      uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
664198090Srdivacky      if (Op0->getType()->isFloatTy())
665193323Sed        GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
666198090Srdivacky      else if (Op0->getType()->isDoubleTy())
667193323Sed        GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
668198090Srdivacky      else if (Op0->getType()->isX86_FP80Ty()) {
669252723Sdim        APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
670193323Sed        uint64_t v;
671193323Sed        bool ignored;
672193323Sed        (void)apf.convertToInteger(&v, BitWidth,
673218893Sdim                                   CE->getOpcode()==Instruction::FPToSI,
674193323Sed                                   APFloat::rmTowardZero, &ignored);
675193323Sed        GV.IntVal = v; // endian?
676193323Sed      }
677193323Sed      return GV;
678193323Sed    }
679193323Sed    case Instruction::PtrToInt: {
680193323Sed      GenericValue GV = getConstantValue(Op0);
681245431Sdim      uint32_t PtrWidth = TD->getTypeSizeInBits(Op0->getType());
682245431Sdim      assert(PtrWidth <= 64 && "Bad pointer width");
683193323Sed      GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
684245431Sdim      uint32_t IntWidth = TD->getTypeSizeInBits(CE->getType());
685245431Sdim      GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
686193323Sed      return GV;
687193323Sed    }
688193323Sed    case Instruction::IntToPtr: {
689193323Sed      GenericValue GV = getConstantValue(Op0);
690245431Sdim      uint32_t PtrWidth = TD->getTypeSizeInBits(CE->getType());
691245431Sdim      GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
692193323Sed      assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
693193323Sed      GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
694193323Sed      return GV;
695193323Sed    }
696193323Sed    case Instruction::BitCast: {
697193323Sed      GenericValue GV = getConstantValue(Op0);
698226890Sdim      Type* DestTy = CE->getType();
699193323Sed      switch (Op0->getType()->getTypeID()) {
700198090Srdivacky        default: llvm_unreachable("Invalid bitcast operand");
701193323Sed        case Type::IntegerTyID:
702203954Srdivacky          assert(DestTy->isFloatingPointTy() && "invalid bitcast");
703198090Srdivacky          if (DestTy->isFloatTy())
704193323Sed            GV.FloatVal = GV.IntVal.bitsToFloat();
705198090Srdivacky          else if (DestTy->isDoubleTy())
706193323Sed            GV.DoubleVal = GV.IntVal.bitsToDouble();
707193323Sed          break;
708218893Sdim        case Type::FloatTyID:
709203954Srdivacky          assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
710218893Sdim          GV.IntVal = APInt::floatToBits(GV.FloatVal);
711193323Sed          break;
712193323Sed        case Type::DoubleTyID:
713203954Srdivacky          assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
714218893Sdim          GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
715193323Sed          break;
716193323Sed        case Type::PointerTyID:
717204642Srdivacky          assert(DestTy->isPointerTy() && "Invalid bitcast");
718193323Sed          break; // getConstantValue(Op0)  above already converted it
719193323Sed      }
720193323Sed      return GV;
721193323Sed    }
722193323Sed    case Instruction::Add:
723193574Sed    case Instruction::FAdd:
724193323Sed    case Instruction::Sub:
725193574Sed    case Instruction::FSub:
726193323Sed    case Instruction::Mul:
727193574Sed    case Instruction::FMul:
728193323Sed    case Instruction::UDiv:
729193323Sed    case Instruction::SDiv:
730193323Sed    case Instruction::URem:
731193323Sed    case Instruction::SRem:
732193323Sed    case Instruction::And:
733193323Sed    case Instruction::Or:
734193323Sed    case Instruction::Xor: {
735193323Sed      GenericValue LHS = getConstantValue(Op0);
736193323Sed      GenericValue RHS = getConstantValue(CE->getOperand(1));
737193323Sed      GenericValue GV;
738193323Sed      switch (CE->getOperand(0)->getType()->getTypeID()) {
739198090Srdivacky      default: llvm_unreachable("Bad add type!");
740193323Sed      case Type::IntegerTyID:
741193323Sed        switch (CE->getOpcode()) {
742198090Srdivacky          default: llvm_unreachable("Invalid integer opcode");
743193323Sed          case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
744193323Sed          case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
745193323Sed          case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
746193323Sed          case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
747193323Sed          case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
748193323Sed          case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
749193323Sed          case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
750193323Sed          case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
751193323Sed          case Instruction::Or:  GV.IntVal = LHS.IntVal | RHS.IntVal; break;
752193323Sed          case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
753193323Sed        }
754193323Sed        break;
755193323Sed      case Type::FloatTyID:
756193323Sed        switch (CE->getOpcode()) {
757198090Srdivacky          default: llvm_unreachable("Invalid float opcode");
758193574Sed          case Instruction::FAdd:
759193323Sed            GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
760193574Sed          case Instruction::FSub:
761193323Sed            GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
762193574Sed          case Instruction::FMul:
763193323Sed            GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
764218893Sdim          case Instruction::FDiv:
765193323Sed            GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
766218893Sdim          case Instruction::FRem:
767208599Srdivacky            GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
768193323Sed        }
769193323Sed        break;
770193323Sed      case Type::DoubleTyID:
771193323Sed        switch (CE->getOpcode()) {
772198090Srdivacky          default: llvm_unreachable("Invalid double opcode");
773193574Sed          case Instruction::FAdd:
774193323Sed            GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
775193574Sed          case Instruction::FSub:
776193323Sed            GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
777193574Sed          case Instruction::FMul:
778193323Sed            GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
779218893Sdim          case Instruction::FDiv:
780193323Sed            GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
781218893Sdim          case Instruction::FRem:
782208599Srdivacky            GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
783193323Sed        }
784193323Sed        break;
785193323Sed      case Type::X86_FP80TyID:
786193323Sed      case Type::PPC_FP128TyID:
787193323Sed      case Type::FP128TyID: {
788252723Sdim        const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
789252723Sdim        APFloat apfLHS = APFloat(Sem, LHS.IntVal);
790193323Sed        switch (CE->getOpcode()) {
791218893Sdim          default: llvm_unreachable("Invalid long double opcode");
792193574Sed          case Instruction::FAdd:
793252723Sdim            apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
794193323Sed            GV.IntVal = apfLHS.bitcastToAPInt();
795193323Sed            break;
796193574Sed          case Instruction::FSub:
797252723Sdim            apfLHS.subtract(APFloat(Sem, RHS.IntVal),
798252723Sdim                            APFloat::rmNearestTiesToEven);
799193323Sed            GV.IntVal = apfLHS.bitcastToAPInt();
800193323Sed            break;
801193574Sed          case Instruction::FMul:
802252723Sdim            apfLHS.multiply(APFloat(Sem, RHS.IntVal),
803252723Sdim                            APFloat::rmNearestTiesToEven);
804193323Sed            GV.IntVal = apfLHS.bitcastToAPInt();
805193323Sed            break;
806218893Sdim          case Instruction::FDiv:
807252723Sdim            apfLHS.divide(APFloat(Sem, RHS.IntVal),
808252723Sdim                          APFloat::rmNearestTiesToEven);
809193323Sed            GV.IntVal = apfLHS.bitcastToAPInt();
810193323Sed            break;
811218893Sdim          case Instruction::FRem:
812252723Sdim            apfLHS.mod(APFloat(Sem, RHS.IntVal),
813252723Sdim                       APFloat::rmNearestTiesToEven);
814193323Sed            GV.IntVal = apfLHS.bitcastToAPInt();
815193323Sed            break;
816193323Sed          }
817193323Sed        }
818193323Sed        break;
819193323Sed      }
820193323Sed      return GV;
821193323Sed    }
822193323Sed    default:
823193323Sed      break;
824193323Sed    }
825218893Sdim
826218893Sdim    SmallString<256> Msg;
827218893Sdim    raw_svector_ostream OS(Msg);
828218893Sdim    OS << "ConstantExpr not handled: " << *CE;
829218893Sdim    report_fatal_error(OS.str());
830193323Sed  }
831193323Sed
832218893Sdim  // Otherwise, we have a simple constant.
833193323Sed  GenericValue Result;
834193323Sed  switch (C->getType()->getTypeID()) {
835218893Sdim  case Type::FloatTyID:
836218893Sdim    Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
837193323Sed    break;
838193323Sed  case Type::DoubleTyID:
839193323Sed    Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
840193323Sed    break;
841193323Sed  case Type::X86_FP80TyID:
842193323Sed  case Type::FP128TyID:
843193323Sed  case Type::PPC_FP128TyID:
844193323Sed    Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
845193323Sed    break;
846193323Sed  case Type::IntegerTyID:
847193323Sed    Result.IntVal = cast<ConstantInt>(C)->getValue();
848193323Sed    break;
849193323Sed  case Type::PointerTyID:
850193323Sed    if (isa<ConstantPointerNull>(C))
851193323Sed      Result.PointerVal = 0;
852193323Sed    else if (const Function *F = dyn_cast<Function>(C))
853193323Sed      Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
854198892Srdivacky    else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
855193323Sed      Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
856198892Srdivacky    else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
857198892Srdivacky      Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
858198892Srdivacky                                                        BA->getBasicBlock())));
859193323Sed    else
860198090Srdivacky      llvm_unreachable("Unknown constant pointer type!");
861193323Sed    break;
862252723Sdim  case Type::VectorTyID: {
863252723Sdim    unsigned elemNum;
864252723Sdim    Type* ElemTy;
865252723Sdim    const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
866252723Sdim    const ConstantVector *CV = dyn_cast<ConstantVector>(C);
867252723Sdim    const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
868252723Sdim
869252723Sdim    if (CDV) {
870252723Sdim        elemNum = CDV->getNumElements();
871252723Sdim        ElemTy = CDV->getElementType();
872252723Sdim    } else if (CV || CAZ) {
873252723Sdim        VectorType* VTy = dyn_cast<VectorType>(C->getType());
874252723Sdim        elemNum = VTy->getNumElements();
875252723Sdim        ElemTy = VTy->getElementType();
876252723Sdim    } else {
877252723Sdim        llvm_unreachable("Unknown constant vector type!");
878252723Sdim    }
879252723Sdim
880252723Sdim    Result.AggregateVal.resize(elemNum);
881252723Sdim    // Check if vector holds floats.
882252723Sdim    if(ElemTy->isFloatTy()) {
883252723Sdim      if (CAZ) {
884252723Sdim        GenericValue floatZero;
885252723Sdim        floatZero.FloatVal = 0.f;
886252723Sdim        std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
887252723Sdim                  floatZero);
888252723Sdim        break;
889252723Sdim      }
890252723Sdim      if(CV) {
891252723Sdim        for (unsigned i = 0; i < elemNum; ++i)
892252723Sdim          if (!isa<UndefValue>(CV->getOperand(i)))
893252723Sdim            Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
894252723Sdim              CV->getOperand(i))->getValueAPF().convertToFloat();
895252723Sdim        break;
896252723Sdim      }
897252723Sdim      if(CDV)
898252723Sdim        for (unsigned i = 0; i < elemNum; ++i)
899252723Sdim          Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
900252723Sdim
901252723Sdim      break;
902252723Sdim    }
903252723Sdim    // Check if vector holds doubles.
904252723Sdim    if (ElemTy->isDoubleTy()) {
905252723Sdim      if (CAZ) {
906252723Sdim        GenericValue doubleZero;
907252723Sdim        doubleZero.DoubleVal = 0.0;
908252723Sdim        std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
909252723Sdim                  doubleZero);
910252723Sdim        break;
911252723Sdim      }
912252723Sdim      if(CV) {
913252723Sdim        for (unsigned i = 0; i < elemNum; ++i)
914252723Sdim          if (!isa<UndefValue>(CV->getOperand(i)))
915252723Sdim            Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
916252723Sdim              CV->getOperand(i))->getValueAPF().convertToDouble();
917252723Sdim        break;
918252723Sdim      }
919252723Sdim      if(CDV)
920252723Sdim        for (unsigned i = 0; i < elemNum; ++i)
921252723Sdim          Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
922252723Sdim
923252723Sdim      break;
924252723Sdim    }
925252723Sdim    // Check if vector holds integers.
926252723Sdim    if (ElemTy->isIntegerTy()) {
927252723Sdim      if (CAZ) {
928252723Sdim        GenericValue intZero;
929252723Sdim        intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
930252723Sdim        std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
931252723Sdim                  intZero);
932252723Sdim        break;
933252723Sdim      }
934252723Sdim      if(CV) {
935252723Sdim        for (unsigned i = 0; i < elemNum; ++i)
936252723Sdim          if (!isa<UndefValue>(CV->getOperand(i)))
937252723Sdim            Result.AggregateVal[i].IntVal = cast<ConstantInt>(
938252723Sdim                                            CV->getOperand(i))->getValue();
939252723Sdim          else {
940252723Sdim            Result.AggregateVal[i].IntVal =
941252723Sdim              APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
942252723Sdim          }
943252723Sdim        break;
944252723Sdim      }
945252723Sdim      if(CDV)
946252723Sdim        for (unsigned i = 0; i < elemNum; ++i)
947252723Sdim          Result.AggregateVal[i].IntVal = APInt(
948252723Sdim            CDV->getElementType()->getPrimitiveSizeInBits(),
949252723Sdim            CDV->getElementAsInteger(i));
950252723Sdim
951252723Sdim      break;
952252723Sdim    }
953252723Sdim    llvm_unreachable("Unknown constant pointer type!");
954252723Sdim  }
955252723Sdim  break;
956252723Sdim
957193323Sed  default:
958218893Sdim    SmallString<256> Msg;
959218893Sdim    raw_svector_ostream OS(Msg);
960218893Sdim    OS << "ERROR: Constant unimplemented for type: " << *C->getType();
961218893Sdim    report_fatal_error(OS.str());
962193323Sed  }
963218893Sdim
964193323Sed  return Result;
965193323Sed}
966193323Sed
967193323Sed/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
968193323Sed/// with the integer held in IntVal.
969193323Sedstatic void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
970193323Sed                             unsigned StoreBytes) {
971193323Sed  assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
972245431Sdim  const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
973193323Sed
974252723Sdim  if (sys::IsLittleEndianHost) {
975193323Sed    // Little-endian host - the source is ordered from LSB to MSB.  Order the
976193323Sed    // destination from LSB to MSB: Do a straight copy.
977193323Sed    memcpy(Dst, Src, StoreBytes);
978218893Sdim  } else {
979193323Sed    // Big-endian host - the source is an array of 64 bit words ordered from
980193323Sed    // LSW to MSW.  Each word is ordered from MSB to LSB.  Order the destination
981193323Sed    // from MSB to LSB: Reverse the word order, but not the bytes in a word.
982193323Sed    while (StoreBytes > sizeof(uint64_t)) {
983193323Sed      StoreBytes -= sizeof(uint64_t);
984193323Sed      // May not be aligned so use memcpy.
985193323Sed      memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
986193323Sed      Src += sizeof(uint64_t);
987193323Sed    }
988193323Sed
989193323Sed    memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
990193323Sed  }
991193323Sed}
992193323Sed
993193323Sedvoid ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
994226890Sdim                                         GenericValue *Ptr, Type *Ty) {
995245431Sdim  const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
996193323Sed
997193323Sed  switch (Ty->getTypeID()) {
998252723Sdim  default:
999252723Sdim    dbgs() << "Cannot store value of type " << *Ty << "!\n";
1000252723Sdim    break;
1001193323Sed  case Type::IntegerTyID:
1002193323Sed    StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
1003193323Sed    break;
1004193323Sed  case Type::FloatTyID:
1005193323Sed    *((float*)Ptr) = Val.FloatVal;
1006193323Sed    break;
1007193323Sed  case Type::DoubleTyID:
1008193323Sed    *((double*)Ptr) = Val.DoubleVal;
1009193323Sed    break;
1010193323Sed  case Type::X86_FP80TyID:
1011193323Sed    memcpy(Ptr, Val.IntVal.getRawData(), 10);
1012193323Sed    break;
1013193323Sed  case Type::PointerTyID:
1014193323Sed    // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1015193323Sed    if (StoreBytes != sizeof(PointerTy))
1016221345Sdim      memset(&(Ptr->PointerVal), 0, StoreBytes);
1017193323Sed
1018193323Sed    *((PointerTy*)Ptr) = Val.PointerVal;
1019193323Sed    break;
1020252723Sdim  case Type::VectorTyID:
1021252723Sdim    for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1022252723Sdim      if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1023252723Sdim        *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1024252723Sdim      if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1025252723Sdim        *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1026252723Sdim      if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1027252723Sdim        unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1028252723Sdim        StoreIntToMemory(Val.AggregateVal[i].IntVal,
1029252723Sdim          (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1030252723Sdim      }
1031252723Sdim    }
1032252723Sdim    break;
1033193323Sed  }
1034193323Sed
1035252723Sdim  if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
1036193323Sed    // Host and target are different endian - reverse the stored bytes.
1037193323Sed    std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1038193323Sed}
1039193323Sed
1040193323Sed/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1041193323Sed/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1042193323Sedstatic void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1043193323Sed  assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
1044252723Sdim  uint8_t *Dst = reinterpret_cast<uint8_t *>(
1045252723Sdim                   const_cast<uint64_t *>(IntVal.getRawData()));
1046193323Sed
1047252723Sdim  if (sys::IsLittleEndianHost)
1048193323Sed    // Little-endian host - the destination must be ordered from LSB to MSB.
1049193323Sed    // The source is ordered from LSB to MSB: Do a straight copy.
1050193323Sed    memcpy(Dst, Src, LoadBytes);
1051193323Sed  else {
1052193323Sed    // Big-endian - the destination is an array of 64 bit words ordered from
1053193323Sed    // LSW to MSW.  Each word must be ordered from MSB to LSB.  The source is
1054193323Sed    // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1055193323Sed    // a word.
1056193323Sed    while (LoadBytes > sizeof(uint64_t)) {
1057193323Sed      LoadBytes -= sizeof(uint64_t);
1058193323Sed      // May not be aligned so use memcpy.
1059193323Sed      memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1060193323Sed      Dst += sizeof(uint64_t);
1061193323Sed    }
1062193323Sed
1063193323Sed    memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1064193323Sed  }
1065193323Sed}
1066193323Sed
1067193323Sed/// FIXME: document
1068193323Sed///
1069193323Sedvoid ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
1070193323Sed                                          GenericValue *Ptr,
1071226890Sdim                                          Type *Ty) {
1072245431Sdim  const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
1073193323Sed
1074193323Sed  switch (Ty->getTypeID()) {
1075193323Sed  case Type::IntegerTyID:
1076193323Sed    // An APInt with all words initially zero.
1077193323Sed    Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1078193323Sed    LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1079193323Sed    break;
1080193323Sed  case Type::FloatTyID:
1081193323Sed    Result.FloatVal = *((float*)Ptr);
1082193323Sed    break;
1083193323Sed  case Type::DoubleTyID:
1084193323Sed    Result.DoubleVal = *((double*)Ptr);
1085193323Sed    break;
1086193323Sed  case Type::PointerTyID:
1087193323Sed    Result.PointerVal = *((PointerTy*)Ptr);
1088193323Sed    break;
1089193323Sed  case Type::X86_FP80TyID: {
1090193323Sed    // This is endian dependent, but it will only work on x86 anyway.
1091193323Sed    // FIXME: Will not trap if loading a signaling NaN.
1092193323Sed    uint64_t y[2];
1093193323Sed    memcpy(y, Ptr, 10);
1094226890Sdim    Result.IntVal = APInt(80, y);
1095193323Sed    break;
1096193323Sed  }
1097252723Sdim  case Type::VectorTyID: {
1098252723Sdim    const VectorType *VT = cast<VectorType>(Ty);
1099252723Sdim    const Type *ElemT = VT->getElementType();
1100252723Sdim    const unsigned numElems = VT->getNumElements();
1101252723Sdim    if (ElemT->isFloatTy()) {
1102252723Sdim      Result.AggregateVal.resize(numElems);
1103252723Sdim      for (unsigned i = 0; i < numElems; ++i)
1104252723Sdim        Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1105252723Sdim    }
1106252723Sdim    if (ElemT->isDoubleTy()) {
1107252723Sdim      Result.AggregateVal.resize(numElems);
1108252723Sdim      for (unsigned i = 0; i < numElems; ++i)
1109252723Sdim        Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1110252723Sdim    }
1111252723Sdim    if (ElemT->isIntegerTy()) {
1112252723Sdim      GenericValue intZero;
1113252723Sdim      const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1114252723Sdim      intZero.IntVal = APInt(elemBitWidth, 0);
1115252723Sdim      Result.AggregateVal.resize(numElems, intZero);
1116252723Sdim      for (unsigned i = 0; i < numElems; ++i)
1117252723Sdim        LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1118252723Sdim          (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1119252723Sdim    }
1120252723Sdim  break;
1121252723Sdim  }
1122193323Sed  default:
1123218893Sdim    SmallString<256> Msg;
1124218893Sdim    raw_svector_ostream OS(Msg);
1125218893Sdim    OS << "Cannot load value of type " << *Ty << "!";
1126218893Sdim    report_fatal_error(OS.str());
1127193323Sed  }
1128193323Sed}
1129193323Sed
1130193323Sedvoid ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
1131202375Srdivacky  DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
1132193323Sed  DEBUG(Init->dump());
1133235633Sdim  if (isa<UndefValue>(Init))
1134193323Sed    return;
1135235633Sdim
1136235633Sdim  if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
1137193323Sed    unsigned ElementSize =
1138245431Sdim      getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
1139193323Sed    for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1140193323Sed      InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1141193323Sed    return;
1142235633Sdim  }
1143235633Sdim
1144235633Sdim  if (isa<ConstantAggregateZero>(Init)) {
1145245431Sdim    memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
1146193323Sed    return;
1147235633Sdim  }
1148235633Sdim
1149235633Sdim  if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
1150193323Sed    unsigned ElementSize =
1151245431Sdim      getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
1152193323Sed    for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1153193323Sed      InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1154193323Sed    return;
1155235633Sdim  }
1156235633Sdim
1157235633Sdim  if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
1158193323Sed    const StructLayout *SL =
1159245431Sdim      getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
1160193323Sed    for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1161193323Sed      InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1162193323Sed    return;
1163235633Sdim  }
1164235633Sdim
1165235633Sdim  if (const ConstantDataSequential *CDS =
1166235633Sdim               dyn_cast<ConstantDataSequential>(Init)) {
1167235633Sdim    // CDS is already laid out in host memory order.
1168235633Sdim    StringRef Data = CDS->getRawDataValues();
1169235633Sdim    memcpy(Addr, Data.data(), Data.size());
1170235633Sdim    return;
1171235633Sdim  }
1172235633Sdim
1173235633Sdim  if (Init->getType()->isFirstClassType()) {
1174193323Sed    GenericValue Val = getConstantValue(Init);
1175193323Sed    StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1176193323Sed    return;
1177193323Sed  }
1178193323Sed
1179218893Sdim  DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1180198090Srdivacky  llvm_unreachable("Unknown constant type to initialize memory with!");
1181193323Sed}
1182193323Sed
1183193323Sed/// EmitGlobals - Emit all of the global variables to memory, storing their
1184193323Sed/// addresses into GlobalAddress.  This must make sure to copy the contents of
1185193323Sed/// their initializers into the memory.
1186193323Sedvoid ExecutionEngine::emitGlobals() {
1187193323Sed  // Loop over all of the global variables in the program, allocating the memory
1188193323Sed  // to hold them.  If there is more than one module, do a prepass over globals
1189193323Sed  // to figure out how the different modules should link together.
1190226890Sdim  std::map<std::pair<std::string, Type*>,
1191193323Sed           const GlobalValue*> LinkedGlobalsMap;
1192193323Sed
1193193323Sed  if (Modules.size() != 1) {
1194193323Sed    for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1195203954Srdivacky      Module &M = *Modules[m];
1196193323Sed      for (Module::const_global_iterator I = M.global_begin(),
1197193323Sed           E = M.global_end(); I != E; ++I) {
1198193323Sed        const GlobalValue *GV = I;
1199193323Sed        if (GV->hasLocalLinkage() || GV->isDeclaration() ||
1200193323Sed            GV->hasAppendingLinkage() || !GV->hasName())
1201193323Sed          continue;// Ignore external globals and globals with internal linkage.
1202218893Sdim
1203218893Sdim        const GlobalValue *&GVEntry =
1204193323Sed          LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1205193323Sed
1206193323Sed        // If this is the first time we've seen this global, it is the canonical
1207193323Sed        // version.
1208193323Sed        if (!GVEntry) {
1209193323Sed          GVEntry = GV;
1210193323Sed          continue;
1211193323Sed        }
1212218893Sdim
1213193323Sed        // If the existing global is strong, never replace it.
1214193323Sed        if (GVEntry->hasExternalLinkage() ||
1215193323Sed            GVEntry->hasDLLImportLinkage() ||
1216193323Sed            GVEntry->hasDLLExportLinkage())
1217193323Sed          continue;
1218218893Sdim
1219193323Sed        // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1220193323Sed        // symbol.  FIXME is this right for common?
1221193323Sed        if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1222193323Sed          GVEntry = GV;
1223193323Sed      }
1224193323Sed    }
1225193323Sed  }
1226218893Sdim
1227193323Sed  std::vector<const GlobalValue*> NonCanonicalGlobals;
1228193323Sed  for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1229203954Srdivacky    Module &M = *Modules[m];
1230193323Sed    for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1231193323Sed         I != E; ++I) {
1232193323Sed      // In the multi-module case, see what this global maps to.
1233193323Sed      if (!LinkedGlobalsMap.empty()) {
1234218893Sdim        if (const GlobalValue *GVEntry =
1235193323Sed              LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1236193323Sed          // If something else is the canonical global, ignore this one.
1237193323Sed          if (GVEntry != &*I) {
1238193323Sed            NonCanonicalGlobals.push_back(I);
1239193323Sed            continue;
1240193323Sed          }
1241193323Sed        }
1242193323Sed      }
1243218893Sdim
1244193323Sed      if (!I->isDeclaration()) {
1245193323Sed        addGlobalMapping(I, getMemoryForGV(I));
1246193323Sed      } else {
1247193323Sed        // External variable reference. Try to use the dynamic loader to
1248193323Sed        // get a pointer to it.
1249193323Sed        if (void *SymAddr =
1250198090Srdivacky            sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1251193323Sed          addGlobalMapping(I, SymAddr);
1252193323Sed        else {
1253207618Srdivacky          report_fatal_error("Could not resolve external global address: "
1254198090Srdivacky                            +I->getName());
1255193323Sed        }
1256193323Sed      }
1257193323Sed    }
1258218893Sdim
1259193323Sed    // If there are multiple modules, map the non-canonical globals to their
1260193323Sed    // canonical location.
1261193323Sed    if (!NonCanonicalGlobals.empty()) {
1262193323Sed      for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1263193323Sed        const GlobalValue *GV = NonCanonicalGlobals[i];
1264193323Sed        const GlobalValue *CGV =
1265193323Sed          LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1266193323Sed        void *Ptr = getPointerToGlobalIfAvailable(CGV);
1267193323Sed        assert(Ptr && "Canonical global wasn't codegen'd!");
1268193323Sed        addGlobalMapping(GV, Ptr);
1269193323Sed      }
1270193323Sed    }
1271218893Sdim
1272218893Sdim    // Now that all of the globals are set up in memory, loop through them all
1273193323Sed    // and initialize their contents.
1274193323Sed    for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1275193323Sed         I != E; ++I) {
1276193323Sed      if (!I->isDeclaration()) {
1277193323Sed        if (!LinkedGlobalsMap.empty()) {
1278218893Sdim          if (const GlobalValue *GVEntry =
1279193323Sed                LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1280193323Sed            if (GVEntry != &*I)  // Not the canonical variable.
1281193323Sed              continue;
1282193323Sed        }
1283193323Sed        EmitGlobalVariable(I);
1284193323Sed      }
1285193323Sed    }
1286193323Sed  }
1287193323Sed}
1288193323Sed
1289193323Sed// EmitGlobalVariable - This method emits the specified global variable to the
1290193323Sed// address specified in GlobalAddresses, or allocates new memory if it's not
1291193323Sed// already in the map.
1292193323Sedvoid ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1293193323Sed  void *GA = getPointerToGlobalIfAvailable(GV);
1294193323Sed
1295193323Sed  if (GA == 0) {
1296193323Sed    // If it's not already specified, allocate memory for the global.
1297193323Sed    GA = getMemoryForGV(GV);
1298263509Sdim
1299263509Sdim    // If we failed to allocate memory for this global, return.
1300263509Sdim    if (GA == 0) return;
1301263509Sdim
1302193323Sed    addGlobalMapping(GV, GA);
1303193323Sed  }
1304218893Sdim
1305193323Sed  // Don't initialize if it's thread local, let the client do it.
1306193323Sed  if (!GV->isThreadLocal())
1307193323Sed    InitializeMemory(GV->getInitializer(), GA);
1308218893Sdim
1309226890Sdim  Type *ElTy = GV->getType()->getElementType();
1310245431Sdim  size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
1311193323Sed  NumInitBytes += (unsigned)GVSize;
1312193323Sed  ++NumGlobals;
1313193323Sed}
1314198090Srdivacky
1315198892SrdivackyExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1316198892Srdivacky  : EE(EE), GlobalAddressMap(this) {
1317198892Srdivacky}
1318198090Srdivacky
1319218893Sdimsys::Mutex *
1320218893SdimExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1321198892Srdivacky  return &EES->EE.lock;
1322198090Srdivacky}
1323218893Sdim
1324218893Sdimvoid ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1325218893Sdim                                                      const GlobalValue *Old) {
1326198892Srdivacky  void *OldVal = EES->GlobalAddressMap.lookup(Old);
1327198892Srdivacky  EES->GlobalAddressReverseMap.erase(OldVal);
1328198892Srdivacky}
1329198090Srdivacky
1330218893Sdimvoid ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1331218893Sdim                                                    const GlobalValue *,
1332218893Sdim                                                    const GlobalValue *) {
1333235633Sdim  llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1334235633Sdim                   " RAUW on a value it has a global mapping for.");
1335198090Srdivacky}
1336