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