1857c21b4SMisha Brukman //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===// 2996fe010SChris Lattner // 3482202a6SJohn Criswell // The LLVM Compiler Infrastructure 4482202a6SJohn Criswell // 5482202a6SJohn Criswell // This file was developed by the LLVM research group and is distributed under 6482202a6SJohn Criswell // the University of Illinois Open Source 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" 16996fe010SChris Lattner #include "llvm/Constants.h" 17260b0c88SMisha Brukman #include "llvm/DerivedTypes.h" 18996fe010SChris Lattner #include "llvm/Module.h" 19260b0c88SMisha Brukman #include "llvm/ModuleProvider.h" 2070e37278SReid Spencer #include "llvm/ADT/Statistic.h" 21260b0c88SMisha Brukman #include "llvm/ExecutionEngine/ExecutionEngine.h" 22ad481312SChris Lattner #include "llvm/ExecutionEngine/GenericValue.h" 237c16caa3SReid Spencer #include "llvm/Support/Debug.h" 246d8dd189SChris Lattner #include "llvm/Support/MutexGuard.h" 2570e37278SReid Spencer #include "llvm/System/DynamicLibrary.h" 26*fde55674SDuncan Sands #include "llvm/System/Host.h" 2770e37278SReid Spencer #include "llvm/Target/TargetData.h" 2872ac14edSJeff Cohen #include <math.h> 2929681deeSChris Lattner using namespace llvm; 30996fe010SChris Lattner 31c346ecd7SChris Lattner STATISTIC(NumInitBytes, "Number of bytes of global vars initialized"); 32c346ecd7SChris Lattner STATISTIC(NumGlobals , "Number of global vars initialized"); 33996fe010SChris Lattner 342d52c1b8SChris Lattner ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0; 352d52c1b8SChris Lattner ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0; 362d52c1b8SChris Lattner 37fd6f3257SChris Lattner ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) { 3887aee74cSChris Lattner LazyCompilationDisabled = false; 390621caefSChris Lattner Modules.push_back(P); 40260b0c88SMisha Brukman assert(P && "ModuleProvider is null?"); 41260b0c88SMisha Brukman } 42260b0c88SMisha Brukman 4392f8b30dSBrian Gaeke ExecutionEngine::~ExecutionEngine() { 44603682adSReid Spencer clearAllGlobalMappings(); 450621caefSChris Lattner for (unsigned i = 0, e = Modules.size(); i != e; ++i) 460621caefSChris Lattner delete Modules[i]; 4792f8b30dSBrian Gaeke } 4892f8b30dSBrian Gaeke 49324fe890SDevang Patel /// removeModuleProvider - Remove a ModuleProvider from the list of modules. 50324fe890SDevang Patel /// Release module from ModuleProvider. 51324fe890SDevang Patel Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P, 52324fe890SDevang Patel std::string *ErrInfo) { 53324fe890SDevang Patel for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(), 54324fe890SDevang Patel E = Modules.end(); I != E; ++I) { 55324fe890SDevang Patel ModuleProvider *MP = *I; 56324fe890SDevang Patel if (MP == P) { 57324fe890SDevang Patel Modules.erase(I); 58324fe890SDevang Patel return MP->releaseModule(ErrInfo); 59324fe890SDevang Patel } 60324fe890SDevang Patel } 61324fe890SDevang Patel return NULL; 62324fe890SDevang Patel } 63324fe890SDevang Patel 640621caefSChris Lattner /// FindFunctionNamed - Search all of the active modules to find the one that 650621caefSChris Lattner /// defines FnName. This is very slow operation and shouldn't be used for 660621caefSChris Lattner /// general code. 670621caefSChris Lattner Function *ExecutionEngine::FindFunctionNamed(const char *FnName) { 680621caefSChris Lattner for (unsigned i = 0, e = Modules.size(); i != e; ++i) { 691241d6d5SReid Spencer if (Function *F = Modules[i]->getModule()->getFunction(FnName)) 700621caefSChris Lattner return F; 710621caefSChris Lattner } 720621caefSChris Lattner return 0; 730621caefSChris Lattner } 740621caefSChris Lattner 750621caefSChris Lattner 766d8dd189SChris Lattner /// addGlobalMapping - Tell the execution engine that the specified global is 776d8dd189SChris Lattner /// at the specified location. This is used internally as functions are JIT'd 786d8dd189SChris Lattner /// and as global variables are laid out in memory. It can and should also be 796d8dd189SChris Lattner /// used by clients of the EE that want to have an LLVM global overlay 806d8dd189SChris Lattner /// existing data in memory. 816d8dd189SChris Lattner void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) { 826d8dd189SChris Lattner MutexGuard locked(lock); 836d8dd189SChris Lattner 846d8dd189SChris Lattner void *&CurVal = state.getGlobalAddressMap(locked)[GV]; 856d8dd189SChris Lattner assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!"); 866d8dd189SChris Lattner CurVal = Addr; 876d8dd189SChris Lattner 886d8dd189SChris Lattner // If we are using the reverse mapping, add it too 896d8dd189SChris Lattner if (!state.getGlobalAddressReverseMap(locked).empty()) { 906d8dd189SChris Lattner const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr]; 916d8dd189SChris Lattner assert((V == 0 || GV == 0) && "GlobalMapping already established!"); 926d8dd189SChris Lattner V = GV; 936d8dd189SChris Lattner } 946d8dd189SChris Lattner } 956d8dd189SChris Lattner 966d8dd189SChris Lattner /// clearAllGlobalMappings - Clear all global mappings and start over again 976d8dd189SChris Lattner /// use in dynamic compilation scenarios when you want to move globals 986d8dd189SChris Lattner void ExecutionEngine::clearAllGlobalMappings() { 996d8dd189SChris Lattner MutexGuard locked(lock); 1006d8dd189SChris Lattner 1016d8dd189SChris Lattner state.getGlobalAddressMap(locked).clear(); 1026d8dd189SChris Lattner state.getGlobalAddressReverseMap(locked).clear(); 1036d8dd189SChris Lattner } 1046d8dd189SChris Lattner 1056d8dd189SChris Lattner /// updateGlobalMapping - Replace an existing mapping for GV with a new 1066d8dd189SChris Lattner /// address. This updates both maps as required. If "Addr" is null, the 1076d8dd189SChris Lattner /// entry for the global is removed from the mappings. 1086d8dd189SChris Lattner void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) { 1096d8dd189SChris Lattner MutexGuard locked(lock); 1106d8dd189SChris Lattner 1116d8dd189SChris Lattner // Deleting from the mapping? 1126d8dd189SChris Lattner if (Addr == 0) { 1136d8dd189SChris Lattner state.getGlobalAddressMap(locked).erase(GV); 1146d8dd189SChris Lattner if (!state.getGlobalAddressReverseMap(locked).empty()) 1156d8dd189SChris Lattner state.getGlobalAddressReverseMap(locked).erase(Addr); 1166d8dd189SChris Lattner return; 1176d8dd189SChris Lattner } 1186d8dd189SChris Lattner 1196d8dd189SChris Lattner void *&CurVal = state.getGlobalAddressMap(locked)[GV]; 1206d8dd189SChris Lattner if (CurVal && !state.getGlobalAddressReverseMap(locked).empty()) 1216d8dd189SChris Lattner state.getGlobalAddressReverseMap(locked).erase(CurVal); 1226d8dd189SChris Lattner CurVal = Addr; 1236d8dd189SChris Lattner 1246d8dd189SChris Lattner // If we are using the reverse mapping, add it too 1256d8dd189SChris Lattner if (!state.getGlobalAddressReverseMap(locked).empty()) { 1266d8dd189SChris Lattner const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr]; 1276d8dd189SChris Lattner assert((V == 0 || GV == 0) && "GlobalMapping already established!"); 1286d8dd189SChris Lattner V = GV; 1296d8dd189SChris Lattner } 1306d8dd189SChris Lattner } 1316d8dd189SChris Lattner 1326d8dd189SChris Lattner /// getPointerToGlobalIfAvailable - This returns the address of the specified 1336d8dd189SChris Lattner /// global value if it is has already been codegen'd, otherwise it returns null. 1346d8dd189SChris Lattner /// 1356d8dd189SChris Lattner void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) { 1366d8dd189SChris Lattner MutexGuard locked(lock); 1376d8dd189SChris Lattner 1386d8dd189SChris Lattner std::map<const GlobalValue*, void*>::iterator I = 1396d8dd189SChris Lattner state.getGlobalAddressMap(locked).find(GV); 1406d8dd189SChris Lattner return I != state.getGlobalAddressMap(locked).end() ? I->second : 0; 1416d8dd189SChris Lattner } 1426d8dd189SChris Lattner 143748e8579SChris Lattner /// getGlobalValueAtAddress - Return the LLVM global value object that starts 144748e8579SChris Lattner /// at the specified address. 145748e8579SChris Lattner /// 146748e8579SChris Lattner const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) { 14779876f52SReid Spencer MutexGuard locked(lock); 14879876f52SReid Spencer 149748e8579SChris Lattner // If we haven't computed the reverse mapping yet, do so first. 15079876f52SReid Spencer if (state.getGlobalAddressReverseMap(locked).empty()) { 1516d8dd189SChris Lattner for (std::map<const GlobalValue*, void *>::iterator 1526d8dd189SChris Lattner I = state.getGlobalAddressMap(locked).begin(), 1536d8dd189SChris Lattner E = state.getGlobalAddressMap(locked).end(); I != E; ++I) 1546d8dd189SChris Lattner state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second, 1556d8dd189SChris Lattner I->first)); 156748e8579SChris Lattner } 157748e8579SChris Lattner 158748e8579SChris Lattner std::map<void *, const GlobalValue*>::iterator I = 15979876f52SReid Spencer state.getGlobalAddressReverseMap(locked).find(Addr); 16079876f52SReid Spencer return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0; 161748e8579SChris Lattner } 1625a0d4829SChris Lattner 1635a0d4829SChris Lattner // CreateArgv - Turn a vector of strings into a nice argv style array of 1645a0d4829SChris Lattner // pointers to null terminated strings. 1655a0d4829SChris Lattner // 1665a0d4829SChris Lattner static void *CreateArgv(ExecutionEngine *EE, 1675a0d4829SChris Lattner const std::vector<std::string> &InputArgv) { 16820a631fdSOwen Anderson unsigned PtrSize = EE->getTargetData()->getPointerSize(); 1695a0d4829SChris Lattner char *Result = new char[(InputArgv.size()+1)*PtrSize]; 1705a0d4829SChris Lattner 1715834fdb3SBill Wendling DOUT << "ARGV = " << (void*)Result << "\n"; 1720d54e78aSReid Spencer const Type *SBytePtr = PointerType::get(Type::Int8Ty); 1735a0d4829SChris Lattner 1745a0d4829SChris Lattner for (unsigned i = 0; i != InputArgv.size(); ++i) { 1755a0d4829SChris Lattner unsigned Size = InputArgv[i].size()+1; 1765a0d4829SChris Lattner char *Dest = new char[Size]; 1775834fdb3SBill Wendling DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n"; 1785a0d4829SChris Lattner 1795a0d4829SChris Lattner std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest); 1805a0d4829SChris Lattner Dest[Size-1] = 0; 1815a0d4829SChris Lattner 1825a0d4829SChris Lattner // Endian safe: Result[i] = (PointerTy)Dest; 1835a0d4829SChris Lattner EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize), 1845a0d4829SChris Lattner SBytePtr); 1855a0d4829SChris Lattner } 1865a0d4829SChris Lattner 1875a0d4829SChris Lattner // Null terminate it 1885a0d4829SChris Lattner EE->StoreValueToMemory(PTOGV(0), 1895a0d4829SChris Lattner (GenericValue*)(Result+InputArgv.size()*PtrSize), 1905a0d4829SChris Lattner SBytePtr); 1915a0d4829SChris Lattner return Result; 1925a0d4829SChris Lattner } 1935a0d4829SChris Lattner 194faae50b6SChris Lattner 195faae50b6SChris Lattner /// runStaticConstructorsDestructors - This method is used to execute all of 1960621caefSChris Lattner /// the static constructors or destructors for a program, depending on the 197faae50b6SChris Lattner /// value of isDtors. 198faae50b6SChris Lattner void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) { 199faae50b6SChris Lattner const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors"; 2000621caefSChris Lattner 2010621caefSChris Lattner // Execute global ctors/dtors for each module in the program. 2020621caefSChris Lattner for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 2030621caefSChris Lattner GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name); 204fe36eaebSChris Lattner 205fe36eaebSChris Lattner // If this global has internal linkage, or if it has a use, then it must be 206fe36eaebSChris Lattner // an old-style (llvmgcc3) static ctor with __main linked in and in use. If 2070621caefSChris Lattner // this is the case, don't execute any of the global ctors, __main will do 2080621caefSChris Lattner // it. 2095301e7c6SReid Spencer if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue; 210faae50b6SChris Lattner 2110621caefSChris Lattner // Should be an array of '{ int, void ()* }' structs. The first value is 2120621caefSChris Lattner // the init priority, which we ignore. 213faae50b6SChris Lattner ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer()); 2140621caefSChris Lattner if (!InitList) continue; 215faae50b6SChris Lattner for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) 2160621caefSChris Lattner if (ConstantStruct *CS = 2170621caefSChris Lattner dyn_cast<ConstantStruct>(InitList->getOperand(i))) { 2180621caefSChris Lattner if (CS->getNumOperands() != 2) break; // Not array of 2-element structs. 219faae50b6SChris Lattner 220faae50b6SChris Lattner Constant *FP = CS->getOperand(1); 221faae50b6SChris Lattner if (FP->isNullValue()) 2220621caefSChris Lattner break; // Found a null terminator, exit. 223faae50b6SChris Lattner 224faae50b6SChris Lattner if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP)) 2256c38f0bbSReid Spencer if (CE->isCast()) 226faae50b6SChris Lattner FP = CE->getOperand(0); 227faae50b6SChris Lattner if (Function *F = dyn_cast<Function>(FP)) { 228faae50b6SChris Lattner // Execute the ctor/dtor function! 229faae50b6SChris Lattner runFunction(F, std::vector<GenericValue>()); 230faae50b6SChris Lattner } 231faae50b6SChris Lattner } 232faae50b6SChris Lattner } 2330621caefSChris Lattner } 234faae50b6SChris Lattner 2355a0d4829SChris Lattner /// runFunctionAsMain - This is a helper function which wraps runFunction to 2365a0d4829SChris Lattner /// handle the common task of starting up main with the specified argc, argv, 2375a0d4829SChris Lattner /// and envp parameters. 2385a0d4829SChris Lattner int ExecutionEngine::runFunctionAsMain(Function *Fn, 2395a0d4829SChris Lattner const std::vector<std::string> &argv, 2405a0d4829SChris Lattner const char * const * envp) { 2415a0d4829SChris Lattner std::vector<GenericValue> GVArgs; 2425a0d4829SChris Lattner GenericValue GVArgc; 24387aa65f4SReid Spencer GVArgc.IntVal = APInt(32, argv.size()); 2448c32c111SAnton Korobeynikov 2458c32c111SAnton Korobeynikov // Check main() type 246b1cad0b3SChris Lattner unsigned NumArgs = Fn->getFunctionType()->getNumParams(); 2478c32c111SAnton Korobeynikov const FunctionType *FTy = Fn->getFunctionType(); 2488c32c111SAnton Korobeynikov const Type* PPInt8Ty = PointerType::get(PointerType::get(Type::Int8Ty)); 2498c32c111SAnton Korobeynikov switch (NumArgs) { 2508c32c111SAnton Korobeynikov case 3: 2518c32c111SAnton Korobeynikov if (FTy->getParamType(2) != PPInt8Ty) { 2528c32c111SAnton Korobeynikov cerr << "Invalid type for third argument of main() supplied\n"; 2538c32c111SAnton Korobeynikov abort(); 2548c32c111SAnton Korobeynikov } 255b781886dSAnton Korobeynikov // FALLS THROUGH 2568c32c111SAnton Korobeynikov case 2: 2578c32c111SAnton Korobeynikov if (FTy->getParamType(1) != PPInt8Ty) { 2588c32c111SAnton Korobeynikov cerr << "Invalid type for second argument of main() supplied\n"; 2598c32c111SAnton Korobeynikov abort(); 2608c32c111SAnton Korobeynikov } 261b781886dSAnton Korobeynikov // FALLS THROUGH 2628c32c111SAnton Korobeynikov case 1: 2638c32c111SAnton Korobeynikov if (FTy->getParamType(0) != Type::Int32Ty) { 2648c32c111SAnton Korobeynikov cerr << "Invalid type for first argument of main() supplied\n"; 2658c32c111SAnton Korobeynikov abort(); 2668c32c111SAnton Korobeynikov } 267b781886dSAnton Korobeynikov // FALLS THROUGH 2688c32c111SAnton Korobeynikov case 0: 2698c32c111SAnton Korobeynikov if (FTy->getReturnType() != Type::Int32Ty && 2708c32c111SAnton Korobeynikov FTy->getReturnType() != Type::VoidTy) { 2718c32c111SAnton Korobeynikov cerr << "Invalid return type of main() supplied\n"; 2728c32c111SAnton Korobeynikov abort(); 2738c32c111SAnton Korobeynikov } 2748c32c111SAnton Korobeynikov break; 2758c32c111SAnton Korobeynikov default: 2768c32c111SAnton Korobeynikov cerr << "Invalid number of arguments of main() supplied\n"; 2778c32c111SAnton Korobeynikov abort(); 2788c32c111SAnton Korobeynikov } 2798c32c111SAnton Korobeynikov 280b1cad0b3SChris Lattner if (NumArgs) { 2815a0d4829SChris Lattner GVArgs.push_back(GVArgc); // Arg #0 = argc. 282b1cad0b3SChris Lattner if (NumArgs > 1) { 2835a0d4829SChris Lattner GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv. 284b1cad0b3SChris Lattner assert(((char **)GVTOP(GVArgs[1]))[0] && 285b1cad0b3SChris Lattner "argv[0] was null after CreateArgv"); 286b1cad0b3SChris Lattner if (NumArgs > 2) { 2875a0d4829SChris Lattner std::vector<std::string> EnvVars; 2885a0d4829SChris Lattner for (unsigned i = 0; envp[i]; ++i) 2895a0d4829SChris Lattner EnvVars.push_back(envp[i]); 2905a0d4829SChris Lattner GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp. 291b1cad0b3SChris Lattner } 292b1cad0b3SChris Lattner } 293b1cad0b3SChris Lattner } 29487aa65f4SReid Spencer return runFunction(Fn, GVArgs).IntVal.getZExtValue(); 2955a0d4829SChris Lattner } 2965a0d4829SChris Lattner 297260b0c88SMisha Brukman /// If possible, create a JIT, unless the caller specifically requests an 298260b0c88SMisha Brukman /// Interpreter or there's an error. If even an Interpreter cannot be created, 299260b0c88SMisha Brukman /// NULL is returned. 300857c21b4SMisha Brukman /// 3012f1e2002SMisha Brukman ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP, 302603682adSReid Spencer bool ForceInterpreter, 303603682adSReid Spencer std::string *ErrorStr) { 3044bd3bd5bSBrian Gaeke ExecutionEngine *EE = 0; 3054bd3bd5bSBrian Gaeke 306c8c6c03dSChris Lattner // Unless the interpreter was explicitly selected, try making a JIT. 3072d52c1b8SChris Lattner if (!ForceInterpreter && JITCtor) 308603682adSReid Spencer EE = JITCtor(MP, ErrorStr); 3094bd3bd5bSBrian Gaeke 3104bd3bd5bSBrian Gaeke // If we can't make a JIT, make an interpreter instead. 3112d52c1b8SChris Lattner if (EE == 0 && InterpCtor) 312603682adSReid Spencer EE = InterpCtor(MP, ErrorStr); 313c8c6c03dSChris Lattner 3140b2de9f2SChris Lattner if (EE) { 31570e37278SReid Spencer // Make sure we can resolve symbols in the program as well. The zero arg 31670e37278SReid Spencer // to the function tells DynamicLibrary to load the program, not a library. 317edaf0b46SChris Lattner if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr)) { 318edaf0b46SChris Lattner delete EE; 319edaf0b46SChris Lattner return 0; 32063539389SChris Lattner } 3210b2de9f2SChris Lattner } 32270e37278SReid Spencer 3234bd3bd5bSBrian Gaeke return EE; 3244bd3bd5bSBrian Gaeke } 3254bd3bd5bSBrian Gaeke 326b5163bb9SChris Lattner ExecutionEngine *ExecutionEngine::create(Module *M) { 327b5163bb9SChris Lattner return create(new ExistingModuleProvider(M)); 328b5163bb9SChris Lattner } 329b5163bb9SChris Lattner 330857c21b4SMisha Brukman /// getPointerToGlobal - This returns the address of the specified global 331857c21b4SMisha Brukman /// value. This may involve code generation if it's a function. 332857c21b4SMisha Brukman /// 333996fe010SChris Lattner void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) { 3341678e859SBrian Gaeke if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV))) 335996fe010SChris Lattner return getPointerToFunction(F); 336996fe010SChris Lattner 33779876f52SReid Spencer MutexGuard locked(lock); 33869e84901SJeff Cohen void *p = state.getGlobalAddressMap(locked)[GV]; 33969e84901SJeff Cohen if (p) 34069e84901SJeff Cohen return p; 34169e84901SJeff Cohen 34269e84901SJeff Cohen // Global variable might have been added since interpreter started. 34369e84901SJeff Cohen if (GlobalVariable *GVar = 34469e84901SJeff Cohen const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV))) 34569e84901SJeff Cohen EmitGlobalVariable(GVar); 34669e84901SJeff Cohen else 3474da5e17cSChris Lattner assert(0 && "Global hasn't had an address allocated yet!"); 34879876f52SReid Spencer return state.getGlobalAddressMap(locked)[GV]; 349996fe010SChris Lattner } 350996fe010SChris Lattner 3516c38f0bbSReid Spencer /// This function converts a Constant* into a GenericValue. The interesting 3526c38f0bbSReid Spencer /// part is if C is a ConstantExpr. 3532dc9f132SReid Spencer /// @brief Get a GenericValue for a Constant* 354996fe010SChris Lattner GenericValue ExecutionEngine::getConstantValue(const Constant *C) { 3556c38f0bbSReid Spencer // If its undefined, return the garbage. 3564fd528f2SReid Spencer if (isa<UndefValue>(C)) 3574fd528f2SReid Spencer return GenericValue(); 3589de0d14dSChris Lattner 3596c38f0bbSReid Spencer // If the value is a ConstantExpr 3606c38f0bbSReid Spencer if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 3614fd528f2SReid Spencer Constant *Op0 = CE->getOperand(0); 3629de0d14dSChris Lattner switch (CE->getOpcode()) { 3639de0d14dSChris Lattner case Instruction::GetElementPtr: { 3646c38f0bbSReid Spencer // Compute the index 3654fd528f2SReid Spencer GenericValue Result = getConstantValue(Op0); 366c44bd78aSChris Lattner SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end()); 3679de0d14dSChris Lattner uint64_t Offset = 3684fd528f2SReid Spencer TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size()); 3699de0d14dSChris Lattner 37087aa65f4SReid Spencer char* tmp = (char*) Result.PointerVal; 37187aa65f4SReid Spencer Result = PTOGV(tmp + Offset); 3729de0d14dSChris Lattner return Result; 3739de0d14dSChris Lattner } 3744fd528f2SReid Spencer case Instruction::Trunc: { 3754fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 3764fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 3774fd528f2SReid Spencer GV.IntVal = GV.IntVal.trunc(BitWidth); 3784fd528f2SReid Spencer return GV; 3794fd528f2SReid Spencer } 3804fd528f2SReid Spencer case Instruction::ZExt: { 3814fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 3824fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 3834fd528f2SReid Spencer GV.IntVal = GV.IntVal.zext(BitWidth); 3844fd528f2SReid Spencer return GV; 3854fd528f2SReid Spencer } 3864fd528f2SReid Spencer case Instruction::SExt: { 3874fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 3884fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 3894fd528f2SReid Spencer GV.IntVal = GV.IntVal.sext(BitWidth); 3904fd528f2SReid Spencer return GV; 3914fd528f2SReid Spencer } 3924fd528f2SReid Spencer case Instruction::FPTrunc: { 393a1336cf5SDale Johannesen // FIXME long double 3944fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 3954fd528f2SReid Spencer GV.FloatVal = float(GV.DoubleVal); 3964fd528f2SReid Spencer return GV; 3974fd528f2SReid Spencer } 3984fd528f2SReid Spencer case Instruction::FPExt:{ 399a1336cf5SDale Johannesen // FIXME long double 4004fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 4014fd528f2SReid Spencer GV.DoubleVal = double(GV.FloatVal); 4024fd528f2SReid Spencer return GV; 4034fd528f2SReid Spencer } 4044fd528f2SReid Spencer case Instruction::UIToFP: { 4054fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 4064fd528f2SReid Spencer if (CE->getType() == Type::FloatTy) 4074fd528f2SReid Spencer GV.FloatVal = float(GV.IntVal.roundToDouble()); 408a1336cf5SDale Johannesen else if (CE->getType() == Type::DoubleTy) 4094fd528f2SReid Spencer GV.DoubleVal = GV.IntVal.roundToDouble(); 410a1336cf5SDale Johannesen else if (CE->getType() == Type::X86_FP80Ty) { 411a1336cf5SDale Johannesen const uint64_t zero[] = {0, 0}; 412a1336cf5SDale Johannesen APFloat apf = APFloat(APInt(80, 2, zero)); 4135f009733SNeil Booth (void)apf.convertFromZeroExtendedInteger(GV.IntVal.getRawData(), 4144230512fSDale Johannesen GV.IntVal.getBitWidth(), false, 4159150652bSDale Johannesen APFloat::rmNearestTiesToEven); 416a1336cf5SDale Johannesen GV.IntVal = apf.convertToAPInt(); 417a1336cf5SDale Johannesen } 4184fd528f2SReid Spencer return GV; 4194fd528f2SReid Spencer } 4204fd528f2SReid Spencer case Instruction::SIToFP: { 4214fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 4224fd528f2SReid Spencer if (CE->getType() == Type::FloatTy) 4234fd528f2SReid Spencer GV.FloatVal = float(GV.IntVal.signedRoundToDouble()); 424a1336cf5SDale Johannesen else if (CE->getType() == Type::DoubleTy) 4254fd528f2SReid Spencer GV.DoubleVal = GV.IntVal.signedRoundToDouble(); 426a1336cf5SDale Johannesen else if (CE->getType() == Type::X86_FP80Ty) { 427a1336cf5SDale Johannesen const uint64_t zero[] = { 0, 0}; 428a1336cf5SDale Johannesen APFloat apf = APFloat(APInt(80, 2, zero)); 4295f009733SNeil Booth (void)apf.convertFromZeroExtendedInteger(GV.IntVal.getRawData(), 4304230512fSDale Johannesen GV.IntVal.getBitWidth(), true, 4319150652bSDale Johannesen APFloat::rmNearestTiesToEven); 432a1336cf5SDale Johannesen GV.IntVal = apf.convertToAPInt(); 433a1336cf5SDale Johannesen } 4344fd528f2SReid Spencer return GV; 4354fd528f2SReid Spencer } 4364fd528f2SReid Spencer case Instruction::FPToUI: // double->APInt conversion handles sign 4374fd528f2SReid Spencer case Instruction::FPToSI: { 4384fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 4394fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 4404fd528f2SReid Spencer if (Op0->getType() == Type::FloatTy) 4414fd528f2SReid Spencer GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth); 442a1336cf5SDale Johannesen else if (Op0->getType() == Type::DoubleTy) 4434fd528f2SReid Spencer GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth); 444a1336cf5SDale Johannesen else if (Op0->getType() == Type::X86_FP80Ty) { 445a1336cf5SDale Johannesen APFloat apf = APFloat(GV.IntVal); 446a1336cf5SDale Johannesen uint64_t v; 447a1336cf5SDale Johannesen (void)apf.convertToInteger(&v, BitWidth, 448a1336cf5SDale Johannesen CE->getOpcode()==Instruction::FPToSI, 449a1336cf5SDale Johannesen APFloat::rmTowardZero); 450a1336cf5SDale Johannesen GV.IntVal = v; // endian? 451a1336cf5SDale Johannesen } 4524fd528f2SReid Spencer return GV; 4534fd528f2SReid Spencer } 4546c38f0bbSReid Spencer case Instruction::PtrToInt: { 4554fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 4564fd528f2SReid Spencer uint32_t PtrWidth = TD->getPointerSizeInBits(); 4574fd528f2SReid Spencer GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal)); 4584fd528f2SReid Spencer return GV; 4594fd528f2SReid Spencer } 4604fd528f2SReid Spencer case Instruction::IntToPtr: { 4614fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 4624fd528f2SReid Spencer uint32_t PtrWidth = TD->getPointerSizeInBits(); 4634fd528f2SReid Spencer if (PtrWidth != GV.IntVal.getBitWidth()) 4644fd528f2SReid Spencer GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth); 4654fd528f2SReid Spencer assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width"); 4664fd528f2SReid Spencer GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue())); 4676c38f0bbSReid Spencer return GV; 4686c38f0bbSReid Spencer } 4696c38f0bbSReid Spencer case Instruction::BitCast: { 4704fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 4714fd528f2SReid Spencer const Type* DestTy = CE->getType(); 4724fd528f2SReid Spencer switch (Op0->getType()->getTypeID()) { 4734fd528f2SReid Spencer default: assert(0 && "Invalid bitcast operand"); 4744fd528f2SReid Spencer case Type::IntegerTyID: 4754fd528f2SReid Spencer assert(DestTy->isFloatingPoint() && "invalid bitcast"); 4764fd528f2SReid Spencer if (DestTy == Type::FloatTy) 4774fd528f2SReid Spencer GV.FloatVal = GV.IntVal.bitsToFloat(); 4784fd528f2SReid Spencer else if (DestTy == Type::DoubleTy) 4794fd528f2SReid Spencer GV.DoubleVal = GV.IntVal.bitsToDouble(); 4806c38f0bbSReid Spencer break; 4814fd528f2SReid Spencer case Type::FloatTyID: 4824fd528f2SReid Spencer assert(DestTy == Type::Int32Ty && "Invalid bitcast"); 4834fd528f2SReid Spencer GV.IntVal.floatToBits(GV.FloatVal); 4844fd528f2SReid Spencer break; 4854fd528f2SReid Spencer case Type::DoubleTyID: 4864fd528f2SReid Spencer assert(DestTy == Type::Int64Ty && "Invalid bitcast"); 4874fd528f2SReid Spencer GV.IntVal.doubleToBits(GV.DoubleVal); 4884fd528f2SReid Spencer break; 4894fd528f2SReid Spencer case Type::PointerTyID: 4904fd528f2SReid Spencer assert(isa<PointerType>(DestTy) && "Invalid bitcast"); 4914fd528f2SReid Spencer break; // getConstantValue(Op0) above already converted it 4926c38f0bbSReid Spencer } 4934fd528f2SReid Spencer return GV; 49468cbcc3eSChris Lattner } 49568cbcc3eSChris Lattner case Instruction::Add: 4964fd528f2SReid Spencer case Instruction::Sub: 4974fd528f2SReid Spencer case Instruction::Mul: 4984fd528f2SReid Spencer case Instruction::UDiv: 4994fd528f2SReid Spencer case Instruction::SDiv: 5004fd528f2SReid Spencer case Instruction::URem: 5014fd528f2SReid Spencer case Instruction::SRem: 5024fd528f2SReid Spencer case Instruction::And: 5034fd528f2SReid Spencer case Instruction::Or: 5044fd528f2SReid Spencer case Instruction::Xor: { 5054fd528f2SReid Spencer GenericValue LHS = getConstantValue(Op0); 5064fd528f2SReid Spencer GenericValue RHS = getConstantValue(CE->getOperand(1)); 5074fd528f2SReid Spencer GenericValue GV; 508c4e6bb5fSChris Lattner switch (CE->getOperand(0)->getType()->getTypeID()) { 509c4e6bb5fSChris Lattner default: assert(0 && "Bad add type!"); abort(); 5107a9c62baSReid Spencer case Type::IntegerTyID: 5114fd528f2SReid Spencer switch (CE->getOpcode()) { 5124fd528f2SReid Spencer default: assert(0 && "Invalid integer opcode"); 5134fd528f2SReid Spencer case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break; 5144fd528f2SReid Spencer case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break; 5154fd528f2SReid Spencer case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break; 5164fd528f2SReid Spencer case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break; 5174fd528f2SReid Spencer case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break; 5184fd528f2SReid Spencer case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break; 5194fd528f2SReid Spencer case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break; 5204fd528f2SReid Spencer case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break; 5214fd528f2SReid Spencer case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break; 5224fd528f2SReid Spencer case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break; 5234fd528f2SReid Spencer } 524c4e6bb5fSChris Lattner break; 525c4e6bb5fSChris Lattner case Type::FloatTyID: 5264fd528f2SReid Spencer switch (CE->getOpcode()) { 5274fd528f2SReid Spencer default: assert(0 && "Invalid float opcode"); abort(); 5284fd528f2SReid Spencer case Instruction::Add: 5294fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break; 5304fd528f2SReid Spencer case Instruction::Sub: 5314fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break; 5324fd528f2SReid Spencer case Instruction::Mul: 5334fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break; 5344fd528f2SReid Spencer case Instruction::FDiv: 5354fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break; 5364fd528f2SReid Spencer case Instruction::FRem: 5374fd528f2SReid Spencer GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break; 5384fd528f2SReid Spencer } 539c4e6bb5fSChris Lattner break; 540c4e6bb5fSChris Lattner case Type::DoubleTyID: 5414fd528f2SReid Spencer switch (CE->getOpcode()) { 5424fd528f2SReid Spencer default: assert(0 && "Invalid double opcode"); abort(); 5434fd528f2SReid Spencer case Instruction::Add: 5444fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break; 5454fd528f2SReid Spencer case Instruction::Sub: 5464fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break; 5474fd528f2SReid Spencer case Instruction::Mul: 5484fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break; 5494fd528f2SReid Spencer case Instruction::FDiv: 5504fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break; 5514fd528f2SReid Spencer case Instruction::FRem: 5524fd528f2SReid Spencer GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break; 5534fd528f2SReid Spencer } 554c4e6bb5fSChris Lattner break; 555a1336cf5SDale Johannesen case Type::X86_FP80TyID: 556a1336cf5SDale Johannesen case Type::PPC_FP128TyID: 557a1336cf5SDale Johannesen case Type::FP128TyID: { 558a1336cf5SDale Johannesen APFloat apfLHS = APFloat(LHS.IntVal); 559a1336cf5SDale Johannesen switch (CE->getOpcode()) { 560a1336cf5SDale Johannesen default: assert(0 && "Invalid long double opcode"); abort(); 561a1336cf5SDale Johannesen case Instruction::Add: 562a1336cf5SDale Johannesen apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 563a1336cf5SDale Johannesen GV.IntVal = apfLHS.convertToAPInt(); 564a1336cf5SDale Johannesen break; 565a1336cf5SDale Johannesen case Instruction::Sub: 566a1336cf5SDale Johannesen apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 567a1336cf5SDale Johannesen GV.IntVal = apfLHS.convertToAPInt(); 568a1336cf5SDale Johannesen break; 569a1336cf5SDale Johannesen case Instruction::Mul: 570a1336cf5SDale Johannesen apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 571a1336cf5SDale Johannesen GV.IntVal = apfLHS.convertToAPInt(); 572a1336cf5SDale Johannesen break; 573a1336cf5SDale Johannesen case Instruction::FDiv: 574a1336cf5SDale Johannesen apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 575a1336cf5SDale Johannesen GV.IntVal = apfLHS.convertToAPInt(); 576a1336cf5SDale Johannesen break; 577a1336cf5SDale Johannesen case Instruction::FRem: 578a1336cf5SDale Johannesen apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 579a1336cf5SDale Johannesen GV.IntVal = apfLHS.convertToAPInt(); 580a1336cf5SDale Johannesen break; 581a1336cf5SDale Johannesen } 582a1336cf5SDale Johannesen } 583a1336cf5SDale Johannesen break; 584c4e6bb5fSChris Lattner } 5854fd528f2SReid Spencer return GV; 5864fd528f2SReid Spencer } 5879de0d14dSChris Lattner default: 58868cbcc3eSChris Lattner break; 58968cbcc3eSChris Lattner } 5904fd528f2SReid Spencer cerr << "ConstantExpr not handled: " << *CE << "\n"; 5919de0d14dSChris Lattner abort(); 5929de0d14dSChris Lattner } 593996fe010SChris Lattner 5944fd528f2SReid Spencer GenericValue Result; 5956b727599SChris Lattner switch (C->getType()->getTypeID()) { 59687aa65f4SReid Spencer case Type::FloatTyID: 597bed9dc42SDale Johannesen Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat(); 5987a9c62baSReid Spencer break; 59987aa65f4SReid Spencer case Type::DoubleTyID: 600bed9dc42SDale Johannesen Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble(); 60187aa65f4SReid Spencer break; 602a1336cf5SDale Johannesen case Type::X86_FP80TyID: 603a1336cf5SDale Johannesen case Type::FP128TyID: 604a1336cf5SDale Johannesen case Type::PPC_FP128TyID: 605a1336cf5SDale Johannesen Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt(); 606a1336cf5SDale Johannesen break; 60787aa65f4SReid Spencer case Type::IntegerTyID: 60887aa65f4SReid Spencer Result.IntVal = cast<ConstantInt>(C)->getValue(); 60987aa65f4SReid Spencer break; 610996fe010SChris Lattner case Type::PointerTyID: 6116a0fd73bSReid Spencer if (isa<ConstantPointerNull>(C)) 612996fe010SChris Lattner Result.PointerVal = 0; 6136a0fd73bSReid Spencer else if (const Function *F = dyn_cast<Function>(C)) 6146a0fd73bSReid Spencer Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F))); 6156a0fd73bSReid Spencer else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C)) 6166a0fd73bSReid Spencer Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV))); 617e6492f10SChris Lattner else 618996fe010SChris Lattner assert(0 && "Unknown constant pointer type!"); 619996fe010SChris Lattner break; 620996fe010SChris Lattner default: 6214fd528f2SReid Spencer cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n"; 6229de0d14dSChris Lattner abort(); 623996fe010SChris Lattner } 624996fe010SChris Lattner return Result; 625996fe010SChris Lattner } 626996fe010SChris Lattner 6274ca2ea5bSNate Begeman /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr 6284ca2ea5bSNate Begeman /// is the address of the memory at which to store Val, cast to GenericValue *. 6294ca2ea5bSNate Begeman /// It is not a pointer to a GenericValue containing the address at which to 6304ca2ea5bSNate Begeman /// store Val. 631857c21b4SMisha Brukman /// 6324e42790cSReid Spencer void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr, 633996fe010SChris Lattner const Type *Ty) { 6346b727599SChris Lattner switch (Ty->getTypeID()) { 6357a9c62baSReid Spencer case Type::IntegerTyID: { 6367a9c62baSReid Spencer unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth(); 6375c65cb46SDuncan Sands unsigned StoreBytes = (BitWidth + 7)/8; 6385c65cb46SDuncan Sands uint8_t *Src = (uint8_t *)Val.IntVal.getRawData(); 6395c65cb46SDuncan Sands uint8_t *Dst = (uint8_t *)Ptr; 6405c65cb46SDuncan Sands 641*fde55674SDuncan Sands if (sys::littleEndianHost()) 6425c65cb46SDuncan Sands // Little-endian host - the source is ordered from LSB to MSB. 6435c65cb46SDuncan Sands // Order the destination from LSB to MSB: Do a straight copy. 6445c65cb46SDuncan Sands memcpy(Dst, Src, StoreBytes); 6455c65cb46SDuncan Sands else { 6465c65cb46SDuncan Sands // Big-endian host - the source is an array of 64 bit words ordered from 6475c65cb46SDuncan Sands // LSW to MSW. Each word is ordered from MSB to LSB. 6485c65cb46SDuncan Sands // Order the destination from MSB to LSB: Reverse the word order, but not 6495c65cb46SDuncan Sands // the bytes in a word. 6505c65cb46SDuncan Sands while (StoreBytes > sizeof(uint64_t)) { 6515c65cb46SDuncan Sands StoreBytes -= sizeof(uint64_t); 6525c65cb46SDuncan Sands // May not be aligned so use memcpy. 6535c65cb46SDuncan Sands memcpy(Dst + StoreBytes, Src, sizeof(uint64_t)); 6545c65cb46SDuncan Sands Src += sizeof(uint64_t); 6555c65cb46SDuncan Sands } 6565c65cb46SDuncan Sands 6575c65cb46SDuncan Sands memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes); 658815f8dd2SReid Spencer } 659996fe010SChris Lattner break; 6607a9c62baSReid Spencer } 661996fe010SChris Lattner case Type::FloatTyID: 66287aa65f4SReid Spencer *((float*)Ptr) = Val.FloatVal; 66387aa65f4SReid Spencer break; 66487aa65f4SReid Spencer case Type::DoubleTyID: 66587aa65f4SReid Spencer *((double*)Ptr) = Val.DoubleVal; 666996fe010SChris Lattner break; 667a1336cf5SDale Johannesen case Type::X86_FP80TyID: { 668a1336cf5SDale Johannesen uint16_t *Dest = (uint16_t*)Ptr; 669a1336cf5SDale Johannesen const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData(); 670a1336cf5SDale Johannesen // This is endian dependent, but it will only work on x86 anyway. 671a1336cf5SDale Johannesen Dest[0] = Src[4]; 672a1336cf5SDale Johannesen Dest[1] = Src[0]; 673a1336cf5SDale Johannesen Dest[2] = Src[1]; 674a1336cf5SDale Johannesen Dest[3] = Src[2]; 675a1336cf5SDale Johannesen Dest[4] = Src[3]; 676a1336cf5SDale Johannesen break; 677a1336cf5SDale Johannesen } 6787a9c62baSReid Spencer case Type::PointerTyID: 67987aa65f4SReid Spencer *((PointerTy*)Ptr) = Val.PointerVal; 680996fe010SChris Lattner break; 681996fe010SChris Lattner default: 682f3baad3eSBill Wendling cerr << "Cannot store value of type " << *Ty << "!\n"; 683996fe010SChris Lattner } 684996fe010SChris Lattner } 685996fe010SChris Lattner 686857c21b4SMisha Brukman /// FIXME: document 687857c21b4SMisha Brukman /// 68800919f57SReid Spencer void ExecutionEngine::LoadValueFromMemory(GenericValue &Result, 68900919f57SReid Spencer GenericValue *Ptr, 6907f389e8cSChris Lattner const Type *Ty) { 6916b727599SChris Lattner switch (Ty->getTypeID()) { 6927a9c62baSReid Spencer case Type::IntegerTyID: { 6937a9c62baSReid Spencer unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth(); 6945c65cb46SDuncan Sands unsigned LoadBytes = (BitWidth + 7)/8; 6955c65cb46SDuncan Sands 6965c65cb46SDuncan Sands // An APInt with all words initially zero. 6975c65cb46SDuncan Sands Result.IntVal = APInt(BitWidth, 0); 6985c65cb46SDuncan Sands 6995c65cb46SDuncan Sands uint8_t *Src = (uint8_t *)Ptr; 7005c65cb46SDuncan Sands uint8_t *Dst = (uint8_t *)Result.IntVal.getRawData(); 7015c65cb46SDuncan Sands 702*fde55674SDuncan Sands if (sys::littleEndianHost()) 7035c65cb46SDuncan Sands // Little-endian host - the destination must be ordered from LSB to MSB. 7045c65cb46SDuncan Sands // The source is ordered from LSB to MSB: Do a straight copy. 7055c65cb46SDuncan Sands memcpy(Dst, Src, LoadBytes); 7065c65cb46SDuncan Sands else { 7075c65cb46SDuncan Sands // Big-endian - the destination is an array of 64 bit words ordered from 7085c65cb46SDuncan Sands // LSW to MSW. Each word must be ordered from MSB to LSB. The source is 7095c65cb46SDuncan Sands // ordered from MSB to LSB: Reverse the word order, but not the bytes in 7105c65cb46SDuncan Sands // a word. 7115c65cb46SDuncan Sands while (LoadBytes > sizeof(uint64_t)) { 7125c65cb46SDuncan Sands LoadBytes -= sizeof(uint64_t); 7135c65cb46SDuncan Sands // May not be aligned so use memcpy. 7145c65cb46SDuncan Sands memcpy(Dst, Src + LoadBytes, sizeof(uint64_t)); 7155c65cb46SDuncan Sands Dst += sizeof(uint64_t); 7165c65cb46SDuncan Sands } 7175c65cb46SDuncan Sands 7185c65cb46SDuncan Sands memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes); 7195c65cb46SDuncan Sands } 7207f389e8cSChris Lattner break; 7217a9c62baSReid Spencer } 7227f389e8cSChris Lattner case Type::FloatTyID: 72387aa65f4SReid Spencer Result.FloatVal = *((float*)Ptr); 72487aa65f4SReid Spencer break; 72587aa65f4SReid Spencer case Type::DoubleTyID: 72687aa65f4SReid Spencer Result.DoubleVal = *((double*)Ptr); 7277f389e8cSChris Lattner break; 7287a9c62baSReid Spencer case Type::PointerTyID: 72987aa65f4SReid Spencer Result.PointerVal = *((PointerTy*)Ptr); 7307f389e8cSChris Lattner break; 731a1336cf5SDale Johannesen case Type::X86_FP80TyID: { 732a1336cf5SDale Johannesen // This is endian dependent, but it will only work on x86 anyway. 733ff306287SDuncan Sands uint16_t *p = (uint16_t*)Ptr; 734ff306287SDuncan Sands union { 735ff306287SDuncan Sands uint16_t x[8]; 736ff306287SDuncan Sands uint64_t y[2]; 737ff306287SDuncan Sands }; 738a1336cf5SDale Johannesen x[0] = p[1]; 739a1336cf5SDale Johannesen x[1] = p[2]; 740a1336cf5SDale Johannesen x[2] = p[3]; 741a1336cf5SDale Johannesen x[3] = p[4]; 742a1336cf5SDale Johannesen x[4] = p[0]; 743ff306287SDuncan Sands Result.IntVal = APInt(80, 2, y); 744a1336cf5SDale Johannesen break; 745a1336cf5SDale Johannesen } 7467f389e8cSChris Lattner default: 747f3baad3eSBill Wendling cerr << "Cannot load value of type " << *Ty << "!\n"; 7487f389e8cSChris Lattner abort(); 7497f389e8cSChris Lattner } 7507f389e8cSChris Lattner } 7517f389e8cSChris Lattner 752996fe010SChris Lattner // InitializeMemory - Recursive function to apply a Constant value into the 753996fe010SChris Lattner // specified memory location... 754996fe010SChris Lattner // 755996fe010SChris Lattner void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) { 75661753bf8SChris Lattner if (isa<UndefValue>(Init)) { 75761753bf8SChris Lattner return; 758d84d35baSReid Spencer } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) { 75969d62138SRobert Bocchino unsigned ElementSize = 76044b8721dSDuncan Sands getTargetData()->getABITypeSize(CP->getType()->getElementType()); 76169d62138SRobert Bocchino for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) 76269d62138SRobert Bocchino InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize); 76369d62138SRobert Bocchino return; 76461753bf8SChris Lattner } else if (Init->getType()->isFirstClassType()) { 765996fe010SChris Lattner GenericValue Val = getConstantValue(Init); 766996fe010SChris Lattner StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType()); 767996fe010SChris Lattner return; 768834b1272SChris Lattner } else if (isa<ConstantAggregateZero>(Init)) { 76944b8721dSDuncan Sands memset(Addr, 0, (size_t)getTargetData()->getABITypeSize(Init->getType())); 770834b1272SChris Lattner return; 771996fe010SChris Lattner } 772996fe010SChris Lattner 7736b727599SChris Lattner switch (Init->getType()->getTypeID()) { 774996fe010SChris Lattner case Type::ArrayTyID: { 775996fe010SChris Lattner const ConstantArray *CPA = cast<ConstantArray>(Init); 776996fe010SChris Lattner unsigned ElementSize = 77744b8721dSDuncan Sands getTargetData()->getABITypeSize(CPA->getType()->getElementType()); 77883243725SAlkis Evlogimenos for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) 77983243725SAlkis Evlogimenos InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize); 780996fe010SChris Lattner return; 781996fe010SChris Lattner } 782996fe010SChris Lattner 783996fe010SChris Lattner case Type::StructTyID: { 784996fe010SChris Lattner const ConstantStruct *CPS = cast<ConstantStruct>(Init); 785996fe010SChris Lattner const StructLayout *SL = 78620a631fdSOwen Anderson getTargetData()->getStructLayout(cast<StructType>(CPS->getType())); 78783243725SAlkis Evlogimenos for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) 788c473d8e4SChris Lattner InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i)); 789996fe010SChris Lattner return; 790996fe010SChris Lattner } 791996fe010SChris Lattner 792996fe010SChris Lattner default: 793f3baad3eSBill Wendling cerr << "Bad Type: " << *Init->getType() << "\n"; 794996fe010SChris Lattner assert(0 && "Unknown constant type to initialize memory with!"); 795996fe010SChris Lattner } 796996fe010SChris Lattner } 797996fe010SChris Lattner 798996fe010SChris Lattner /// EmitGlobals - Emit all of the global variables to memory, storing their 799996fe010SChris Lattner /// addresses into GlobalAddress. This must make sure to copy the contents of 800996fe010SChris Lattner /// their initializers into the memory. 801996fe010SChris Lattner /// 802996fe010SChris Lattner void ExecutionEngine::emitGlobals() { 80320a631fdSOwen Anderson const TargetData *TD = getTargetData(); 804996fe010SChris Lattner 805996fe010SChris Lattner // Loop over all of the global variables in the program, allocating the memory 8060621caefSChris Lattner // to hold them. If there is more than one module, do a prepass over globals 8070621caefSChris Lattner // to figure out how the different modules should link together. 8080621caefSChris Lattner // 8090621caefSChris Lattner std::map<std::pair<std::string, const Type*>, 8100621caefSChris Lattner const GlobalValue*> LinkedGlobalsMap; 8110621caefSChris Lattner 8120621caefSChris Lattner if (Modules.size() != 1) { 8130621caefSChris Lattner for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 8140621caefSChris Lattner Module &M = *Modules[m]->getModule(); 8150621caefSChris Lattner for (Module::const_global_iterator I = M.global_begin(), 8160621caefSChris Lattner E = M.global_end(); I != E; ++I) { 8170621caefSChris Lattner const GlobalValue *GV = I; 8185301e7c6SReid Spencer if (GV->hasInternalLinkage() || GV->isDeclaration() || 8190621caefSChris Lattner GV->hasAppendingLinkage() || !GV->hasName()) 8200621caefSChris Lattner continue;// Ignore external globals and globals with internal linkage. 8210621caefSChris Lattner 8220621caefSChris Lattner const GlobalValue *&GVEntry = 8230621caefSChris Lattner LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())]; 8240621caefSChris Lattner 8250621caefSChris Lattner // If this is the first time we've seen this global, it is the canonical 8260621caefSChris Lattner // version. 8270621caefSChris Lattner if (!GVEntry) { 8280621caefSChris Lattner GVEntry = GV; 8290621caefSChris Lattner continue; 8300621caefSChris Lattner } 8310621caefSChris Lattner 8320621caefSChris Lattner // If the existing global is strong, never replace it. 833d61d39ecSAnton Korobeynikov if (GVEntry->hasExternalLinkage() || 834d61d39ecSAnton Korobeynikov GVEntry->hasDLLImportLinkage() || 835d61d39ecSAnton Korobeynikov GVEntry->hasDLLExportLinkage()) 8360621caefSChris Lattner continue; 8370621caefSChris Lattner 8380621caefSChris Lattner // Otherwise, we know it's linkonce/weak, replace it if this is a strong 8390621caefSChris Lattner // symbol. 84012c94949SAnton Korobeynikov if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage()) 8410621caefSChris Lattner GVEntry = GV; 8420621caefSChris Lattner } 8430621caefSChris Lattner } 8440621caefSChris Lattner } 8450621caefSChris Lattner 8460621caefSChris Lattner std::vector<const GlobalValue*> NonCanonicalGlobals; 8470621caefSChris Lattner for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 8480621caefSChris Lattner Module &M = *Modules[m]->getModule(); 8498ffb6611SChris Lattner for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 8500621caefSChris Lattner I != E; ++I) { 8510621caefSChris Lattner // In the multi-module case, see what this global maps to. 8520621caefSChris Lattner if (!LinkedGlobalsMap.empty()) { 8530621caefSChris Lattner if (const GlobalValue *GVEntry = 8540621caefSChris Lattner LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) { 8550621caefSChris Lattner // If something else is the canonical global, ignore this one. 8560621caefSChris Lattner if (GVEntry != &*I) { 8570621caefSChris Lattner NonCanonicalGlobals.push_back(I); 8580621caefSChris Lattner continue; 8590621caefSChris Lattner } 8600621caefSChris Lattner } 8610621caefSChris Lattner } 8620621caefSChris Lattner 8635301e7c6SReid Spencer if (!I->isDeclaration()) { 8640621caefSChris Lattner // Get the type of the global. 865996fe010SChris Lattner const Type *Ty = I->getType()->getElementType(); 866996fe010SChris Lattner 867996fe010SChris Lattner // Allocate some memory for it! 86844b8721dSDuncan Sands unsigned Size = TD->getABITypeSize(Ty); 8696bbe3eceSChris Lattner addGlobalMapping(I, new char[Size]); 870996fe010SChris Lattner } else { 871e8bbcfc2SBrian Gaeke // External variable reference. Try to use the dynamic loader to 872e8bbcfc2SBrian Gaeke // get a pointer to it. 8730621caefSChris Lattner if (void *SymAddr = 8740621caefSChris Lattner sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str())) 875748e8579SChris Lattner addGlobalMapping(I, SymAddr); 8769de0d14dSChris Lattner else { 877f3baad3eSBill Wendling cerr << "Could not resolve external global address: " 8789de0d14dSChris Lattner << I->getName() << "\n"; 8799de0d14dSChris Lattner abort(); 8809de0d14dSChris Lattner } 881996fe010SChris Lattner } 8820621caefSChris Lattner } 8830621caefSChris Lattner 8840621caefSChris Lattner // If there are multiple modules, map the non-canonical globals to their 8850621caefSChris Lattner // canonical location. 8860621caefSChris Lattner if (!NonCanonicalGlobals.empty()) { 8870621caefSChris Lattner for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) { 8880621caefSChris Lattner const GlobalValue *GV = NonCanonicalGlobals[i]; 8890621caefSChris Lattner const GlobalValue *CGV = 8900621caefSChris Lattner LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())]; 8910621caefSChris Lattner void *Ptr = getPointerToGlobalIfAvailable(CGV); 8920621caefSChris Lattner assert(Ptr && "Canonical global wasn't codegen'd!"); 8930621caefSChris Lattner addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV)); 8940621caefSChris Lattner } 8950621caefSChris Lattner } 896996fe010SChris Lattner 8977a9c62baSReid Spencer // Now that all of the globals are set up in memory, loop through them all 8987a9c62baSReid Spencer // and initialize their contents. 8998ffb6611SChris Lattner for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 9000621caefSChris Lattner I != E; ++I) { 9015301e7c6SReid Spencer if (!I->isDeclaration()) { 9020621caefSChris Lattner if (!LinkedGlobalsMap.empty()) { 9030621caefSChris Lattner if (const GlobalValue *GVEntry = 9040621caefSChris Lattner LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) 9050621caefSChris Lattner if (GVEntry != &*I) // Not the canonical variable. 9060621caefSChris Lattner continue; 9070621caefSChris Lattner } 9086bbe3eceSChris Lattner EmitGlobalVariable(I); 9096bbe3eceSChris Lattner } 9100621caefSChris Lattner } 9110621caefSChris Lattner } 9120621caefSChris Lattner } 9136bbe3eceSChris Lattner 9146bbe3eceSChris Lattner // EmitGlobalVariable - This method emits the specified global variable to the 9156bbe3eceSChris Lattner // address specified in GlobalAddresses, or allocates new memory if it's not 9166bbe3eceSChris Lattner // already in the map. 917fbcc0aa1SChris Lattner void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) { 918748e8579SChris Lattner void *GA = getPointerToGlobalIfAvailable(GV); 9195834fdb3SBill Wendling DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n"; 920dc631735SChris Lattner 921fbcc0aa1SChris Lattner const Type *ElTy = GV->getType()->getElementType(); 92244b8721dSDuncan Sands size_t GVSize = (size_t)getTargetData()->getABITypeSize(ElTy); 9236bbe3eceSChris Lattner if (GA == 0) { 9246bbe3eceSChris Lattner // If it's not already specified, allocate memory for the global. 925d215992bSChris Lattner GA = new char[GVSize]; 926748e8579SChris Lattner addGlobalMapping(GV, GA); 9276bbe3eceSChris Lattner } 928fbcc0aa1SChris Lattner 9296bbe3eceSChris Lattner InitializeMemory(GV->getInitializer(), GA); 930df1f1524SChris Lattner NumInitBytes += (unsigned)GVSize; 9316bbe3eceSChris Lattner ++NumGlobals; 932996fe010SChris Lattner } 933