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