ExecutionEngine.cpp revision db125cfaf57cc83e7dd7453de2d509bc8efd0e5e
1//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// 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/ExecutionEngine/ExecutionEngine.h"
17
18#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Module.h"
21#include "llvm/ExecutionEngine/GenericValue.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/MutexGuard.h"
27#include "llvm/Support/ValueHandle.h"
28#include "llvm/Support/raw_ostream.h"
29#include "llvm/Support/DynamicLibrary.h"
30#include "llvm/Support/Host.h"
31#include "llvm/Target/TargetData.h"
32#include "llvm/Target/TargetMachine.h"
33#include <cmath>
34#include <cstring>
35using namespace llvm;
36
37STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
38STATISTIC(NumGlobals  , "Number of global vars initialized");
39
40ExecutionEngine *(*ExecutionEngine::JITCtor)(
41  Module *M,
42  std::string *ErrorStr,
43  JITMemoryManager *JMM,
44  CodeGenOpt::Level OptLevel,
45  bool GVsWithCode,
46  TargetMachine *TM) = 0;
47ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
48  Module *M,
49  std::string *ErrorStr,
50  JITMemoryManager *JMM,
51  CodeGenOpt::Level OptLevel,
52  bool GVsWithCode,
53  TargetMachine *TM) = 0;
54ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
55                                                std::string *ErrorStr) = 0;
56
57ExecutionEngine::ExecutionEngine(Module *M)
58  : EEState(*this),
59    LazyFunctionCreator(0),
60    ExceptionTableRegister(0),
61    ExceptionTableDeregister(0) {
62  CompilingLazily         = false;
63  GVCompilationDisabled   = false;
64  SymbolSearchingDisabled = false;
65  Modules.push_back(M);
66  assert(M && "Module is null?");
67}
68
69ExecutionEngine::~ExecutionEngine() {
70  clearAllGlobalMappings();
71  for (unsigned i = 0, e = Modules.size(); i != e; ++i)
72    delete Modules[i];
73}
74
75void ExecutionEngine::DeregisterAllTables() {
76  if (ExceptionTableDeregister) {
77    DenseMap<const Function*, void*>::iterator it = AllExceptionTables.begin();
78    DenseMap<const Function*, void*>::iterator ite = AllExceptionTables.end();
79    for (; it != ite; ++it)
80      ExceptionTableDeregister(it->second);
81    AllExceptionTables.clear();
82  }
83}
84
85namespace {
86/// \brief Helper class which uses a value handler to automatically deletes the
87/// memory block when the GlobalVariable is destroyed.
88class GVMemoryBlock : public CallbackVH {
89  GVMemoryBlock(const GlobalVariable *GV)
90    : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
91
92public:
93  /// \brief Returns the address the GlobalVariable should be written into.  The
94  /// GVMemoryBlock object prefixes that.
95  static char *Create(const GlobalVariable *GV, const TargetData& TD) {
96    Type *ElTy = GV->getType()->getElementType();
97    size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
98    void *RawMemory = ::operator new(
99      TargetData::RoundUpAlignment(sizeof(GVMemoryBlock),
100                                   TD.getPreferredAlignment(GV))
101      + GVSize);
102    new(RawMemory) GVMemoryBlock(GV);
103    return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
104  }
105
106  virtual void deleted() {
107    // We allocated with operator new and with some extra memory hanging off the
108    // end, so don't just delete this.  I'm not sure if this is actually
109    // required.
110    this->~GVMemoryBlock();
111    ::operator delete(this);
112  }
113};
114}  // anonymous namespace
115
116char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
117  return GVMemoryBlock::Create(GV, *getTargetData());
118}
119
120bool ExecutionEngine::removeModule(Module *M) {
121  for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
122        E = Modules.end(); I != E; ++I) {
123    Module *Found = *I;
124    if (Found == M) {
125      Modules.erase(I);
126      clearGlobalMappingsFromModule(M);
127      return true;
128    }
129  }
130  return false;
131}
132
133Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
134  for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
135    if (Function *F = Modules[i]->getFunction(FnName))
136      return F;
137  }
138  return 0;
139}
140
141
142void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
143                                          const GlobalValue *ToUnmap) {
144  GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
145  void *OldVal;
146
147  // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
148  // GlobalAddressMap.
149  if (I == GlobalAddressMap.end())
150    OldVal = 0;
151  else {
152    OldVal = I->second;
153    GlobalAddressMap.erase(I);
154  }
155
156  GlobalAddressReverseMap.erase(OldVal);
157  return OldVal;
158}
159
160void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
161  MutexGuard locked(lock);
162
163  DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
164        << "\' to [" << Addr << "]\n";);
165  void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
166  assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
167  CurVal = Addr;
168
169  // If we are using the reverse mapping, add it too.
170  if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
171    AssertingVH<const GlobalValue> &V =
172      EEState.getGlobalAddressReverseMap(locked)[Addr];
173    assert((V == 0 || GV == 0) && "GlobalMapping already established!");
174    V = GV;
175  }
176}
177
178void ExecutionEngine::clearAllGlobalMappings() {
179  MutexGuard locked(lock);
180
181  EEState.getGlobalAddressMap(locked).clear();
182  EEState.getGlobalAddressReverseMap(locked).clear();
183}
184
185void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
186  MutexGuard locked(lock);
187
188  for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
189    EEState.RemoveMapping(locked, FI);
190  for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
191       GI != GE; ++GI)
192    EEState.RemoveMapping(locked, GI);
193}
194
195void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
196  MutexGuard locked(lock);
197
198  ExecutionEngineState::GlobalAddressMapTy &Map =
199    EEState.getGlobalAddressMap(locked);
200
201  // Deleting from the mapping?
202  if (Addr == 0)
203    return EEState.RemoveMapping(locked, GV);
204
205  void *&CurVal = Map[GV];
206  void *OldVal = CurVal;
207
208  if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
209    EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
210  CurVal = Addr;
211
212  // If we are using the reverse mapping, add it too.
213  if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
214    AssertingVH<const GlobalValue> &V =
215      EEState.getGlobalAddressReverseMap(locked)[Addr];
216    assert((V == 0 || GV == 0) && "GlobalMapping already established!");
217    V = GV;
218  }
219  return OldVal;
220}
221
222void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
223  MutexGuard locked(lock);
224
225  ExecutionEngineState::GlobalAddressMapTy::iterator I =
226    EEState.getGlobalAddressMap(locked).find(GV);
227  return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
228}
229
230const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
231  MutexGuard locked(lock);
232
233  // If we haven't computed the reverse mapping yet, do so first.
234  if (EEState.getGlobalAddressReverseMap(locked).empty()) {
235    for (ExecutionEngineState::GlobalAddressMapTy::iterator
236         I = EEState.getGlobalAddressMap(locked).begin(),
237         E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
238      EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
239                                                          I->second, I->first));
240  }
241
242  std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
243    EEState.getGlobalAddressReverseMap(locked).find(Addr);
244  return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
245}
246
247namespace {
248class ArgvArray {
249  char *Array;
250  std::vector<char*> Values;
251public:
252  ArgvArray() : Array(NULL) {}
253  ~ArgvArray() { clear(); }
254  void clear() {
255    delete[] Array;
256    Array = NULL;
257    for (size_t I = 0, E = Values.size(); I != E; ++I) {
258      delete[] Values[I];
259    }
260    Values.clear();
261  }
262  /// Turn a vector of strings into a nice argv style array of pointers to null
263  /// terminated strings.
264  void *reset(LLVMContext &C, ExecutionEngine *EE,
265              const std::vector<std::string> &InputArgv);
266};
267}  // anonymous namespace
268void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
269                       const std::vector<std::string> &InputArgv) {
270  clear();  // Free the old contents.
271  unsigned PtrSize = EE->getTargetData()->getPointerSize();
272  Array = new char[(InputArgv.size()+1)*PtrSize];
273
274  DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
275  Type *SBytePtr = Type::getInt8PtrTy(C);
276
277  for (unsigned i = 0; i != InputArgv.size(); ++i) {
278    unsigned Size = InputArgv[i].size()+1;
279    char *Dest = new char[Size];
280    Values.push_back(Dest);
281    DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
282
283    std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
284    Dest[Size-1] = 0;
285
286    // Endian safe: Array[i] = (PointerTy)Dest;
287    EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
288                           SBytePtr);
289  }
290
291  // Null terminate it
292  EE->StoreValueToMemory(PTOGV(0),
293                         (GenericValue*)(Array+InputArgv.size()*PtrSize),
294                         SBytePtr);
295  return Array;
296}
297
298void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
299                                                       bool isDtors) {
300  const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
301  GlobalVariable *GV = module->getNamedGlobal(Name);
302
303  // If this global has internal linkage, or if it has a use, then it must be
304  // an old-style (llvmgcc3) static ctor with __main linked in and in use.  If
305  // this is the case, don't execute any of the global ctors, __main will do
306  // it.
307  if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
308
309  // Should be an array of '{ i32, void ()* }' structs.  The first value is
310  // the init priority, which we ignore.
311  if (isa<ConstantAggregateZero>(GV->getInitializer()))
312    return;
313  ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer());
314  for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
315    if (isa<ConstantAggregateZero>(InitList->getOperand(i)))
316      continue;
317    ConstantStruct *CS = cast<ConstantStruct>(InitList->getOperand(i));
318
319    Constant *FP = CS->getOperand(1);
320    if (FP->isNullValue())
321      continue;  // Found a sentinal value, ignore.
322
323    // Strip off constant expression casts.
324    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
325      if (CE->isCast())
326        FP = CE->getOperand(0);
327
328    // Execute the ctor/dtor function!
329    if (Function *F = dyn_cast<Function>(FP))
330      runFunction(F, std::vector<GenericValue>());
331
332    // FIXME: It is marginally lame that we just do nothing here if we see an
333    // entry we don't recognize. It might not be unreasonable for the verifier
334    // to not even allow this and just assert here.
335  }
336}
337
338void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
339  // Execute global ctors/dtors for each module in the program.
340  for (unsigned i = 0, e = Modules.size(); i != e; ++i)
341    runStaticConstructorsDestructors(Modules[i], isDtors);
342}
343
344#ifndef NDEBUG
345/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
346static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
347  unsigned PtrSize = EE->getTargetData()->getPointerSize();
348  for (unsigned i = 0; i < PtrSize; ++i)
349    if (*(i + (uint8_t*)Loc))
350      return false;
351  return true;
352}
353#endif
354
355int ExecutionEngine::runFunctionAsMain(Function *Fn,
356                                       const std::vector<std::string> &argv,
357                                       const char * const * envp) {
358  std::vector<GenericValue> GVArgs;
359  GenericValue GVArgc;
360  GVArgc.IntVal = APInt(32, argv.size());
361
362  // Check main() type
363  unsigned NumArgs = Fn->getFunctionType()->getNumParams();
364  FunctionType *FTy = Fn->getFunctionType();
365  Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
366
367  // Check the argument types.
368  if (NumArgs > 3)
369    report_fatal_error("Invalid number of arguments of main() supplied");
370  if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
371    report_fatal_error("Invalid type for third argument of main() supplied");
372  if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
373    report_fatal_error("Invalid type for second argument of main() supplied");
374  if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
375    report_fatal_error("Invalid type for first argument of main() supplied");
376  if (!FTy->getReturnType()->isIntegerTy() &&
377      !FTy->getReturnType()->isVoidTy())
378    report_fatal_error("Invalid return type of main() supplied");
379
380  ArgvArray CArgv;
381  ArgvArray CEnv;
382  if (NumArgs) {
383    GVArgs.push_back(GVArgc); // Arg #0 = argc.
384    if (NumArgs > 1) {
385      // Arg #1 = argv.
386      GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
387      assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
388             "argv[0] was null after CreateArgv");
389      if (NumArgs > 2) {
390        std::vector<std::string> EnvVars;
391        for (unsigned i = 0; envp[i]; ++i)
392          EnvVars.push_back(envp[i]);
393        // Arg #2 = envp.
394        GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
395      }
396    }
397  }
398
399  return runFunction(Fn, GVArgs).IntVal.getZExtValue();
400}
401
402ExecutionEngine *ExecutionEngine::create(Module *M,
403                                         bool ForceInterpreter,
404                                         std::string *ErrorStr,
405                                         CodeGenOpt::Level OptLevel,
406                                         bool GVsWithCode) {
407  return EngineBuilder(M)
408      .setEngineKind(ForceInterpreter
409                     ? EngineKind::Interpreter
410                     : EngineKind::JIT)
411      .setErrorStr(ErrorStr)
412      .setOptLevel(OptLevel)
413      .setAllocateGVsWithCode(GVsWithCode)
414      .create();
415}
416
417/// createJIT - This is the factory method for creating a JIT for the current
418/// machine, it does not fall back to the interpreter.  This takes ownership
419/// of the module.
420ExecutionEngine *ExecutionEngine::createJIT(Module *M,
421                                            std::string *ErrorStr,
422                                            JITMemoryManager *JMM,
423                                            CodeGenOpt::Level OptLevel,
424                                            bool GVsWithCode,
425                                            CodeModel::Model CMM) {
426  if (ExecutionEngine::JITCtor == 0) {
427    if (ErrorStr)
428      *ErrorStr = "JIT has not been linked in.";
429    return 0;
430  }
431
432  // Use the defaults for extra parameters.  Users can use EngineBuilder to
433  // set them.
434  StringRef MArch = "";
435  StringRef MCPU = "";
436  SmallVector<std::string, 1> MAttrs;
437
438  TargetMachine *TM =
439          EngineBuilder::selectTarget(M, MArch, MCPU, MAttrs, ErrorStr);
440  if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
441  TM->setCodeModel(CMM);
442
443  return ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel, GVsWithCode, TM);
444}
445
446ExecutionEngine *EngineBuilder::create() {
447  // Make sure we can resolve symbols in the program as well. The zero arg
448  // to the function tells DynamicLibrary to load the program, not a library.
449  if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
450    return 0;
451
452  // If the user specified a memory manager but didn't specify which engine to
453  // create, we assume they only want the JIT, and we fail if they only want
454  // the interpreter.
455  if (JMM) {
456    if (WhichEngine & EngineKind::JIT)
457      WhichEngine = EngineKind::JIT;
458    else {
459      if (ErrorStr)
460        *ErrorStr = "Cannot create an interpreter with a memory manager.";
461      return 0;
462    }
463  }
464
465  // Unless the interpreter was explicitly selected or the JIT is not linked,
466  // try making a JIT.
467  if (WhichEngine & EngineKind::JIT) {
468    if (TargetMachine *TM =
469        EngineBuilder::selectTarget(M, MArch, MCPU, MAttrs, ErrorStr)) {
470      TM->setCodeModel(CMModel);
471
472      if (UseMCJIT && ExecutionEngine::MCJITCtor) {
473        ExecutionEngine *EE =
474          ExecutionEngine::MCJITCtor(M, ErrorStr, JMM, OptLevel,
475                                     AllocateGVsWithCode, TM);
476        if (EE) return EE;
477      } else if (ExecutionEngine::JITCtor) {
478        ExecutionEngine *EE =
479          ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
480                                   AllocateGVsWithCode, TM);
481        if (EE) return EE;
482      }
483    }
484  }
485
486  // If we can't make a JIT and we didn't request one specifically, try making
487  // an interpreter instead.
488  if (WhichEngine & EngineKind::Interpreter) {
489    if (ExecutionEngine::InterpCtor)
490      return ExecutionEngine::InterpCtor(M, ErrorStr);
491    if (ErrorStr)
492      *ErrorStr = "Interpreter has not been linked in.";
493    return 0;
494  }
495
496  if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
497    if (ErrorStr)
498      *ErrorStr = "JIT has not been linked in.";
499  }
500
501  return 0;
502}
503
504void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
505  if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
506    return getPointerToFunction(F);
507
508  MutexGuard locked(lock);
509  if (void *P = EEState.getGlobalAddressMap(locked)[GV])
510    return P;
511
512  // Global variable might have been added since interpreter started.
513  if (GlobalVariable *GVar =
514          const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
515    EmitGlobalVariable(GVar);
516  else
517    llvm_unreachable("Global hasn't had an address allocated yet!");
518
519  return EEState.getGlobalAddressMap(locked)[GV];
520}
521
522/// \brief Converts a Constant* into a GenericValue, including handling of
523/// ConstantExpr values.
524GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
525  // If its undefined, return the garbage.
526  if (isa<UndefValue>(C)) {
527    GenericValue Result;
528    switch (C->getType()->getTypeID()) {
529    case Type::IntegerTyID:
530    case Type::X86_FP80TyID:
531    case Type::FP128TyID:
532    case Type::PPC_FP128TyID:
533      // Although the value is undefined, we still have to construct an APInt
534      // with the correct bit width.
535      Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
536      break;
537    default:
538      break;
539    }
540    return Result;
541  }
542
543  // Otherwise, if the value is a ConstantExpr...
544  if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
545    Constant *Op0 = CE->getOperand(0);
546    switch (CE->getOpcode()) {
547    case Instruction::GetElementPtr: {
548      // Compute the index
549      GenericValue Result = getConstantValue(Op0);
550      SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
551      uint64_t Offset =
552        TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
553
554      char* tmp = (char*) Result.PointerVal;
555      Result = PTOGV(tmp + Offset);
556      return Result;
557    }
558    case Instruction::Trunc: {
559      GenericValue GV = getConstantValue(Op0);
560      uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
561      GV.IntVal = GV.IntVal.trunc(BitWidth);
562      return GV;
563    }
564    case Instruction::ZExt: {
565      GenericValue GV = getConstantValue(Op0);
566      uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
567      GV.IntVal = GV.IntVal.zext(BitWidth);
568      return GV;
569    }
570    case Instruction::SExt: {
571      GenericValue GV = getConstantValue(Op0);
572      uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
573      GV.IntVal = GV.IntVal.sext(BitWidth);
574      return GV;
575    }
576    case Instruction::FPTrunc: {
577      // FIXME long double
578      GenericValue GV = getConstantValue(Op0);
579      GV.FloatVal = float(GV.DoubleVal);
580      return GV;
581    }
582    case Instruction::FPExt:{
583      // FIXME long double
584      GenericValue GV = getConstantValue(Op0);
585      GV.DoubleVal = double(GV.FloatVal);
586      return GV;
587    }
588    case Instruction::UIToFP: {
589      GenericValue GV = getConstantValue(Op0);
590      if (CE->getType()->isFloatTy())
591        GV.FloatVal = float(GV.IntVal.roundToDouble());
592      else if (CE->getType()->isDoubleTy())
593        GV.DoubleVal = GV.IntVal.roundToDouble();
594      else if (CE->getType()->isX86_FP80Ty()) {
595        APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
596        (void)apf.convertFromAPInt(GV.IntVal,
597                                   false,
598                                   APFloat::rmNearestTiesToEven);
599        GV.IntVal = apf.bitcastToAPInt();
600      }
601      return GV;
602    }
603    case Instruction::SIToFP: {
604      GenericValue GV = getConstantValue(Op0);
605      if (CE->getType()->isFloatTy())
606        GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
607      else if (CE->getType()->isDoubleTy())
608        GV.DoubleVal = GV.IntVal.signedRoundToDouble();
609      else if (CE->getType()->isX86_FP80Ty()) {
610        APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
611        (void)apf.convertFromAPInt(GV.IntVal,
612                                   true,
613                                   APFloat::rmNearestTiesToEven);
614        GV.IntVal = apf.bitcastToAPInt();
615      }
616      return GV;
617    }
618    case Instruction::FPToUI: // double->APInt conversion handles sign
619    case Instruction::FPToSI: {
620      GenericValue GV = getConstantValue(Op0);
621      uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
622      if (Op0->getType()->isFloatTy())
623        GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
624      else if (Op0->getType()->isDoubleTy())
625        GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
626      else if (Op0->getType()->isX86_FP80Ty()) {
627        APFloat apf = APFloat(GV.IntVal);
628        uint64_t v;
629        bool ignored;
630        (void)apf.convertToInteger(&v, BitWidth,
631                                   CE->getOpcode()==Instruction::FPToSI,
632                                   APFloat::rmTowardZero, &ignored);
633        GV.IntVal = v; // endian?
634      }
635      return GV;
636    }
637    case Instruction::PtrToInt: {
638      GenericValue GV = getConstantValue(Op0);
639      uint32_t PtrWidth = TD->getPointerSizeInBits();
640      GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
641      return GV;
642    }
643    case Instruction::IntToPtr: {
644      GenericValue GV = getConstantValue(Op0);
645      uint32_t PtrWidth = TD->getPointerSizeInBits();
646      if (PtrWidth != GV.IntVal.getBitWidth())
647        GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
648      assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
649      GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
650      return GV;
651    }
652    case Instruction::BitCast: {
653      GenericValue GV = getConstantValue(Op0);
654      Type* DestTy = CE->getType();
655      switch (Op0->getType()->getTypeID()) {
656        default: llvm_unreachable("Invalid bitcast operand");
657        case Type::IntegerTyID:
658          assert(DestTy->isFloatingPointTy() && "invalid bitcast");
659          if (DestTy->isFloatTy())
660            GV.FloatVal = GV.IntVal.bitsToFloat();
661          else if (DestTy->isDoubleTy())
662            GV.DoubleVal = GV.IntVal.bitsToDouble();
663          break;
664        case Type::FloatTyID:
665          assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
666          GV.IntVal = APInt::floatToBits(GV.FloatVal);
667          break;
668        case Type::DoubleTyID:
669          assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
670          GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
671          break;
672        case Type::PointerTyID:
673          assert(DestTy->isPointerTy() && "Invalid bitcast");
674          break; // getConstantValue(Op0)  above already converted it
675      }
676      return GV;
677    }
678    case Instruction::Add:
679    case Instruction::FAdd:
680    case Instruction::Sub:
681    case Instruction::FSub:
682    case Instruction::Mul:
683    case Instruction::FMul:
684    case Instruction::UDiv:
685    case Instruction::SDiv:
686    case Instruction::URem:
687    case Instruction::SRem:
688    case Instruction::And:
689    case Instruction::Or:
690    case Instruction::Xor: {
691      GenericValue LHS = getConstantValue(Op0);
692      GenericValue RHS = getConstantValue(CE->getOperand(1));
693      GenericValue GV;
694      switch (CE->getOperand(0)->getType()->getTypeID()) {
695      default: llvm_unreachable("Bad add type!");
696      case Type::IntegerTyID:
697        switch (CE->getOpcode()) {
698          default: llvm_unreachable("Invalid integer opcode");
699          case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
700          case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
701          case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
702          case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
703          case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
704          case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
705          case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
706          case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
707          case Instruction::Or:  GV.IntVal = LHS.IntVal | RHS.IntVal; break;
708          case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
709        }
710        break;
711      case Type::FloatTyID:
712        switch (CE->getOpcode()) {
713          default: llvm_unreachable("Invalid float opcode");
714          case Instruction::FAdd:
715            GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
716          case Instruction::FSub:
717            GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
718          case Instruction::FMul:
719            GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
720          case Instruction::FDiv:
721            GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
722          case Instruction::FRem:
723            GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
724        }
725        break;
726      case Type::DoubleTyID:
727        switch (CE->getOpcode()) {
728          default: llvm_unreachable("Invalid double opcode");
729          case Instruction::FAdd:
730            GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
731          case Instruction::FSub:
732            GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
733          case Instruction::FMul:
734            GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
735          case Instruction::FDiv:
736            GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
737          case Instruction::FRem:
738            GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
739        }
740        break;
741      case Type::X86_FP80TyID:
742      case Type::PPC_FP128TyID:
743      case Type::FP128TyID: {
744        APFloat apfLHS = APFloat(LHS.IntVal);
745        switch (CE->getOpcode()) {
746          default: llvm_unreachable("Invalid long double opcode");
747          case Instruction::FAdd:
748            apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
749            GV.IntVal = apfLHS.bitcastToAPInt();
750            break;
751          case Instruction::FSub:
752            apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
753            GV.IntVal = apfLHS.bitcastToAPInt();
754            break;
755          case Instruction::FMul:
756            apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
757            GV.IntVal = apfLHS.bitcastToAPInt();
758            break;
759          case Instruction::FDiv:
760            apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
761            GV.IntVal = apfLHS.bitcastToAPInt();
762            break;
763          case Instruction::FRem:
764            apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
765            GV.IntVal = apfLHS.bitcastToAPInt();
766            break;
767          }
768        }
769        break;
770      }
771      return GV;
772    }
773    default:
774      break;
775    }
776
777    SmallString<256> Msg;
778    raw_svector_ostream OS(Msg);
779    OS << "ConstantExpr not handled: " << *CE;
780    report_fatal_error(OS.str());
781  }
782
783  // Otherwise, we have a simple constant.
784  GenericValue Result;
785  switch (C->getType()->getTypeID()) {
786  case Type::FloatTyID:
787    Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
788    break;
789  case Type::DoubleTyID:
790    Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
791    break;
792  case Type::X86_FP80TyID:
793  case Type::FP128TyID:
794  case Type::PPC_FP128TyID:
795    Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
796    break;
797  case Type::IntegerTyID:
798    Result.IntVal = cast<ConstantInt>(C)->getValue();
799    break;
800  case Type::PointerTyID:
801    if (isa<ConstantPointerNull>(C))
802      Result.PointerVal = 0;
803    else if (const Function *F = dyn_cast<Function>(C))
804      Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
805    else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
806      Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
807    else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
808      Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
809                                                        BA->getBasicBlock())));
810    else
811      llvm_unreachable("Unknown constant pointer type!");
812    break;
813  default:
814    SmallString<256> Msg;
815    raw_svector_ostream OS(Msg);
816    OS << "ERROR: Constant unimplemented for type: " << *C->getType();
817    report_fatal_error(OS.str());
818  }
819
820  return Result;
821}
822
823/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
824/// with the integer held in IntVal.
825static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
826                             unsigned StoreBytes) {
827  assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
828  uint8_t *Src = (uint8_t *)IntVal.getRawData();
829
830  if (sys::isLittleEndianHost()) {
831    // Little-endian host - the source is ordered from LSB to MSB.  Order the
832    // destination from LSB to MSB: Do a straight copy.
833    memcpy(Dst, Src, StoreBytes);
834  } else {
835    // Big-endian host - the source is an array of 64 bit words ordered from
836    // LSW to MSW.  Each word is ordered from MSB to LSB.  Order the destination
837    // from MSB to LSB: Reverse the word order, but not the bytes in a word.
838    while (StoreBytes > sizeof(uint64_t)) {
839      StoreBytes -= sizeof(uint64_t);
840      // May not be aligned so use memcpy.
841      memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
842      Src += sizeof(uint64_t);
843    }
844
845    memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
846  }
847}
848
849void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
850                                         GenericValue *Ptr, Type *Ty) {
851  const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
852
853  switch (Ty->getTypeID()) {
854  case Type::IntegerTyID:
855    StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
856    break;
857  case Type::FloatTyID:
858    *((float*)Ptr) = Val.FloatVal;
859    break;
860  case Type::DoubleTyID:
861    *((double*)Ptr) = Val.DoubleVal;
862    break;
863  case Type::X86_FP80TyID:
864    memcpy(Ptr, Val.IntVal.getRawData(), 10);
865    break;
866  case Type::PointerTyID:
867    // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
868    if (StoreBytes != sizeof(PointerTy))
869      memset(&(Ptr->PointerVal), 0, StoreBytes);
870
871    *((PointerTy*)Ptr) = Val.PointerVal;
872    break;
873  default:
874    dbgs() << "Cannot store value of type " << *Ty << "!\n";
875  }
876
877  if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
878    // Host and target are different endian - reverse the stored bytes.
879    std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
880}
881
882/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
883/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
884static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
885  assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
886  uint8_t *Dst = (uint8_t *)IntVal.getRawData();
887
888  if (sys::isLittleEndianHost())
889    // Little-endian host - the destination must be ordered from LSB to MSB.
890    // The source is ordered from LSB to MSB: Do a straight copy.
891    memcpy(Dst, Src, LoadBytes);
892  else {
893    // Big-endian - the destination is an array of 64 bit words ordered from
894    // LSW to MSW.  Each word must be ordered from MSB to LSB.  The source is
895    // ordered from MSB to LSB: Reverse the word order, but not the bytes in
896    // a word.
897    while (LoadBytes > sizeof(uint64_t)) {
898      LoadBytes -= sizeof(uint64_t);
899      // May not be aligned so use memcpy.
900      memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
901      Dst += sizeof(uint64_t);
902    }
903
904    memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
905  }
906}
907
908/// FIXME: document
909///
910void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
911                                          GenericValue *Ptr,
912                                          Type *Ty) {
913  const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
914
915  switch (Ty->getTypeID()) {
916  case Type::IntegerTyID:
917    // An APInt with all words initially zero.
918    Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
919    LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
920    break;
921  case Type::FloatTyID:
922    Result.FloatVal = *((float*)Ptr);
923    break;
924  case Type::DoubleTyID:
925    Result.DoubleVal = *((double*)Ptr);
926    break;
927  case Type::PointerTyID:
928    Result.PointerVal = *((PointerTy*)Ptr);
929    break;
930  case Type::X86_FP80TyID: {
931    // This is endian dependent, but it will only work on x86 anyway.
932    // FIXME: Will not trap if loading a signaling NaN.
933    uint64_t y[2];
934    memcpy(y, Ptr, 10);
935    Result.IntVal = APInt(80, 2, y);
936    break;
937  }
938  default:
939    SmallString<256> Msg;
940    raw_svector_ostream OS(Msg);
941    OS << "Cannot load value of type " << *Ty << "!";
942    report_fatal_error(OS.str());
943  }
944}
945
946void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
947  DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
948  DEBUG(Init->dump());
949  if (isa<UndefValue>(Init)) {
950    return;
951  } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
952    unsigned ElementSize =
953      getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
954    for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
955      InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
956    return;
957  } else if (isa<ConstantAggregateZero>(Init)) {
958    memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
959    return;
960  } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
961    unsigned ElementSize =
962      getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
963    for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
964      InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
965    return;
966  } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
967    const StructLayout *SL =
968      getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
969    for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
970      InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
971    return;
972  } else if (Init->getType()->isFirstClassType()) {
973    GenericValue Val = getConstantValue(Init);
974    StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
975    return;
976  }
977
978  DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
979  llvm_unreachable("Unknown constant type to initialize memory with!");
980}
981
982/// EmitGlobals - Emit all of the global variables to memory, storing their
983/// addresses into GlobalAddress.  This must make sure to copy the contents of
984/// their initializers into the memory.
985void ExecutionEngine::emitGlobals() {
986  // Loop over all of the global variables in the program, allocating the memory
987  // to hold them.  If there is more than one module, do a prepass over globals
988  // to figure out how the different modules should link together.
989  std::map<std::pair<std::string, Type*>,
990           const GlobalValue*> LinkedGlobalsMap;
991
992  if (Modules.size() != 1) {
993    for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
994      Module &M = *Modules[m];
995      for (Module::const_global_iterator I = M.global_begin(),
996           E = M.global_end(); I != E; ++I) {
997        const GlobalValue *GV = I;
998        if (GV->hasLocalLinkage() || GV->isDeclaration() ||
999            GV->hasAppendingLinkage() || !GV->hasName())
1000          continue;// Ignore external globals and globals with internal linkage.
1001
1002        const GlobalValue *&GVEntry =
1003          LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1004
1005        // If this is the first time we've seen this global, it is the canonical
1006        // version.
1007        if (!GVEntry) {
1008          GVEntry = GV;
1009          continue;
1010        }
1011
1012        // If the existing global is strong, never replace it.
1013        if (GVEntry->hasExternalLinkage() ||
1014            GVEntry->hasDLLImportLinkage() ||
1015            GVEntry->hasDLLExportLinkage())
1016          continue;
1017
1018        // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1019        // symbol.  FIXME is this right for common?
1020        if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1021          GVEntry = GV;
1022      }
1023    }
1024  }
1025
1026  std::vector<const GlobalValue*> NonCanonicalGlobals;
1027  for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1028    Module &M = *Modules[m];
1029    for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1030         I != E; ++I) {
1031      // In the multi-module case, see what this global maps to.
1032      if (!LinkedGlobalsMap.empty()) {
1033        if (const GlobalValue *GVEntry =
1034              LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1035          // If something else is the canonical global, ignore this one.
1036          if (GVEntry != &*I) {
1037            NonCanonicalGlobals.push_back(I);
1038            continue;
1039          }
1040        }
1041      }
1042
1043      if (!I->isDeclaration()) {
1044        addGlobalMapping(I, getMemoryForGV(I));
1045      } else {
1046        // External variable reference. Try to use the dynamic loader to
1047        // get a pointer to it.
1048        if (void *SymAddr =
1049            sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1050          addGlobalMapping(I, SymAddr);
1051        else {
1052          report_fatal_error("Could not resolve external global address: "
1053                            +I->getName());
1054        }
1055      }
1056    }
1057
1058    // If there are multiple modules, map the non-canonical globals to their
1059    // canonical location.
1060    if (!NonCanonicalGlobals.empty()) {
1061      for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1062        const GlobalValue *GV = NonCanonicalGlobals[i];
1063        const GlobalValue *CGV =
1064          LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1065        void *Ptr = getPointerToGlobalIfAvailable(CGV);
1066        assert(Ptr && "Canonical global wasn't codegen'd!");
1067        addGlobalMapping(GV, Ptr);
1068      }
1069    }
1070
1071    // Now that all of the globals are set up in memory, loop through them all
1072    // and initialize their contents.
1073    for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1074         I != E; ++I) {
1075      if (!I->isDeclaration()) {
1076        if (!LinkedGlobalsMap.empty()) {
1077          if (const GlobalValue *GVEntry =
1078                LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1079            if (GVEntry != &*I)  // Not the canonical variable.
1080              continue;
1081        }
1082        EmitGlobalVariable(I);
1083      }
1084    }
1085  }
1086}
1087
1088// EmitGlobalVariable - This method emits the specified global variable to the
1089// address specified in GlobalAddresses, or allocates new memory if it's not
1090// already in the map.
1091void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1092  void *GA = getPointerToGlobalIfAvailable(GV);
1093
1094  if (GA == 0) {
1095    // If it's not already specified, allocate memory for the global.
1096    GA = getMemoryForGV(GV);
1097    addGlobalMapping(GV, GA);
1098  }
1099
1100  // Don't initialize if it's thread local, let the client do it.
1101  if (!GV->isThreadLocal())
1102    InitializeMemory(GV->getInitializer(), GA);
1103
1104  Type *ElTy = GV->getType()->getElementType();
1105  size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
1106  NumInitBytes += (unsigned)GVSize;
1107  ++NumGlobals;
1108}
1109
1110ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1111  : EE(EE), GlobalAddressMap(this) {
1112}
1113
1114sys::Mutex *
1115ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1116  return &EES->EE.lock;
1117}
1118
1119void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1120                                                      const GlobalValue *Old) {
1121  void *OldVal = EES->GlobalAddressMap.lookup(Old);
1122  EES->GlobalAddressReverseMap.erase(OldVal);
1123}
1124
1125void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1126                                                    const GlobalValue *,
1127                                                    const GlobalValue *) {
1128  assert(false && "The ExecutionEngine doesn't know how to handle a"
1129         " RAUW on a value it has a global mapping for.");
1130}
1131