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