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