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