1857c21b4SMisha Brukman //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===// 2996fe010SChris Lattner // 3482202a6SJohn Criswell // The LLVM Compiler Infrastructure 4482202a6SJohn Criswell // 5f3ebc3f3SChris Lattner // This file is distributed under the University of Illinois Open Source 6f3ebc3f3SChris Lattner // License. See LICENSE.TXT for details. 7482202a6SJohn Criswell // 8482202a6SJohn Criswell //===----------------------------------------------------------------------===// 9482202a6SJohn Criswell // 10996fe010SChris Lattner // This file defines the common interface used by the various execution engine 11996fe010SChris Lattner // subclasses. 12996fe010SChris Lattner // 13996fe010SChris Lattner //===----------------------------------------------------------------------===// 14996fe010SChris Lattner 15ee937c80SChris Lattner #define DEBUG_TYPE "jit" 166bf87df5SJeffrey Yasskin #include "llvm/ExecutionEngine/ExecutionEngine.h" 176bf87df5SJeffrey Yasskin 18996fe010SChris Lattner #include "llvm/Constants.h" 19260b0c88SMisha Brukman #include "llvm/DerivedTypes.h" 20996fe010SChris Lattner #include "llvm/Module.h" 21260b0c88SMisha Brukman #include "llvm/ModuleProvider.h" 22ad481312SChris Lattner #include "llvm/ExecutionEngine/GenericValue.h" 23390d78b3SChris Lattner #include "llvm/ADT/Statistic.h" 247c16caa3SReid Spencer #include "llvm/Support/Debug.h" 256c2d233eSTorok Edwin #include "llvm/Support/ErrorHandling.h" 266d8dd189SChris Lattner #include "llvm/Support/MutexGuard.h" 276bf87df5SJeffrey Yasskin #include "llvm/Support/ValueHandle.h" 28ccb29cd2STorok Edwin #include "llvm/Support/raw_ostream.h" 2970e37278SReid Spencer #include "llvm/System/DynamicLibrary.h" 30fde55674SDuncan Sands #include "llvm/System/Host.h" 3170e37278SReid Spencer #include "llvm/Target/TargetData.h" 32579f0713SAnton Korobeynikov #include <cmath> 33579f0713SAnton Korobeynikov #include <cstring> 3429681deeSChris Lattner using namespace llvm; 35996fe010SChris Lattner 36c346ecd7SChris Lattner STATISTIC(NumInitBytes, "Number of bytes of global vars initialized"); 37c346ecd7SChris Lattner STATISTIC(NumGlobals , "Number of global vars initialized"); 38996fe010SChris Lattner 39fc8a2d5aSReid Kleckner ExecutionEngine *(*ExecutionEngine::JITCtor)(ModuleProvider *MP, 40fc8a2d5aSReid Kleckner std::string *ErrorStr, 41fc8a2d5aSReid Kleckner JITMemoryManager *JMM, 42fc8a2d5aSReid Kleckner CodeGenOpt::Level OptLevel, 43fc8a2d5aSReid Kleckner bool GVsWithCode) = 0; 44fc8a2d5aSReid Kleckner ExecutionEngine *(*ExecutionEngine::InterpCtor)(ModuleProvider *MP, 45fc8a2d5aSReid Kleckner std::string *ErrorStr) = 0; 4621ad494fSNicolas Geoffray ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0; 4721ad494fSNicolas Geoffray 482d52c1b8SChris Lattner 49fd6f3257SChris Lattner ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) { 5087aee74cSChris Lattner LazyCompilationDisabled = false; 51cdc0060eSEvan Cheng GVCompilationDisabled = false; 5284a9055eSEvan Cheng SymbolSearchingDisabled = false; 5318d85e74SNate Begeman DlsymStubsEnabled = false; 540621caefSChris Lattner Modules.push_back(P); 55260b0c88SMisha Brukman assert(P && "ModuleProvider is null?"); 56260b0c88SMisha Brukman } 57260b0c88SMisha Brukman 5892f8b30dSBrian Gaeke ExecutionEngine::~ExecutionEngine() { 59603682adSReid Spencer clearAllGlobalMappings(); 600621caefSChris Lattner for (unsigned i = 0, e = Modules.size(); i != e; ++i) 610621caefSChris Lattner delete Modules[i]; 6292f8b30dSBrian Gaeke } 6392f8b30dSBrian Gaeke 645457ce9aSNicolas Geoffray char* ExecutionEngine::getMemoryForGV(const GlobalVariable* GV) { 655457ce9aSNicolas Geoffray const Type *ElTy = GV->getType()->getElementType(); 66af9eaa83SDuncan Sands size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy); 675457ce9aSNicolas Geoffray return new char[GVSize]; 685457ce9aSNicolas Geoffray } 695457ce9aSNicolas Geoffray 70324fe890SDevang Patel /// removeModuleProvider - Remove a ModuleProvider from the list of modules. 71617001d8SNate Begeman /// Relases the Module from the ModuleProvider, materializing it in the 72617001d8SNate Begeman /// process, and returns the materialized Module. 73324fe890SDevang Patel Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P, 74324fe890SDevang Patel std::string *ErrInfo) { 75324fe890SDevang Patel for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(), 76324fe890SDevang Patel E = Modules.end(); I != E; ++I) { 77324fe890SDevang Patel ModuleProvider *MP = *I; 78324fe890SDevang Patel if (MP == P) { 79324fe890SDevang Patel Modules.erase(I); 808f83fc4dSNate Begeman clearGlobalMappingsFromModule(MP->getModule()); 81324fe890SDevang Patel return MP->releaseModule(ErrInfo); 82324fe890SDevang Patel } 83324fe890SDevang Patel } 84324fe890SDevang Patel return NULL; 85324fe890SDevang Patel } 86324fe890SDevang Patel 87617001d8SNate Begeman /// deleteModuleProvider - Remove a ModuleProvider from the list of modules, 88617001d8SNate Begeman /// and deletes the ModuleProvider and owned Module. Avoids materializing 89617001d8SNate Begeman /// the underlying module. 90617001d8SNate Begeman void ExecutionEngine::deleteModuleProvider(ModuleProvider *P, 91617001d8SNate Begeman std::string *ErrInfo) { 92617001d8SNate Begeman for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(), 93617001d8SNate Begeman E = Modules.end(); I != E; ++I) { 94617001d8SNate Begeman ModuleProvider *MP = *I; 95617001d8SNate Begeman if (MP == P) { 96617001d8SNate Begeman Modules.erase(I); 97617001d8SNate Begeman clearGlobalMappingsFromModule(MP->getModule()); 98617001d8SNate Begeman delete MP; 99617001d8SNate Begeman return; 100617001d8SNate Begeman } 101617001d8SNate Begeman } 102617001d8SNate Begeman } 103617001d8SNate Begeman 1040621caefSChris Lattner /// FindFunctionNamed - Search all of the active modules to find the one that 1050621caefSChris Lattner /// defines FnName. This is very slow operation and shouldn't be used for 1060621caefSChris Lattner /// general code. 1070621caefSChris Lattner Function *ExecutionEngine::FindFunctionNamed(const char *FnName) { 1080621caefSChris Lattner for (unsigned i = 0, e = Modules.size(); i != e; ++i) { 1091241d6d5SReid Spencer if (Function *F = Modules[i]->getModule()->getFunction(FnName)) 1100621caefSChris Lattner return F; 1110621caefSChris Lattner } 1120621caefSChris Lattner return 0; 1130621caefSChris Lattner } 1140621caefSChris Lattner 1150621caefSChris Lattner 1166d8dd189SChris Lattner /// addGlobalMapping - Tell the execution engine that the specified global is 1176d8dd189SChris Lattner /// at the specified location. This is used internally as functions are JIT'd 1186d8dd189SChris Lattner /// and as global variables are laid out in memory. It can and should also be 1196d8dd189SChris Lattner /// used by clients of the EE that want to have an LLVM global overlay 1206d8dd189SChris Lattner /// existing data in memory. 1216d8dd189SChris Lattner void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) { 1226d8dd189SChris Lattner MutexGuard locked(lock); 1236d8dd189SChris Lattner 1249813b0b0SDaniel Dunbar DEBUG(errs() << "JIT: Map \'" << GV->getName() 1259813b0b0SDaniel Dunbar << "\' to [" << Addr << "]\n";); 1266d8dd189SChris Lattner void *&CurVal = state.getGlobalAddressMap(locked)[GV]; 1276d8dd189SChris Lattner assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!"); 1286d8dd189SChris Lattner CurVal = Addr; 1296d8dd189SChris Lattner 1306d8dd189SChris Lattner // If we are using the reverse mapping, add it too 1316d8dd189SChris Lattner if (!state.getGlobalAddressReverseMap(locked).empty()) { 1326bf87df5SJeffrey Yasskin AssertingVH<const GlobalValue> &V = 1336bf87df5SJeffrey Yasskin state.getGlobalAddressReverseMap(locked)[Addr]; 1346d8dd189SChris Lattner assert((V == 0 || GV == 0) && "GlobalMapping already established!"); 1356d8dd189SChris Lattner V = GV; 1366d8dd189SChris Lattner } 1376d8dd189SChris Lattner } 1386d8dd189SChris Lattner 1396d8dd189SChris Lattner /// clearAllGlobalMappings - Clear all global mappings and start over again 1406d8dd189SChris Lattner /// use in dynamic compilation scenarios when you want to move globals 1416d8dd189SChris Lattner void ExecutionEngine::clearAllGlobalMappings() { 1426d8dd189SChris Lattner MutexGuard locked(lock); 1436d8dd189SChris Lattner 1446d8dd189SChris Lattner state.getGlobalAddressMap(locked).clear(); 1456d8dd189SChris Lattner state.getGlobalAddressReverseMap(locked).clear(); 1466d8dd189SChris Lattner } 1476d8dd189SChris Lattner 1488f83fc4dSNate Begeman /// clearGlobalMappingsFromModule - Clear all global mappings that came from a 1498f83fc4dSNate Begeman /// particular module, because it has been removed from the JIT. 1508f83fc4dSNate Begeman void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) { 1518f83fc4dSNate Begeman MutexGuard locked(lock); 1528f83fc4dSNate Begeman 1538f83fc4dSNate Begeman for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) { 1546bf87df5SJeffrey Yasskin state.getGlobalAddressMap(locked).erase(&*FI); 1556bf87df5SJeffrey Yasskin state.getGlobalAddressReverseMap(locked).erase(&*FI); 1568f83fc4dSNate Begeman } 1578f83fc4dSNate Begeman for (Module::global_iterator GI = M->global_begin(), GE = M->global_end(); 1588f83fc4dSNate Begeman GI != GE; ++GI) { 1596bf87df5SJeffrey Yasskin state.getGlobalAddressMap(locked).erase(&*GI); 1606bf87df5SJeffrey Yasskin state.getGlobalAddressReverseMap(locked).erase(&*GI); 1618f83fc4dSNate Begeman } 1628f83fc4dSNate Begeman } 1638f83fc4dSNate Begeman 1646d8dd189SChris Lattner /// updateGlobalMapping - Replace an existing mapping for GV with a new 1656d8dd189SChris Lattner /// address. This updates both maps as required. If "Addr" is null, the 1666d8dd189SChris Lattner /// entry for the global is removed from the mappings. 167ee181730SChris Lattner void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) { 1686d8dd189SChris Lattner MutexGuard locked(lock); 1696d8dd189SChris Lattner 1706bf87df5SJeffrey Yasskin std::map<AssertingVH<const GlobalValue>, void *> &Map = 1716bf87df5SJeffrey Yasskin state.getGlobalAddressMap(locked); 172ee181730SChris Lattner 1736d8dd189SChris Lattner // Deleting from the mapping? 1746d8dd189SChris Lattner if (Addr == 0) { 1756bf87df5SJeffrey Yasskin std::map<AssertingVH<const GlobalValue>, void *>::iterator I = Map.find(GV); 176ee181730SChris Lattner void *OldVal; 177ee181730SChris Lattner if (I == Map.end()) 178ee181730SChris Lattner OldVal = 0; 179ee181730SChris Lattner else { 180ee181730SChris Lattner OldVal = I->second; 181ee181730SChris Lattner Map.erase(I); 1826d8dd189SChris Lattner } 1836d8dd189SChris Lattner 184ee181730SChris Lattner if (!state.getGlobalAddressReverseMap(locked).empty()) 185337b124aSJeffrey Yasskin state.getGlobalAddressReverseMap(locked).erase(OldVal); 186ee181730SChris Lattner return OldVal; 187ee181730SChris Lattner } 188ee181730SChris Lattner 189ee181730SChris Lattner void *&CurVal = Map[GV]; 190ee181730SChris Lattner void *OldVal = CurVal; 191ee181730SChris Lattner 1926d8dd189SChris Lattner if (CurVal && !state.getGlobalAddressReverseMap(locked).empty()) 1936d8dd189SChris Lattner state.getGlobalAddressReverseMap(locked).erase(CurVal); 1946d8dd189SChris Lattner CurVal = Addr; 1956d8dd189SChris Lattner 1966d8dd189SChris Lattner // If we are using the reverse mapping, add it too 1976d8dd189SChris Lattner if (!state.getGlobalAddressReverseMap(locked).empty()) { 1986bf87df5SJeffrey Yasskin AssertingVH<const GlobalValue> &V = 1996bf87df5SJeffrey Yasskin state.getGlobalAddressReverseMap(locked)[Addr]; 2006d8dd189SChris Lattner assert((V == 0 || GV == 0) && "GlobalMapping already established!"); 2016d8dd189SChris Lattner V = GV; 2026d8dd189SChris Lattner } 203ee181730SChris Lattner return OldVal; 2046d8dd189SChris Lattner } 2056d8dd189SChris Lattner 2066d8dd189SChris Lattner /// getPointerToGlobalIfAvailable - This returns the address of the specified 2076d8dd189SChris Lattner /// global value if it is has already been codegen'd, otherwise it returns null. 2086d8dd189SChris Lattner /// 2096d8dd189SChris Lattner void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) { 2106d8dd189SChris Lattner MutexGuard locked(lock); 2116d8dd189SChris Lattner 2126bf87df5SJeffrey Yasskin std::map<AssertingVH<const GlobalValue>, void*>::iterator I = 2136d8dd189SChris Lattner state.getGlobalAddressMap(locked).find(GV); 2146d8dd189SChris Lattner return I != state.getGlobalAddressMap(locked).end() ? I->second : 0; 2156d8dd189SChris Lattner } 2166d8dd189SChris Lattner 217748e8579SChris Lattner /// getGlobalValueAtAddress - Return the LLVM global value object that starts 218748e8579SChris Lattner /// at the specified address. 219748e8579SChris Lattner /// 220748e8579SChris Lattner const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) { 22179876f52SReid Spencer MutexGuard locked(lock); 22279876f52SReid Spencer 223748e8579SChris Lattner // If we haven't computed the reverse mapping yet, do so first. 22479876f52SReid Spencer if (state.getGlobalAddressReverseMap(locked).empty()) { 2256bf87df5SJeffrey Yasskin for (std::map<AssertingVH<const GlobalValue>, void *>::iterator 2266d8dd189SChris Lattner I = state.getGlobalAddressMap(locked).begin(), 2276d8dd189SChris Lattner E = state.getGlobalAddressMap(locked).end(); I != E; ++I) 2286d8dd189SChris Lattner state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second, 2296d8dd189SChris Lattner I->first)); 230748e8579SChris Lattner } 231748e8579SChris Lattner 2326bf87df5SJeffrey Yasskin std::map<void *, AssertingVH<const GlobalValue> >::iterator I = 23379876f52SReid Spencer state.getGlobalAddressReverseMap(locked).find(Addr); 23479876f52SReid Spencer return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0; 235748e8579SChris Lattner } 2365a0d4829SChris Lattner 2375a0d4829SChris Lattner // CreateArgv - Turn a vector of strings into a nice argv style array of 2385a0d4829SChris Lattner // pointers to null terminated strings. 2395a0d4829SChris Lattner // 24055f1c09eSOwen Anderson static void *CreateArgv(LLVMContext &C, ExecutionEngine *EE, 2415a0d4829SChris Lattner const std::vector<std::string> &InputArgv) { 24220a631fdSOwen Anderson unsigned PtrSize = EE->getTargetData()->getPointerSize(); 2435a0d4829SChris Lattner char *Result = new char[(InputArgv.size()+1)*PtrSize]; 2445a0d4829SChris Lattner 2454dc3eddeSChris Lattner DEBUG(errs() << "JIT: ARGV = " << (void*)Result << "\n"); 24655f1c09eSOwen Anderson const Type *SBytePtr = PointerType::getUnqual(Type::getInt8Ty(C)); 2475a0d4829SChris Lattner 2485a0d4829SChris Lattner for (unsigned i = 0; i != InputArgv.size(); ++i) { 2495a0d4829SChris Lattner unsigned Size = InputArgv[i].size()+1; 2505a0d4829SChris Lattner char *Dest = new char[Size]; 2514dc3eddeSChris Lattner DEBUG(errs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n"); 2525a0d4829SChris Lattner 2535a0d4829SChris Lattner std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest); 2545a0d4829SChris Lattner Dest[Size-1] = 0; 2555a0d4829SChris Lattner 2565a0d4829SChris Lattner // Endian safe: Result[i] = (PointerTy)Dest; 2575a0d4829SChris Lattner EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize), 2585a0d4829SChris Lattner SBytePtr); 2595a0d4829SChris Lattner } 2605a0d4829SChris Lattner 2615a0d4829SChris Lattner // Null terminate it 2625a0d4829SChris Lattner EE->StoreValueToMemory(PTOGV(0), 2635a0d4829SChris Lattner (GenericValue*)(Result+InputArgv.size()*PtrSize), 2645a0d4829SChris Lattner SBytePtr); 2655a0d4829SChris Lattner return Result; 2665a0d4829SChris Lattner } 2675a0d4829SChris Lattner 268faae50b6SChris Lattner 269faae50b6SChris Lattner /// runStaticConstructorsDestructors - This method is used to execute all of 2701a9a0b7bSEvan Cheng /// the static constructors or destructors for a module, depending on the 271faae50b6SChris Lattner /// value of isDtors. 272*41fa2bd1SChris Lattner void ExecutionEngine::runStaticConstructorsDestructors(Module *module, 273*41fa2bd1SChris Lattner bool isDtors) { 274faae50b6SChris Lattner const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors"; 2750621caefSChris Lattner 2760621caefSChris Lattner // Execute global ctors/dtors for each module in the program. 2771a9a0b7bSEvan Cheng 2781a9a0b7bSEvan Cheng GlobalVariable *GV = module->getNamedGlobal(Name); 279fe36eaebSChris Lattner 280fe36eaebSChris Lattner // If this global has internal linkage, or if it has a use, then it must be 281fe36eaebSChris Lattner // an old-style (llvmgcc3) static ctor with __main linked in and in use. If 2820621caefSChris Lattner // this is the case, don't execute any of the global ctors, __main will do 2830621caefSChris Lattner // it. 2846de96a1bSRafael Espindola if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return; 285faae50b6SChris Lattner 2860621caefSChris Lattner // Should be an array of '{ int, void ()* }' structs. The first value is 2870621caefSChris Lattner // the init priority, which we ignore. 288faae50b6SChris Lattner ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer()); 2891a9a0b7bSEvan Cheng if (!InitList) return; 290faae50b6SChris Lattner for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) 2910621caefSChris Lattner if (ConstantStruct *CS = 2920621caefSChris Lattner dyn_cast<ConstantStruct>(InitList->getOperand(i))) { 2931a9a0b7bSEvan Cheng if (CS->getNumOperands() != 2) return; // Not array of 2-element structs. 294faae50b6SChris Lattner 295faae50b6SChris Lattner Constant *FP = CS->getOperand(1); 296faae50b6SChris Lattner if (FP->isNullValue()) 2970621caefSChris Lattner break; // Found a null terminator, exit. 298faae50b6SChris Lattner 299faae50b6SChris Lattner if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP)) 3006c38f0bbSReid Spencer if (CE->isCast()) 301faae50b6SChris Lattner FP = CE->getOperand(0); 302faae50b6SChris Lattner if (Function *F = dyn_cast<Function>(FP)) { 303faae50b6SChris Lattner // Execute the ctor/dtor function! 304faae50b6SChris Lattner runFunction(F, std::vector<GenericValue>()); 305faae50b6SChris Lattner } 306faae50b6SChris Lattner } 307faae50b6SChris Lattner } 3081a9a0b7bSEvan Cheng 3091a9a0b7bSEvan Cheng /// runStaticConstructorsDestructors - This method is used to execute all of 3101a9a0b7bSEvan Cheng /// the static constructors or destructors for a program, depending on the 3111a9a0b7bSEvan Cheng /// value of isDtors. 3121a9a0b7bSEvan Cheng void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) { 3131a9a0b7bSEvan Cheng // Execute global ctors/dtors for each module in the program. 3141a9a0b7bSEvan Cheng for (unsigned m = 0, e = Modules.size(); m != e; ++m) 3151a9a0b7bSEvan Cheng runStaticConstructorsDestructors(Modules[m]->getModule(), isDtors); 3160621caefSChris Lattner } 317faae50b6SChris Lattner 318cf3e3017SDan Gohman #ifndef NDEBUG 3191202d1b1SDuncan Sands /// isTargetNullPtr - Return whether the target pointer stored at Loc is null. 3201202d1b1SDuncan Sands static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) { 3211202d1b1SDuncan Sands unsigned PtrSize = EE->getTargetData()->getPointerSize(); 3221202d1b1SDuncan Sands for (unsigned i = 0; i < PtrSize; ++i) 3231202d1b1SDuncan Sands if (*(i + (uint8_t*)Loc)) 3241202d1b1SDuncan Sands return false; 3251202d1b1SDuncan Sands return true; 3261202d1b1SDuncan Sands } 327cf3e3017SDan Gohman #endif 3281202d1b1SDuncan Sands 3295a0d4829SChris Lattner /// runFunctionAsMain - This is a helper function which wraps runFunction to 3305a0d4829SChris Lattner /// handle the common task of starting up main with the specified argc, argv, 3315a0d4829SChris Lattner /// and envp parameters. 3325a0d4829SChris Lattner int ExecutionEngine::runFunctionAsMain(Function *Fn, 3335a0d4829SChris Lattner const std::vector<std::string> &argv, 3345a0d4829SChris Lattner const char * const * envp) { 3355a0d4829SChris Lattner std::vector<GenericValue> GVArgs; 3365a0d4829SChris Lattner GenericValue GVArgc; 33787aa65f4SReid Spencer GVArgc.IntVal = APInt(32, argv.size()); 3388c32c111SAnton Korobeynikov 3398c32c111SAnton Korobeynikov // Check main() type 340b1cad0b3SChris Lattner unsigned NumArgs = Fn->getFunctionType()->getNumParams(); 3418c32c111SAnton Korobeynikov const FunctionType *FTy = Fn->getFunctionType(); 342edf07887SChristopher Lamb const Type* PPInt8Ty = 34355f1c09eSOwen Anderson PointerType::getUnqual(PointerType::getUnqual( 34455f1c09eSOwen Anderson Type::getInt8Ty(Fn->getContext()))); 3458c32c111SAnton Korobeynikov switch (NumArgs) { 3468c32c111SAnton Korobeynikov case 3: 3478c32c111SAnton Korobeynikov if (FTy->getParamType(2) != PPInt8Ty) { 348ccb29cd2STorok Edwin llvm_report_error("Invalid type for third argument of main() supplied"); 3498c32c111SAnton Korobeynikov } 350b781886dSAnton Korobeynikov // FALLS THROUGH 3518c32c111SAnton Korobeynikov case 2: 3528c32c111SAnton Korobeynikov if (FTy->getParamType(1) != PPInt8Ty) { 353ccb29cd2STorok Edwin llvm_report_error("Invalid type for second argument of main() supplied"); 3548c32c111SAnton Korobeynikov } 355b781886dSAnton Korobeynikov // FALLS THROUGH 3568c32c111SAnton Korobeynikov case 1: 35755f1c09eSOwen Anderson if (FTy->getParamType(0) != Type::getInt32Ty(Fn->getContext())) { 358ccb29cd2STorok Edwin llvm_report_error("Invalid type for first argument of main() supplied"); 3598c32c111SAnton Korobeynikov } 360b781886dSAnton Korobeynikov // FALLS THROUGH 3618c32c111SAnton Korobeynikov case 0: 362370ec10dSChris Lattner if (!isa<IntegerType>(FTy->getReturnType()) && 36355f1c09eSOwen Anderson FTy->getReturnType() != Type::getVoidTy(FTy->getContext())) { 364ccb29cd2STorok Edwin llvm_report_error("Invalid return type of main() supplied"); 3658c32c111SAnton Korobeynikov } 3668c32c111SAnton Korobeynikov break; 3678c32c111SAnton Korobeynikov default: 368ccb29cd2STorok Edwin llvm_report_error("Invalid number of arguments of main() supplied"); 3698c32c111SAnton Korobeynikov } 3708c32c111SAnton Korobeynikov 371b1cad0b3SChris Lattner if (NumArgs) { 3725a0d4829SChris Lattner GVArgs.push_back(GVArgc); // Arg #0 = argc. 373b1cad0b3SChris Lattner if (NumArgs > 1) { 37455f1c09eSOwen Anderson // Arg #1 = argv. 37555f1c09eSOwen Anderson GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, argv))); 3761202d1b1SDuncan Sands assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) && 377b1cad0b3SChris Lattner "argv[0] was null after CreateArgv"); 378b1cad0b3SChris Lattner if (NumArgs > 2) { 3795a0d4829SChris Lattner std::vector<std::string> EnvVars; 3805a0d4829SChris Lattner for (unsigned i = 0; envp[i]; ++i) 3815a0d4829SChris Lattner EnvVars.push_back(envp[i]); 38255f1c09eSOwen Anderson // Arg #2 = envp. 38355f1c09eSOwen Anderson GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, EnvVars))); 384b1cad0b3SChris Lattner } 385b1cad0b3SChris Lattner } 386b1cad0b3SChris Lattner } 38787aa65f4SReid Spencer return runFunction(Fn, GVArgs).IntVal.getZExtValue(); 3885a0d4829SChris Lattner } 3895a0d4829SChris Lattner 390260b0c88SMisha Brukman /// If possible, create a JIT, unless the caller specifically requests an 391260b0c88SMisha Brukman /// Interpreter or there's an error. If even an Interpreter cannot be created, 392260b0c88SMisha Brukman /// NULL is returned. 393857c21b4SMisha Brukman /// 3942f1e2002SMisha Brukman ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP, 395603682adSReid Spencer bool ForceInterpreter, 3967ff05bf5SEvan Cheng std::string *ErrorStr, 39770415d97SJeffrey Yasskin CodeGenOpt::Level OptLevel, 39870415d97SJeffrey Yasskin bool GVsWithCode) { 399fc8a2d5aSReid Kleckner return EngineBuilder(MP) 400fc8a2d5aSReid Kleckner .setEngineKind(ForceInterpreter 401fc8a2d5aSReid Kleckner ? EngineKind::Interpreter 402fc8a2d5aSReid Kleckner : EngineKind::JIT) 403fc8a2d5aSReid Kleckner .setErrorStr(ErrorStr) 404fc8a2d5aSReid Kleckner .setOptLevel(OptLevel) 405fc8a2d5aSReid Kleckner .setAllocateGVsWithCode(GVsWithCode) 406fc8a2d5aSReid Kleckner .create(); 407fc8a2d5aSReid Kleckner } 4084bd3bd5bSBrian Gaeke 409fc8a2d5aSReid Kleckner ExecutionEngine *ExecutionEngine::create(Module *M) { 410fc8a2d5aSReid Kleckner return EngineBuilder(M).create(); 411fc8a2d5aSReid Kleckner } 412fc8a2d5aSReid Kleckner 413fc8a2d5aSReid Kleckner /// EngineBuilder - Overloaded constructor that automatically creates an 414fc8a2d5aSReid Kleckner /// ExistingModuleProvider for an existing module. 415fc8a2d5aSReid Kleckner EngineBuilder::EngineBuilder(Module *m) : MP(new ExistingModuleProvider(m)) { 416fc8a2d5aSReid Kleckner InitEngine(); 417fc8a2d5aSReid Kleckner } 418fc8a2d5aSReid Kleckner 419fc8a2d5aSReid Kleckner ExecutionEngine *EngineBuilder::create() { 420a53414fdSNick Lewycky // Make sure we can resolve symbols in the program as well. The zero arg 421a53414fdSNick Lewycky // to the function tells DynamicLibrary to load the program, not a library. 422a53414fdSNick Lewycky if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr)) 423a53414fdSNick Lewycky return 0; 424a53414fdSNick Lewycky 425fc8a2d5aSReid Kleckner // If the user specified a memory manager but didn't specify which engine to 426fc8a2d5aSReid Kleckner // create, we assume they only want the JIT, and we fail if they only want 427fc8a2d5aSReid Kleckner // the interpreter. 428fc8a2d5aSReid Kleckner if (JMM) { 429*41fa2bd1SChris Lattner if (WhichEngine & EngineKind::JIT) 430fc8a2d5aSReid Kleckner WhichEngine = EngineKind::JIT; 431*41fa2bd1SChris Lattner else { 432fc8a2d5aSReid Kleckner *ErrorStr = "Cannot create an interpreter with a memory manager."; 433*41fa2bd1SChris Lattner return 0; 434fc8a2d5aSReid Kleckner } 4354bd3bd5bSBrian Gaeke } 4364bd3bd5bSBrian Gaeke 437fc8a2d5aSReid Kleckner // Unless the interpreter was explicitly selected or the JIT is not linked, 438fc8a2d5aSReid Kleckner // try making a JIT. 439*41fa2bd1SChris Lattner if (WhichEngine & EngineKind::JIT) { 440*41fa2bd1SChris Lattner if (ExecutionEngine::JITCtor) { 441*41fa2bd1SChris Lattner ExecutionEngine *EE = 442*41fa2bd1SChris Lattner ExecutionEngine::JITCtor(MP, ErrorStr, JMM, OptLevel, 443fc8a2d5aSReid Kleckner AllocateGVsWithCode); 444*41fa2bd1SChris Lattner if (EE) return EE; 445*41fa2bd1SChris Lattner } else { 446*41fa2bd1SChris Lattner *ErrorStr = "JIT has not been linked in."; 447*41fa2bd1SChris Lattner return 0; 448*41fa2bd1SChris Lattner } 449fc8a2d5aSReid Kleckner } 450fc8a2d5aSReid Kleckner 451fc8a2d5aSReid Kleckner // If we can't make a JIT and we didn't request one specifically, try making 452fc8a2d5aSReid Kleckner // an interpreter instead. 453*41fa2bd1SChris Lattner if (WhichEngine & EngineKind::Interpreter) { 454*41fa2bd1SChris Lattner if (ExecutionEngine::InterpCtor) 455*41fa2bd1SChris Lattner return ExecutionEngine::InterpCtor(MP, ErrorStr); 456*41fa2bd1SChris Lattner *ErrorStr = "Interpreter has not been linked in."; 457*41fa2bd1SChris Lattner return 0; 458fc8a2d5aSReid Kleckner } 459fc8a2d5aSReid Kleckner 460*41fa2bd1SChris Lattner return 0; 461b5163bb9SChris Lattner } 462b5163bb9SChris Lattner 463857c21b4SMisha Brukman /// getPointerToGlobal - This returns the address of the specified global 464857c21b4SMisha Brukman /// value. This may involve code generation if it's a function. 465857c21b4SMisha Brukman /// 466996fe010SChris Lattner void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) { 4671678e859SBrian Gaeke if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV))) 468996fe010SChris Lattner return getPointerToFunction(F); 469996fe010SChris Lattner 47079876f52SReid Spencer MutexGuard locked(lock); 47169e84901SJeff Cohen void *p = state.getGlobalAddressMap(locked)[GV]; 47269e84901SJeff Cohen if (p) 47369e84901SJeff Cohen return p; 47469e84901SJeff Cohen 47569e84901SJeff Cohen // Global variable might have been added since interpreter started. 47669e84901SJeff Cohen if (GlobalVariable *GVar = 47769e84901SJeff Cohen const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV))) 47869e84901SJeff Cohen EmitGlobalVariable(GVar); 47969e84901SJeff Cohen else 480fbcc663cSTorok Edwin llvm_unreachable("Global hasn't had an address allocated yet!"); 48179876f52SReid Spencer return state.getGlobalAddressMap(locked)[GV]; 482996fe010SChris Lattner } 483996fe010SChris Lattner 4846c38f0bbSReid Spencer /// This function converts a Constant* into a GenericValue. The interesting 4856c38f0bbSReid Spencer /// part is if C is a ConstantExpr. 4862dc9f132SReid Spencer /// @brief Get a GenericValue for a Constant* 487996fe010SChris Lattner GenericValue ExecutionEngine::getConstantValue(const Constant *C) { 4886c38f0bbSReid Spencer // If its undefined, return the garbage. 4894fd528f2SReid Spencer if (isa<UndefValue>(C)) 4904fd528f2SReid Spencer return GenericValue(); 4919de0d14dSChris Lattner 4926c38f0bbSReid Spencer // If the value is a ConstantExpr 4936c38f0bbSReid Spencer if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 4944fd528f2SReid Spencer Constant *Op0 = CE->getOperand(0); 4959de0d14dSChris Lattner switch (CE->getOpcode()) { 4969de0d14dSChris Lattner case Instruction::GetElementPtr: { 4976c38f0bbSReid Spencer // Compute the index 4984fd528f2SReid Spencer GenericValue Result = getConstantValue(Op0); 499c44bd78aSChris Lattner SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end()); 5009de0d14dSChris Lattner uint64_t Offset = 5014fd528f2SReid Spencer TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size()); 5029de0d14dSChris Lattner 50387aa65f4SReid Spencer char* tmp = (char*) Result.PointerVal; 50487aa65f4SReid Spencer Result = PTOGV(tmp + Offset); 5059de0d14dSChris Lattner return Result; 5069de0d14dSChris Lattner } 5074fd528f2SReid Spencer case Instruction::Trunc: { 5084fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 5094fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 5104fd528f2SReid Spencer GV.IntVal = GV.IntVal.trunc(BitWidth); 5114fd528f2SReid Spencer return GV; 5124fd528f2SReid Spencer } 5134fd528f2SReid Spencer case Instruction::ZExt: { 5144fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 5154fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 5164fd528f2SReid Spencer GV.IntVal = GV.IntVal.zext(BitWidth); 5174fd528f2SReid Spencer return GV; 5184fd528f2SReid Spencer } 5194fd528f2SReid Spencer case Instruction::SExt: { 5204fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 5214fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 5224fd528f2SReid Spencer GV.IntVal = GV.IntVal.sext(BitWidth); 5234fd528f2SReid Spencer return GV; 5244fd528f2SReid Spencer } 5254fd528f2SReid Spencer case Instruction::FPTrunc: { 526a1336cf5SDale Johannesen // FIXME long double 5274fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 5284fd528f2SReid Spencer GV.FloatVal = float(GV.DoubleVal); 5294fd528f2SReid Spencer return GV; 5304fd528f2SReid Spencer } 5314fd528f2SReid Spencer case Instruction::FPExt:{ 532a1336cf5SDale Johannesen // FIXME long double 5334fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 5344fd528f2SReid Spencer GV.DoubleVal = double(GV.FloatVal); 5354fd528f2SReid Spencer return GV; 5364fd528f2SReid Spencer } 5374fd528f2SReid Spencer case Instruction::UIToFP: { 5384fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 53955f1c09eSOwen Anderson if (CE->getType() == Type::getFloatTy(CE->getContext())) 5404fd528f2SReid Spencer GV.FloatVal = float(GV.IntVal.roundToDouble()); 54155f1c09eSOwen Anderson else if (CE->getType() == Type::getDoubleTy(CE->getContext())) 5424fd528f2SReid Spencer GV.DoubleVal = GV.IntVal.roundToDouble(); 54355f1c09eSOwen Anderson else if (CE->getType() == Type::getX86_FP80Ty(Op0->getContext())) { 544a1336cf5SDale Johannesen const uint64_t zero[] = {0, 0}; 545a1336cf5SDale Johannesen APFloat apf = APFloat(APInt(80, 2, zero)); 546ca24fd90SDan Gohman (void)apf.convertFromAPInt(GV.IntVal, 547ca24fd90SDan Gohman false, 5489150652bSDale Johannesen APFloat::rmNearestTiesToEven); 54954306fe4SDale Johannesen GV.IntVal = apf.bitcastToAPInt(); 550a1336cf5SDale Johannesen } 5514fd528f2SReid Spencer return GV; 5524fd528f2SReid Spencer } 5534fd528f2SReid Spencer case Instruction::SIToFP: { 5544fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 55555f1c09eSOwen Anderson if (CE->getType() == Type::getFloatTy(CE->getContext())) 5564fd528f2SReid Spencer GV.FloatVal = float(GV.IntVal.signedRoundToDouble()); 55755f1c09eSOwen Anderson else if (CE->getType() == Type::getDoubleTy(CE->getContext())) 5584fd528f2SReid Spencer GV.DoubleVal = GV.IntVal.signedRoundToDouble(); 55955f1c09eSOwen Anderson else if (CE->getType() == Type::getX86_FP80Ty(CE->getContext())) { 560a1336cf5SDale Johannesen const uint64_t zero[] = { 0, 0}; 561a1336cf5SDale Johannesen APFloat apf = APFloat(APInt(80, 2, zero)); 562ca24fd90SDan Gohman (void)apf.convertFromAPInt(GV.IntVal, 563ca24fd90SDan Gohman true, 5649150652bSDale Johannesen APFloat::rmNearestTiesToEven); 56554306fe4SDale Johannesen GV.IntVal = apf.bitcastToAPInt(); 566a1336cf5SDale Johannesen } 5674fd528f2SReid Spencer return GV; 5684fd528f2SReid Spencer } 5694fd528f2SReid Spencer case Instruction::FPToUI: // double->APInt conversion handles sign 5704fd528f2SReid Spencer case Instruction::FPToSI: { 5714fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 5724fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 57355f1c09eSOwen Anderson if (Op0->getType() == Type::getFloatTy(Op0->getContext())) 5744fd528f2SReid Spencer GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth); 57555f1c09eSOwen Anderson else if (Op0->getType() == Type::getDoubleTy(Op0->getContext())) 5764fd528f2SReid Spencer GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth); 57755f1c09eSOwen Anderson else if (Op0->getType() == Type::getX86_FP80Ty(Op0->getContext())) { 578a1336cf5SDale Johannesen APFloat apf = APFloat(GV.IntVal); 579a1336cf5SDale Johannesen uint64_t v; 5804f0bd68cSDale Johannesen bool ignored; 581a1336cf5SDale Johannesen (void)apf.convertToInteger(&v, BitWidth, 582a1336cf5SDale Johannesen CE->getOpcode()==Instruction::FPToSI, 5834f0bd68cSDale Johannesen APFloat::rmTowardZero, &ignored); 584a1336cf5SDale Johannesen GV.IntVal = v; // endian? 585a1336cf5SDale Johannesen } 5864fd528f2SReid Spencer return GV; 5874fd528f2SReid Spencer } 5886c38f0bbSReid Spencer case Instruction::PtrToInt: { 5894fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 5904fd528f2SReid Spencer uint32_t PtrWidth = TD->getPointerSizeInBits(); 5914fd528f2SReid Spencer GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal)); 5924fd528f2SReid Spencer return GV; 5934fd528f2SReid Spencer } 5944fd528f2SReid Spencer case Instruction::IntToPtr: { 5954fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 5964fd528f2SReid Spencer uint32_t PtrWidth = TD->getPointerSizeInBits(); 5974fd528f2SReid Spencer if (PtrWidth != GV.IntVal.getBitWidth()) 5984fd528f2SReid Spencer GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth); 5994fd528f2SReid Spencer assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width"); 6004fd528f2SReid Spencer GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue())); 6016c38f0bbSReid Spencer return GV; 6026c38f0bbSReid Spencer } 6036c38f0bbSReid Spencer case Instruction::BitCast: { 6044fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 6054fd528f2SReid Spencer const Type* DestTy = CE->getType(); 6064fd528f2SReid Spencer switch (Op0->getType()->getTypeID()) { 607fbcc663cSTorok Edwin default: llvm_unreachable("Invalid bitcast operand"); 6084fd528f2SReid Spencer case Type::IntegerTyID: 6094fd528f2SReid Spencer assert(DestTy->isFloatingPoint() && "invalid bitcast"); 61055f1c09eSOwen Anderson if (DestTy == Type::getFloatTy(Op0->getContext())) 6114fd528f2SReid Spencer GV.FloatVal = GV.IntVal.bitsToFloat(); 61255f1c09eSOwen Anderson else if (DestTy == Type::getDoubleTy(DestTy->getContext())) 6134fd528f2SReid Spencer GV.DoubleVal = GV.IntVal.bitsToDouble(); 6146c38f0bbSReid Spencer break; 6154fd528f2SReid Spencer case Type::FloatTyID: 61655f1c09eSOwen Anderson assert(DestTy == Type::getInt32Ty(DestTy->getContext()) && 61755f1c09eSOwen Anderson "Invalid bitcast"); 6184fd528f2SReid Spencer GV.IntVal.floatToBits(GV.FloatVal); 6194fd528f2SReid Spencer break; 6204fd528f2SReid Spencer case Type::DoubleTyID: 62155f1c09eSOwen Anderson assert(DestTy == Type::getInt64Ty(DestTy->getContext()) && 62255f1c09eSOwen Anderson "Invalid bitcast"); 6234fd528f2SReid Spencer GV.IntVal.doubleToBits(GV.DoubleVal); 6244fd528f2SReid Spencer break; 6254fd528f2SReid Spencer case Type::PointerTyID: 6264fd528f2SReid Spencer assert(isa<PointerType>(DestTy) && "Invalid bitcast"); 6274fd528f2SReid Spencer break; // getConstantValue(Op0) above already converted it 6286c38f0bbSReid Spencer } 6294fd528f2SReid Spencer return GV; 63068cbcc3eSChris Lattner } 63168cbcc3eSChris Lattner case Instruction::Add: 632a5b9645cSDan Gohman case Instruction::FAdd: 6334fd528f2SReid Spencer case Instruction::Sub: 634a5b9645cSDan Gohman case Instruction::FSub: 6354fd528f2SReid Spencer case Instruction::Mul: 636a5b9645cSDan Gohman case Instruction::FMul: 6374fd528f2SReid Spencer case Instruction::UDiv: 6384fd528f2SReid Spencer case Instruction::SDiv: 6394fd528f2SReid Spencer case Instruction::URem: 6404fd528f2SReid Spencer case Instruction::SRem: 6414fd528f2SReid Spencer case Instruction::And: 6424fd528f2SReid Spencer case Instruction::Or: 6434fd528f2SReid Spencer case Instruction::Xor: { 6444fd528f2SReid Spencer GenericValue LHS = getConstantValue(Op0); 6454fd528f2SReid Spencer GenericValue RHS = getConstantValue(CE->getOperand(1)); 6464fd528f2SReid Spencer GenericValue GV; 647c4e6bb5fSChris Lattner switch (CE->getOperand(0)->getType()->getTypeID()) { 648fbcc663cSTorok Edwin default: llvm_unreachable("Bad add type!"); 6497a9c62baSReid Spencer case Type::IntegerTyID: 6504fd528f2SReid Spencer switch (CE->getOpcode()) { 651fbcc663cSTorok Edwin default: llvm_unreachable("Invalid integer opcode"); 6524fd528f2SReid Spencer case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break; 6534fd528f2SReid Spencer case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break; 6544fd528f2SReid Spencer case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break; 6554fd528f2SReid Spencer case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break; 6564fd528f2SReid Spencer case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break; 6574fd528f2SReid Spencer case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break; 6584fd528f2SReid Spencer case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break; 6594fd528f2SReid Spencer case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break; 6604fd528f2SReid Spencer case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break; 6614fd528f2SReid Spencer case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break; 6624fd528f2SReid Spencer } 663c4e6bb5fSChris Lattner break; 664c4e6bb5fSChris Lattner case Type::FloatTyID: 6654fd528f2SReid Spencer switch (CE->getOpcode()) { 666fbcc663cSTorok Edwin default: llvm_unreachable("Invalid float opcode"); 667a5b9645cSDan Gohman case Instruction::FAdd: 6684fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break; 669a5b9645cSDan Gohman case Instruction::FSub: 6704fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break; 671a5b9645cSDan Gohman case Instruction::FMul: 6724fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break; 6734fd528f2SReid Spencer case Instruction::FDiv: 6744fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break; 6754fd528f2SReid Spencer case Instruction::FRem: 6764fd528f2SReid Spencer GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break; 6774fd528f2SReid Spencer } 678c4e6bb5fSChris Lattner break; 679c4e6bb5fSChris Lattner case Type::DoubleTyID: 6804fd528f2SReid Spencer switch (CE->getOpcode()) { 681fbcc663cSTorok Edwin default: llvm_unreachable("Invalid double opcode"); 682a5b9645cSDan Gohman case Instruction::FAdd: 6834fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break; 684a5b9645cSDan Gohman case Instruction::FSub: 6854fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break; 686a5b9645cSDan Gohman case Instruction::FMul: 6874fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break; 6884fd528f2SReid Spencer case Instruction::FDiv: 6894fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break; 6904fd528f2SReid Spencer case Instruction::FRem: 6914fd528f2SReid Spencer GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break; 6924fd528f2SReid Spencer } 693c4e6bb5fSChris Lattner break; 694a1336cf5SDale Johannesen case Type::X86_FP80TyID: 695a1336cf5SDale Johannesen case Type::PPC_FP128TyID: 696a1336cf5SDale Johannesen case Type::FP128TyID: { 697a1336cf5SDale Johannesen APFloat apfLHS = APFloat(LHS.IntVal); 698a1336cf5SDale Johannesen switch (CE->getOpcode()) { 699fbcc663cSTorok Edwin default: llvm_unreachable("Invalid long double opcode");llvm_unreachable(0); 700a5b9645cSDan Gohman case Instruction::FAdd: 701a1336cf5SDale Johannesen apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 70254306fe4SDale Johannesen GV.IntVal = apfLHS.bitcastToAPInt(); 703a1336cf5SDale Johannesen break; 704a5b9645cSDan Gohman case Instruction::FSub: 705a1336cf5SDale Johannesen apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 70654306fe4SDale Johannesen GV.IntVal = apfLHS.bitcastToAPInt(); 707a1336cf5SDale Johannesen break; 708a5b9645cSDan Gohman case Instruction::FMul: 709a1336cf5SDale Johannesen apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 71054306fe4SDale Johannesen GV.IntVal = apfLHS.bitcastToAPInt(); 711a1336cf5SDale Johannesen break; 712a1336cf5SDale Johannesen case Instruction::FDiv: 713a1336cf5SDale Johannesen apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 71454306fe4SDale Johannesen GV.IntVal = apfLHS.bitcastToAPInt(); 715a1336cf5SDale Johannesen break; 716a1336cf5SDale Johannesen case Instruction::FRem: 717a1336cf5SDale Johannesen apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 71854306fe4SDale Johannesen GV.IntVal = apfLHS.bitcastToAPInt(); 719a1336cf5SDale Johannesen break; 720a1336cf5SDale Johannesen } 721a1336cf5SDale Johannesen } 722a1336cf5SDale Johannesen break; 723c4e6bb5fSChris Lattner } 7244fd528f2SReid Spencer return GV; 7254fd528f2SReid Spencer } 7269de0d14dSChris Lattner default: 72768cbcc3eSChris Lattner break; 72868cbcc3eSChris Lattner } 729ccb29cd2STorok Edwin std::string msg; 730ccb29cd2STorok Edwin raw_string_ostream Msg(msg); 731ccb29cd2STorok Edwin Msg << "ConstantExpr not handled: " << *CE; 732ccb29cd2STorok Edwin llvm_report_error(Msg.str()); 7339de0d14dSChris Lattner } 734996fe010SChris Lattner 7354fd528f2SReid Spencer GenericValue Result; 7366b727599SChris Lattner switch (C->getType()->getTypeID()) { 73787aa65f4SReid Spencer case Type::FloatTyID: 738bed9dc42SDale Johannesen Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat(); 7397a9c62baSReid Spencer break; 74087aa65f4SReid Spencer case Type::DoubleTyID: 741bed9dc42SDale Johannesen Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble(); 74287aa65f4SReid Spencer break; 743a1336cf5SDale Johannesen case Type::X86_FP80TyID: 744a1336cf5SDale Johannesen case Type::FP128TyID: 745a1336cf5SDale Johannesen case Type::PPC_FP128TyID: 74654306fe4SDale Johannesen Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt(); 747a1336cf5SDale Johannesen break; 74887aa65f4SReid Spencer case Type::IntegerTyID: 74987aa65f4SReid Spencer Result.IntVal = cast<ConstantInt>(C)->getValue(); 75087aa65f4SReid Spencer break; 751996fe010SChris Lattner case Type::PointerTyID: 7526a0fd73bSReid Spencer if (isa<ConstantPointerNull>(C)) 753996fe010SChris Lattner Result.PointerVal = 0; 7546a0fd73bSReid Spencer else if (const Function *F = dyn_cast<Function>(C)) 7556a0fd73bSReid Spencer Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F))); 7566a0fd73bSReid Spencer else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C)) 7576a0fd73bSReid Spencer Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV))); 758e6492f10SChris Lattner else 759fbcc663cSTorok Edwin llvm_unreachable("Unknown constant pointer type!"); 760996fe010SChris Lattner break; 761996fe010SChris Lattner default: 762ccb29cd2STorok Edwin std::string msg; 763ccb29cd2STorok Edwin raw_string_ostream Msg(msg); 764ccb29cd2STorok Edwin Msg << "ERROR: Constant unimplemented for type: " << *C->getType(); 765ccb29cd2STorok Edwin llvm_report_error(Msg.str()); 766996fe010SChris Lattner } 767996fe010SChris Lattner return Result; 768996fe010SChris Lattner } 769996fe010SChris Lattner 7701202d1b1SDuncan Sands /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst 7711202d1b1SDuncan Sands /// with the integer held in IntVal. 7721202d1b1SDuncan Sands static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst, 7731202d1b1SDuncan Sands unsigned StoreBytes) { 7741202d1b1SDuncan Sands assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!"); 7751202d1b1SDuncan Sands uint8_t *Src = (uint8_t *)IntVal.getRawData(); 7765c65cb46SDuncan Sands 777aa121227SChris Lattner if (sys::isLittleEndianHost()) 7781202d1b1SDuncan Sands // Little-endian host - the source is ordered from LSB to MSB. Order the 7791202d1b1SDuncan Sands // destination from LSB to MSB: Do a straight copy. 7805c65cb46SDuncan Sands memcpy(Dst, Src, StoreBytes); 7815c65cb46SDuncan Sands else { 7825c65cb46SDuncan Sands // Big-endian host - the source is an array of 64 bit words ordered from 7831202d1b1SDuncan Sands // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination 7841202d1b1SDuncan Sands // from MSB to LSB: Reverse the word order, but not the bytes in a word. 7855c65cb46SDuncan Sands while (StoreBytes > sizeof(uint64_t)) { 7865c65cb46SDuncan Sands StoreBytes -= sizeof(uint64_t); 7875c65cb46SDuncan Sands // May not be aligned so use memcpy. 7885c65cb46SDuncan Sands memcpy(Dst + StoreBytes, Src, sizeof(uint64_t)); 7895c65cb46SDuncan Sands Src += sizeof(uint64_t); 7905c65cb46SDuncan Sands } 7915c65cb46SDuncan Sands 7925c65cb46SDuncan Sands memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes); 793815f8dd2SReid Spencer } 7947a9c62baSReid Spencer } 7951202d1b1SDuncan Sands 7961202d1b1SDuncan Sands /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr 7971202d1b1SDuncan Sands /// is the address of the memory at which to store Val, cast to GenericValue *. 7981202d1b1SDuncan Sands /// It is not a pointer to a GenericValue containing the address at which to 7991202d1b1SDuncan Sands /// store Val. 80009053e62SEvan Cheng void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, 80109053e62SEvan Cheng GenericValue *Ptr, const Type *Ty) { 8021202d1b1SDuncan Sands const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty); 8031202d1b1SDuncan Sands 8041202d1b1SDuncan Sands switch (Ty->getTypeID()) { 8051202d1b1SDuncan Sands case Type::IntegerTyID: 8061202d1b1SDuncan Sands StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes); 8071202d1b1SDuncan Sands break; 808996fe010SChris Lattner case Type::FloatTyID: 80987aa65f4SReid Spencer *((float*)Ptr) = Val.FloatVal; 81087aa65f4SReid Spencer break; 81187aa65f4SReid Spencer case Type::DoubleTyID: 81287aa65f4SReid Spencer *((double*)Ptr) = Val.DoubleVal; 813996fe010SChris Lattner break; 8144d7e4ee7SDale Johannesen case Type::X86_FP80TyID: 8154d7e4ee7SDale Johannesen memcpy(Ptr, Val.IntVal.getRawData(), 10); 816a1336cf5SDale Johannesen break; 8177a9c62baSReid Spencer case Type::PointerTyID: 8181202d1b1SDuncan Sands // Ensure 64 bit target pointers are fully initialized on 32 bit hosts. 8191202d1b1SDuncan Sands if (StoreBytes != sizeof(PointerTy)) 8201202d1b1SDuncan Sands memset(Ptr, 0, StoreBytes); 8211202d1b1SDuncan Sands 82287aa65f4SReid Spencer *((PointerTy*)Ptr) = Val.PointerVal; 823996fe010SChris Lattner break; 824996fe010SChris Lattner default: 8253924bb57SChris Lattner errs() << "Cannot store value of type " << *Ty << "!\n"; 826996fe010SChris Lattner } 8271202d1b1SDuncan Sands 828aa121227SChris Lattner if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian()) 8291202d1b1SDuncan Sands // Host and target are different endian - reverse the stored bytes. 8301202d1b1SDuncan Sands std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr); 831996fe010SChris Lattner } 832996fe010SChris Lattner 8331202d1b1SDuncan Sands /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting 8341202d1b1SDuncan Sands /// from Src into IntVal, which is assumed to be wide enough and to hold zero. 8351202d1b1SDuncan Sands static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) { 8361202d1b1SDuncan Sands assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!"); 8371202d1b1SDuncan Sands uint8_t *Dst = (uint8_t *)IntVal.getRawData(); 8385c65cb46SDuncan Sands 839aa121227SChris Lattner if (sys::isLittleEndianHost()) 8405c65cb46SDuncan Sands // Little-endian host - the destination must be ordered from LSB to MSB. 8415c65cb46SDuncan Sands // The source is ordered from LSB to MSB: Do a straight copy. 8425c65cb46SDuncan Sands memcpy(Dst, Src, LoadBytes); 8435c65cb46SDuncan Sands else { 8445c65cb46SDuncan Sands // Big-endian - the destination is an array of 64 bit words ordered from 8455c65cb46SDuncan Sands // LSW to MSW. Each word must be ordered from MSB to LSB. The source is 8465c65cb46SDuncan Sands // ordered from MSB to LSB: Reverse the word order, but not the bytes in 8475c65cb46SDuncan Sands // a word. 8485c65cb46SDuncan Sands while (LoadBytes > sizeof(uint64_t)) { 8495c65cb46SDuncan Sands LoadBytes -= sizeof(uint64_t); 8505c65cb46SDuncan Sands // May not be aligned so use memcpy. 8515c65cb46SDuncan Sands memcpy(Dst, Src + LoadBytes, sizeof(uint64_t)); 8525c65cb46SDuncan Sands Dst += sizeof(uint64_t); 8535c65cb46SDuncan Sands } 8545c65cb46SDuncan Sands 8555c65cb46SDuncan Sands memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes); 8565c65cb46SDuncan Sands } 8577a9c62baSReid Spencer } 8581202d1b1SDuncan Sands 8591202d1b1SDuncan Sands /// FIXME: document 8601202d1b1SDuncan Sands /// 8611202d1b1SDuncan Sands void ExecutionEngine::LoadValueFromMemory(GenericValue &Result, 8621202d1b1SDuncan Sands GenericValue *Ptr, 8631202d1b1SDuncan Sands const Type *Ty) { 8641202d1b1SDuncan Sands const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty); 8651202d1b1SDuncan Sands 8661202d1b1SDuncan Sands switch (Ty->getTypeID()) { 8671202d1b1SDuncan Sands case Type::IntegerTyID: 8681202d1b1SDuncan Sands // An APInt with all words initially zero. 8691202d1b1SDuncan Sands Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0); 8701202d1b1SDuncan Sands LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes); 8711202d1b1SDuncan Sands break; 8727f389e8cSChris Lattner case Type::FloatTyID: 87387aa65f4SReid Spencer Result.FloatVal = *((float*)Ptr); 87487aa65f4SReid Spencer break; 87587aa65f4SReid Spencer case Type::DoubleTyID: 87687aa65f4SReid Spencer Result.DoubleVal = *((double*)Ptr); 8777f389e8cSChris Lattner break; 8787a9c62baSReid Spencer case Type::PointerTyID: 87987aa65f4SReid Spencer Result.PointerVal = *((PointerTy*)Ptr); 8807f389e8cSChris Lattner break; 881a1336cf5SDale Johannesen case Type::X86_FP80TyID: { 882a1336cf5SDale Johannesen // This is endian dependent, but it will only work on x86 anyway. 88326d6539eSDuncan Sands // FIXME: Will not trap if loading a signaling NaN. 884ff306287SDuncan Sands uint64_t y[2]; 8854d7e4ee7SDale Johannesen memcpy(y, Ptr, 10); 886ff306287SDuncan Sands Result.IntVal = APInt(80, 2, y); 887a1336cf5SDale Johannesen break; 888a1336cf5SDale Johannesen } 8897f389e8cSChris Lattner default: 890ccb29cd2STorok Edwin std::string msg; 891ccb29cd2STorok Edwin raw_string_ostream Msg(msg); 892ccb29cd2STorok Edwin Msg << "Cannot load value of type " << *Ty << "!"; 893ccb29cd2STorok Edwin llvm_report_error(Msg.str()); 8947f389e8cSChris Lattner } 8957f389e8cSChris Lattner } 8967f389e8cSChris Lattner 897996fe010SChris Lattner // InitializeMemory - Recursive function to apply a Constant value into the 898996fe010SChris Lattner // specified memory location... 899996fe010SChris Lattner // 900996fe010SChris Lattner void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) { 9014dc3eddeSChris Lattner DEBUG(errs() << "JIT: Initializing " << Addr << " "); 902b086d382SDale Johannesen DEBUG(Init->dump()); 90361753bf8SChris Lattner if (isa<UndefValue>(Init)) { 90461753bf8SChris Lattner return; 905d84d35baSReid Spencer } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) { 90669d62138SRobert Bocchino unsigned ElementSize = 907af9eaa83SDuncan Sands getTargetData()->getTypeAllocSize(CP->getType()->getElementType()); 90869d62138SRobert Bocchino for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) 90969d62138SRobert Bocchino InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize); 91069d62138SRobert Bocchino return; 9111dd86b11SChris Lattner } else if (isa<ConstantAggregateZero>(Init)) { 912af9eaa83SDuncan Sands memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType())); 9131dd86b11SChris Lattner return; 91469ddfbfeSDan Gohman } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) { 91569ddfbfeSDan Gohman unsigned ElementSize = 916af9eaa83SDuncan Sands getTargetData()->getTypeAllocSize(CPA->getType()->getElementType()); 91769ddfbfeSDan Gohman for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) 91869ddfbfeSDan Gohman InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize); 91969ddfbfeSDan Gohman return; 92069ddfbfeSDan Gohman } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) { 92169ddfbfeSDan Gohman const StructLayout *SL = 92269ddfbfeSDan Gohman getTargetData()->getStructLayout(cast<StructType>(CPS->getType())); 92369ddfbfeSDan Gohman for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) 92469ddfbfeSDan Gohman InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i)); 92569ddfbfeSDan Gohman return; 92661753bf8SChris Lattner } else if (Init->getType()->isFirstClassType()) { 927996fe010SChris Lattner GenericValue Val = getConstantValue(Init); 928996fe010SChris Lattner StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType()); 929996fe010SChris Lattner return; 930996fe010SChris Lattner } 931996fe010SChris Lattner 9323924bb57SChris Lattner errs() << "Bad Type: " << *Init->getType() << "\n"; 933fbcc663cSTorok Edwin llvm_unreachable("Unknown constant type to initialize memory with!"); 934996fe010SChris Lattner } 935996fe010SChris Lattner 936996fe010SChris Lattner /// EmitGlobals - Emit all of the global variables to memory, storing their 937996fe010SChris Lattner /// addresses into GlobalAddress. This must make sure to copy the contents of 938996fe010SChris Lattner /// their initializers into the memory. 939996fe010SChris Lattner /// 940996fe010SChris Lattner void ExecutionEngine::emitGlobals() { 941996fe010SChris Lattner 942996fe010SChris Lattner // Loop over all of the global variables in the program, allocating the memory 9430621caefSChris Lattner // to hold them. If there is more than one module, do a prepass over globals 9440621caefSChris Lattner // to figure out how the different modules should link together. 9450621caefSChris Lattner // 9460621caefSChris Lattner std::map<std::pair<std::string, const Type*>, 9470621caefSChris Lattner const GlobalValue*> LinkedGlobalsMap; 9480621caefSChris Lattner 9490621caefSChris Lattner if (Modules.size() != 1) { 9500621caefSChris Lattner for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 9510621caefSChris Lattner Module &M = *Modules[m]->getModule(); 9520621caefSChris Lattner for (Module::const_global_iterator I = M.global_begin(), 9530621caefSChris Lattner E = M.global_end(); I != E; ++I) { 9540621caefSChris Lattner const GlobalValue *GV = I; 9556de96a1bSRafael Espindola if (GV->hasLocalLinkage() || GV->isDeclaration() || 9560621caefSChris Lattner GV->hasAppendingLinkage() || !GV->hasName()) 9570621caefSChris Lattner continue;// Ignore external globals and globals with internal linkage. 9580621caefSChris Lattner 9590621caefSChris Lattner const GlobalValue *&GVEntry = 9600621caefSChris Lattner LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())]; 9610621caefSChris Lattner 9620621caefSChris Lattner // If this is the first time we've seen this global, it is the canonical 9630621caefSChris Lattner // version. 9640621caefSChris Lattner if (!GVEntry) { 9650621caefSChris Lattner GVEntry = GV; 9660621caefSChris Lattner continue; 9670621caefSChris Lattner } 9680621caefSChris Lattner 9690621caefSChris Lattner // If the existing global is strong, never replace it. 970d61d39ecSAnton Korobeynikov if (GVEntry->hasExternalLinkage() || 971d61d39ecSAnton Korobeynikov GVEntry->hasDLLImportLinkage() || 972d61d39ecSAnton Korobeynikov GVEntry->hasDLLExportLinkage()) 9730621caefSChris Lattner continue; 9740621caefSChris Lattner 9750621caefSChris Lattner // Otherwise, we know it's linkonce/weak, replace it if this is a strong 976ce4396bcSDale Johannesen // symbol. FIXME is this right for common? 97712c94949SAnton Korobeynikov if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage()) 9780621caefSChris Lattner GVEntry = GV; 9790621caefSChris Lattner } 9800621caefSChris Lattner } 9810621caefSChris Lattner } 9820621caefSChris Lattner 9830621caefSChris Lattner std::vector<const GlobalValue*> NonCanonicalGlobals; 9840621caefSChris Lattner for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 9850621caefSChris Lattner Module &M = *Modules[m]->getModule(); 9868ffb6611SChris Lattner for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 9870621caefSChris Lattner I != E; ++I) { 9880621caefSChris Lattner // In the multi-module case, see what this global maps to. 9890621caefSChris Lattner if (!LinkedGlobalsMap.empty()) { 9900621caefSChris Lattner if (const GlobalValue *GVEntry = 9910621caefSChris Lattner LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) { 9920621caefSChris Lattner // If something else is the canonical global, ignore this one. 9930621caefSChris Lattner if (GVEntry != &*I) { 9940621caefSChris Lattner NonCanonicalGlobals.push_back(I); 9950621caefSChris Lattner continue; 9960621caefSChris Lattner } 9970621caefSChris Lattner } 9980621caefSChris Lattner } 9990621caefSChris Lattner 10005301e7c6SReid Spencer if (!I->isDeclaration()) { 10015457ce9aSNicolas Geoffray addGlobalMapping(I, getMemoryForGV(I)); 1002996fe010SChris Lattner } else { 1003e8bbcfc2SBrian Gaeke // External variable reference. Try to use the dynamic loader to 1004e8bbcfc2SBrian Gaeke // get a pointer to it. 10050621caefSChris Lattner if (void *SymAddr = 10065899e340SDaniel Dunbar sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName())) 1007748e8579SChris Lattner addGlobalMapping(I, SymAddr); 10089de0d14dSChris Lattner else { 10096c2d233eSTorok Edwin llvm_report_error("Could not resolve external global address: " 10106c2d233eSTorok Edwin +I->getName()); 10119de0d14dSChris Lattner } 1012996fe010SChris Lattner } 10130621caefSChris Lattner } 10140621caefSChris Lattner 10150621caefSChris Lattner // If there are multiple modules, map the non-canonical globals to their 10160621caefSChris Lattner // canonical location. 10170621caefSChris Lattner if (!NonCanonicalGlobals.empty()) { 10180621caefSChris Lattner for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) { 10190621caefSChris Lattner const GlobalValue *GV = NonCanonicalGlobals[i]; 10200621caefSChris Lattner const GlobalValue *CGV = 10210621caefSChris Lattner LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())]; 10220621caefSChris Lattner void *Ptr = getPointerToGlobalIfAvailable(CGV); 10230621caefSChris Lattner assert(Ptr && "Canonical global wasn't codegen'd!"); 1024a67f06b9SNuno Lopes addGlobalMapping(GV, Ptr); 10250621caefSChris Lattner } 10260621caefSChris Lattner } 1027996fe010SChris Lattner 10287a9c62baSReid Spencer // Now that all of the globals are set up in memory, loop through them all 10297a9c62baSReid Spencer // and initialize their contents. 10308ffb6611SChris Lattner for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 10310621caefSChris Lattner I != E; ++I) { 10325301e7c6SReid Spencer if (!I->isDeclaration()) { 10330621caefSChris Lattner if (!LinkedGlobalsMap.empty()) { 10340621caefSChris Lattner if (const GlobalValue *GVEntry = 10350621caefSChris Lattner LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) 10360621caefSChris Lattner if (GVEntry != &*I) // Not the canonical variable. 10370621caefSChris Lattner continue; 10380621caefSChris Lattner } 10396bbe3eceSChris Lattner EmitGlobalVariable(I); 10406bbe3eceSChris Lattner } 10410621caefSChris Lattner } 10420621caefSChris Lattner } 10430621caefSChris Lattner } 10446bbe3eceSChris Lattner 10456bbe3eceSChris Lattner // EmitGlobalVariable - This method emits the specified global variable to the 10466bbe3eceSChris Lattner // address specified in GlobalAddresses, or allocates new memory if it's not 10476bbe3eceSChris Lattner // already in the map. 1048fbcc0aa1SChris Lattner void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) { 1049748e8579SChris Lattner void *GA = getPointerToGlobalIfAvailable(GV); 1050dc631735SChris Lattner 10516bbe3eceSChris Lattner if (GA == 0) { 10526bbe3eceSChris Lattner // If it's not already specified, allocate memory for the global. 10535457ce9aSNicolas Geoffray GA = getMemoryForGV(GV); 1054748e8579SChris Lattner addGlobalMapping(GV, GA); 10556bbe3eceSChris Lattner } 1056fbcc0aa1SChris Lattner 10575457ce9aSNicolas Geoffray // Don't initialize if it's thread local, let the client do it. 10585457ce9aSNicolas Geoffray if (!GV->isThreadLocal()) 10596bbe3eceSChris Lattner InitializeMemory(GV->getInitializer(), GA); 10605457ce9aSNicolas Geoffray 10615457ce9aSNicolas Geoffray const Type *ElTy = GV->getType()->getElementType(); 1062af9eaa83SDuncan Sands size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy); 1063df1f1524SChris Lattner NumInitBytes += (unsigned)GVSize; 10646bbe3eceSChris Lattner ++NumGlobals; 1065996fe010SChris Lattner } 1066