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