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" 2670e37278SReid Spencer #include "llvm/Target/TargetData.h" 2772ac14edSJeff Cohen #include <math.h> 2829681deeSChris Lattner using namespace llvm; 29996fe010SChris Lattner 30c346ecd7SChris Lattner STATISTIC(NumInitBytes, "Number of bytes of global vars initialized"); 31c346ecd7SChris Lattner STATISTIC(NumGlobals , "Number of global vars initialized"); 32996fe010SChris Lattner 332d52c1b8SChris Lattner ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0; 342d52c1b8SChris Lattner ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0; 352d52c1b8SChris Lattner 36fd6f3257SChris Lattner ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) { 3787aee74cSChris Lattner LazyCompilationDisabled = false; 380621caefSChris Lattner Modules.push_back(P); 39260b0c88SMisha Brukman assert(P && "ModuleProvider is null?"); 40260b0c88SMisha Brukman } 41260b0c88SMisha Brukman 4292f8b30dSBrian Gaeke ExecutionEngine::~ExecutionEngine() { 43603682adSReid Spencer clearAllGlobalMappings(); 440621caefSChris Lattner for (unsigned i = 0, e = Modules.size(); i != e; ++i) 450621caefSChris Lattner delete Modules[i]; 4692f8b30dSBrian Gaeke } 4792f8b30dSBrian Gaeke 48324fe890SDevang Patel /// removeModuleProvider - Remove a ModuleProvider from the list of modules. 49324fe890SDevang Patel /// Release module from ModuleProvider. 50324fe890SDevang Patel Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P, 51324fe890SDevang Patel std::string *ErrInfo) { 52324fe890SDevang Patel for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(), 53324fe890SDevang Patel E = Modules.end(); I != E; ++I) { 54324fe890SDevang Patel ModuleProvider *MP = *I; 55324fe890SDevang Patel if (MP == P) { 56324fe890SDevang Patel Modules.erase(I); 57324fe890SDevang Patel return MP->releaseModule(ErrInfo); 58324fe890SDevang Patel } 59324fe890SDevang Patel } 60324fe890SDevang Patel return NULL; 61324fe890SDevang Patel } 62324fe890SDevang Patel 630621caefSChris Lattner /// FindFunctionNamed - Search all of the active modules to find the one that 640621caefSChris Lattner /// defines FnName. This is very slow operation and shouldn't be used for 650621caefSChris Lattner /// general code. 660621caefSChris Lattner Function *ExecutionEngine::FindFunctionNamed(const char *FnName) { 670621caefSChris Lattner for (unsigned i = 0, e = Modules.size(); i != e; ++i) { 681241d6d5SReid Spencer if (Function *F = Modules[i]->getModule()->getFunction(FnName)) 690621caefSChris Lattner return F; 700621caefSChris Lattner } 710621caefSChris Lattner return 0; 720621caefSChris Lattner } 730621caefSChris Lattner 740621caefSChris Lattner 756d8dd189SChris Lattner /// addGlobalMapping - Tell the execution engine that the specified global is 766d8dd189SChris Lattner /// at the specified location. This is used internally as functions are JIT'd 776d8dd189SChris Lattner /// and as global variables are laid out in memory. It can and should also be 786d8dd189SChris Lattner /// used by clients of the EE that want to have an LLVM global overlay 796d8dd189SChris Lattner /// existing data in memory. 806d8dd189SChris Lattner void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) { 816d8dd189SChris Lattner MutexGuard locked(lock); 826d8dd189SChris Lattner 836d8dd189SChris Lattner void *&CurVal = state.getGlobalAddressMap(locked)[GV]; 846d8dd189SChris Lattner assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!"); 856d8dd189SChris Lattner CurVal = Addr; 866d8dd189SChris Lattner 876d8dd189SChris Lattner // If we are using the reverse mapping, add it too 886d8dd189SChris Lattner if (!state.getGlobalAddressReverseMap(locked).empty()) { 896d8dd189SChris Lattner const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr]; 906d8dd189SChris Lattner assert((V == 0 || GV == 0) && "GlobalMapping already established!"); 916d8dd189SChris Lattner V = GV; 926d8dd189SChris Lattner } 936d8dd189SChris Lattner } 946d8dd189SChris Lattner 956d8dd189SChris Lattner /// clearAllGlobalMappings - Clear all global mappings and start over again 966d8dd189SChris Lattner /// use in dynamic compilation scenarios when you want to move globals 976d8dd189SChris Lattner void ExecutionEngine::clearAllGlobalMappings() { 986d8dd189SChris Lattner MutexGuard locked(lock); 996d8dd189SChris Lattner 1006d8dd189SChris Lattner state.getGlobalAddressMap(locked).clear(); 1016d8dd189SChris Lattner state.getGlobalAddressReverseMap(locked).clear(); 1026d8dd189SChris Lattner } 1036d8dd189SChris Lattner 1046d8dd189SChris Lattner /// updateGlobalMapping - Replace an existing mapping for GV with a new 1056d8dd189SChris Lattner /// address. This updates both maps as required. If "Addr" is null, the 1066d8dd189SChris Lattner /// entry for the global is removed from the mappings. 1076d8dd189SChris Lattner void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) { 1086d8dd189SChris Lattner MutexGuard locked(lock); 1096d8dd189SChris Lattner 1106d8dd189SChris Lattner // Deleting from the mapping? 1116d8dd189SChris Lattner if (Addr == 0) { 1126d8dd189SChris Lattner state.getGlobalAddressMap(locked).erase(GV); 1136d8dd189SChris Lattner if (!state.getGlobalAddressReverseMap(locked).empty()) 1146d8dd189SChris Lattner state.getGlobalAddressReverseMap(locked).erase(Addr); 1156d8dd189SChris Lattner return; 1166d8dd189SChris Lattner } 1176d8dd189SChris Lattner 1186d8dd189SChris Lattner void *&CurVal = state.getGlobalAddressMap(locked)[GV]; 1196d8dd189SChris Lattner if (CurVal && !state.getGlobalAddressReverseMap(locked).empty()) 1206d8dd189SChris Lattner state.getGlobalAddressReverseMap(locked).erase(CurVal); 1216d8dd189SChris Lattner CurVal = Addr; 1226d8dd189SChris Lattner 1236d8dd189SChris Lattner // If we are using the reverse mapping, add it too 1246d8dd189SChris Lattner if (!state.getGlobalAddressReverseMap(locked).empty()) { 1256d8dd189SChris Lattner const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr]; 1266d8dd189SChris Lattner assert((V == 0 || GV == 0) && "GlobalMapping already established!"); 1276d8dd189SChris Lattner V = GV; 1286d8dd189SChris Lattner } 1296d8dd189SChris Lattner } 1306d8dd189SChris Lattner 1316d8dd189SChris Lattner /// getPointerToGlobalIfAvailable - This returns the address of the specified 1326d8dd189SChris Lattner /// global value if it is has already been codegen'd, otherwise it returns null. 1336d8dd189SChris Lattner /// 1346d8dd189SChris Lattner void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) { 1356d8dd189SChris Lattner MutexGuard locked(lock); 1366d8dd189SChris Lattner 1376d8dd189SChris Lattner std::map<const GlobalValue*, void*>::iterator I = 1386d8dd189SChris Lattner state.getGlobalAddressMap(locked).find(GV); 1396d8dd189SChris Lattner return I != state.getGlobalAddressMap(locked).end() ? I->second : 0; 1406d8dd189SChris Lattner } 1416d8dd189SChris Lattner 142748e8579SChris Lattner /// getGlobalValueAtAddress - Return the LLVM global value object that starts 143748e8579SChris Lattner /// at the specified address. 144748e8579SChris Lattner /// 145748e8579SChris Lattner const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) { 14679876f52SReid Spencer MutexGuard locked(lock); 14779876f52SReid Spencer 148748e8579SChris Lattner // If we haven't computed the reverse mapping yet, do so first. 14979876f52SReid Spencer if (state.getGlobalAddressReverseMap(locked).empty()) { 1506d8dd189SChris Lattner for (std::map<const GlobalValue*, void *>::iterator 1516d8dd189SChris Lattner I = state.getGlobalAddressMap(locked).begin(), 1526d8dd189SChris Lattner E = state.getGlobalAddressMap(locked).end(); I != E; ++I) 1536d8dd189SChris Lattner state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second, 1546d8dd189SChris Lattner I->first)); 155748e8579SChris Lattner } 156748e8579SChris Lattner 157748e8579SChris Lattner std::map<void *, const GlobalValue*>::iterator I = 15879876f52SReid Spencer state.getGlobalAddressReverseMap(locked).find(Addr); 15979876f52SReid Spencer return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0; 160748e8579SChris Lattner } 1615a0d4829SChris Lattner 1625a0d4829SChris Lattner // CreateArgv - Turn a vector of strings into a nice argv style array of 1635a0d4829SChris Lattner // pointers to null terminated strings. 1645a0d4829SChris Lattner // 1655a0d4829SChris Lattner static void *CreateArgv(ExecutionEngine *EE, 1665a0d4829SChris Lattner const std::vector<std::string> &InputArgv) { 16720a631fdSOwen Anderson unsigned PtrSize = EE->getTargetData()->getPointerSize(); 1685a0d4829SChris Lattner char *Result = new char[(InputArgv.size()+1)*PtrSize]; 1695a0d4829SChris Lattner 1705834fdb3SBill Wendling DOUT << "ARGV = " << (void*)Result << "\n"; 1710d54e78aSReid Spencer const Type *SBytePtr = PointerType::get(Type::Int8Ty); 1725a0d4829SChris Lattner 1735a0d4829SChris Lattner for (unsigned i = 0; i != InputArgv.size(); ++i) { 1745a0d4829SChris Lattner unsigned Size = InputArgv[i].size()+1; 1755a0d4829SChris Lattner char *Dest = new char[Size]; 1765834fdb3SBill Wendling DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n"; 1775a0d4829SChris Lattner 1785a0d4829SChris Lattner std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest); 1795a0d4829SChris Lattner Dest[Size-1] = 0; 1805a0d4829SChris Lattner 1815a0d4829SChris Lattner // Endian safe: Result[i] = (PointerTy)Dest; 1825a0d4829SChris Lattner EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize), 1835a0d4829SChris Lattner SBytePtr); 1845a0d4829SChris Lattner } 1855a0d4829SChris Lattner 1865a0d4829SChris Lattner // Null terminate it 1875a0d4829SChris Lattner EE->StoreValueToMemory(PTOGV(0), 1885a0d4829SChris Lattner (GenericValue*)(Result+InputArgv.size()*PtrSize), 1895a0d4829SChris Lattner SBytePtr); 1905a0d4829SChris Lattner return Result; 1915a0d4829SChris Lattner } 1925a0d4829SChris Lattner 193faae50b6SChris Lattner 194faae50b6SChris Lattner /// runStaticConstructorsDestructors - This method is used to execute all of 1950621caefSChris Lattner /// the static constructors or destructors for a program, depending on the 196faae50b6SChris Lattner /// value of isDtors. 197faae50b6SChris Lattner void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) { 198faae50b6SChris Lattner const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors"; 1990621caefSChris Lattner 2000621caefSChris Lattner // Execute global ctors/dtors for each module in the program. 2010621caefSChris Lattner for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 2020621caefSChris Lattner GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name); 203fe36eaebSChris Lattner 204fe36eaebSChris Lattner // If this global has internal linkage, or if it has a use, then it must be 205fe36eaebSChris Lattner // an old-style (llvmgcc3) static ctor with __main linked in and in use. If 2060621caefSChris Lattner // this is the case, don't execute any of the global ctors, __main will do 2070621caefSChris Lattner // it. 2085301e7c6SReid Spencer if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue; 209faae50b6SChris Lattner 2100621caefSChris Lattner // Should be an array of '{ int, void ()* }' structs. The first value is 2110621caefSChris Lattner // the init priority, which we ignore. 212faae50b6SChris Lattner ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer()); 2130621caefSChris Lattner if (!InitList) continue; 214faae50b6SChris Lattner for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) 2150621caefSChris Lattner if (ConstantStruct *CS = 2160621caefSChris Lattner dyn_cast<ConstantStruct>(InitList->getOperand(i))) { 2170621caefSChris Lattner if (CS->getNumOperands() != 2) break; // Not array of 2-element structs. 218faae50b6SChris Lattner 219faae50b6SChris Lattner Constant *FP = CS->getOperand(1); 220faae50b6SChris Lattner if (FP->isNullValue()) 2210621caefSChris Lattner break; // Found a null terminator, exit. 222faae50b6SChris Lattner 223faae50b6SChris Lattner if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP)) 2246c38f0bbSReid Spencer if (CE->isCast()) 225faae50b6SChris Lattner FP = CE->getOperand(0); 226faae50b6SChris Lattner if (Function *F = dyn_cast<Function>(FP)) { 227faae50b6SChris Lattner // Execute the ctor/dtor function! 228faae50b6SChris Lattner runFunction(F, std::vector<GenericValue>()); 229faae50b6SChris Lattner } 230faae50b6SChris Lattner } 231faae50b6SChris Lattner } 2320621caefSChris Lattner } 233faae50b6SChris Lattner 2345a0d4829SChris Lattner /// runFunctionAsMain - This is a helper function which wraps runFunction to 2355a0d4829SChris Lattner /// handle the common task of starting up main with the specified argc, argv, 2365a0d4829SChris Lattner /// and envp parameters. 2375a0d4829SChris Lattner int ExecutionEngine::runFunctionAsMain(Function *Fn, 2385a0d4829SChris Lattner const std::vector<std::string> &argv, 2395a0d4829SChris Lattner const char * const * envp) { 2405a0d4829SChris Lattner std::vector<GenericValue> GVArgs; 2415a0d4829SChris Lattner GenericValue GVArgc; 24287aa65f4SReid Spencer GVArgc.IntVal = APInt(32, argv.size()); 2438c32c111SAnton Korobeynikov 2448c32c111SAnton Korobeynikov // Check main() type 245b1cad0b3SChris Lattner unsigned NumArgs = Fn->getFunctionType()->getNumParams(); 2468c32c111SAnton Korobeynikov const FunctionType *FTy = Fn->getFunctionType(); 2478c32c111SAnton Korobeynikov const Type* PPInt8Ty = PointerType::get(PointerType::get(Type::Int8Ty)); 2488c32c111SAnton Korobeynikov switch (NumArgs) { 2498c32c111SAnton Korobeynikov case 3: 2508c32c111SAnton Korobeynikov if (FTy->getParamType(2) != PPInt8Ty) { 2518c32c111SAnton Korobeynikov cerr << "Invalid type for third argument of main() supplied\n"; 2528c32c111SAnton Korobeynikov abort(); 2538c32c111SAnton Korobeynikov } 254b781886dSAnton Korobeynikov // FALLS THROUGH 2558c32c111SAnton Korobeynikov case 2: 2568c32c111SAnton Korobeynikov if (FTy->getParamType(1) != PPInt8Ty) { 2578c32c111SAnton Korobeynikov cerr << "Invalid type for second argument of main() supplied\n"; 2588c32c111SAnton Korobeynikov abort(); 2598c32c111SAnton Korobeynikov } 260b781886dSAnton Korobeynikov // FALLS THROUGH 2618c32c111SAnton Korobeynikov case 1: 2628c32c111SAnton Korobeynikov if (FTy->getParamType(0) != Type::Int32Ty) { 2638c32c111SAnton Korobeynikov cerr << "Invalid type for first argument of main() supplied\n"; 2648c32c111SAnton Korobeynikov abort(); 2658c32c111SAnton Korobeynikov } 266b781886dSAnton Korobeynikov // FALLS THROUGH 2678c32c111SAnton Korobeynikov case 0: 2688c32c111SAnton Korobeynikov if (FTy->getReturnType() != Type::Int32Ty && 2698c32c111SAnton Korobeynikov FTy->getReturnType() != Type::VoidTy) { 2708c32c111SAnton Korobeynikov cerr << "Invalid return type of main() supplied\n"; 2718c32c111SAnton Korobeynikov abort(); 2728c32c111SAnton Korobeynikov } 2738c32c111SAnton Korobeynikov break; 2748c32c111SAnton Korobeynikov default: 2758c32c111SAnton Korobeynikov cerr << "Invalid number of arguments of main() supplied\n"; 2768c32c111SAnton Korobeynikov abort(); 2778c32c111SAnton Korobeynikov } 2788c32c111SAnton Korobeynikov 279b1cad0b3SChris Lattner if (NumArgs) { 2805a0d4829SChris Lattner GVArgs.push_back(GVArgc); // Arg #0 = argc. 281b1cad0b3SChris Lattner if (NumArgs > 1) { 2825a0d4829SChris Lattner GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv. 283b1cad0b3SChris Lattner assert(((char **)GVTOP(GVArgs[1]))[0] && 284b1cad0b3SChris Lattner "argv[0] was null after CreateArgv"); 285b1cad0b3SChris Lattner if (NumArgs > 2) { 2865a0d4829SChris Lattner std::vector<std::string> EnvVars; 2875a0d4829SChris Lattner for (unsigned i = 0; envp[i]; ++i) 2885a0d4829SChris Lattner EnvVars.push_back(envp[i]); 2895a0d4829SChris Lattner GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp. 290b1cad0b3SChris Lattner } 291b1cad0b3SChris Lattner } 292b1cad0b3SChris Lattner } 29387aa65f4SReid Spencer return runFunction(Fn, GVArgs).IntVal.getZExtValue(); 2945a0d4829SChris Lattner } 2955a0d4829SChris Lattner 296260b0c88SMisha Brukman /// If possible, create a JIT, unless the caller specifically requests an 297260b0c88SMisha Brukman /// Interpreter or there's an error. If even an Interpreter cannot be created, 298260b0c88SMisha Brukman /// NULL is returned. 299857c21b4SMisha Brukman /// 3002f1e2002SMisha Brukman ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP, 301603682adSReid Spencer bool ForceInterpreter, 302603682adSReid Spencer std::string *ErrorStr) { 3034bd3bd5bSBrian Gaeke ExecutionEngine *EE = 0; 3044bd3bd5bSBrian Gaeke 305c8c6c03dSChris Lattner // Unless the interpreter was explicitly selected, try making a JIT. 3062d52c1b8SChris Lattner if (!ForceInterpreter && JITCtor) 307603682adSReid Spencer EE = JITCtor(MP, ErrorStr); 3084bd3bd5bSBrian Gaeke 3094bd3bd5bSBrian Gaeke // If we can't make a JIT, make an interpreter instead. 3102d52c1b8SChris Lattner if (EE == 0 && InterpCtor) 311603682adSReid Spencer EE = InterpCtor(MP, ErrorStr); 312c8c6c03dSChris Lattner 3130b2de9f2SChris Lattner if (EE) { 31470e37278SReid Spencer // Make sure we can resolve symbols in the program as well. The zero arg 31570e37278SReid Spencer // to the function tells DynamicLibrary to load the program, not a library. 316edaf0b46SChris Lattner if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr)) { 317edaf0b46SChris Lattner delete EE; 318edaf0b46SChris Lattner return 0; 31963539389SChris Lattner } 3200b2de9f2SChris Lattner } 32170e37278SReid Spencer 3224bd3bd5bSBrian Gaeke return EE; 3234bd3bd5bSBrian Gaeke } 3244bd3bd5bSBrian Gaeke 325b5163bb9SChris Lattner ExecutionEngine *ExecutionEngine::create(Module *M) { 326b5163bb9SChris Lattner return create(new ExistingModuleProvider(M)); 327b5163bb9SChris Lattner } 328b5163bb9SChris Lattner 329857c21b4SMisha Brukman /// getPointerToGlobal - This returns the address of the specified global 330857c21b4SMisha Brukman /// value. This may involve code generation if it's a function. 331857c21b4SMisha Brukman /// 332996fe010SChris Lattner void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) { 3331678e859SBrian Gaeke if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV))) 334996fe010SChris Lattner return getPointerToFunction(F); 335996fe010SChris Lattner 33679876f52SReid Spencer MutexGuard locked(lock); 33769e84901SJeff Cohen void *p = state.getGlobalAddressMap(locked)[GV]; 33869e84901SJeff Cohen if (p) 33969e84901SJeff Cohen return p; 34069e84901SJeff Cohen 34169e84901SJeff Cohen // Global variable might have been added since interpreter started. 34269e84901SJeff Cohen if (GlobalVariable *GVar = 34369e84901SJeff Cohen const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV))) 34469e84901SJeff Cohen EmitGlobalVariable(GVar); 34569e84901SJeff Cohen else 3464da5e17cSChris Lattner assert(0 && "Global hasn't had an address allocated yet!"); 34779876f52SReid Spencer return state.getGlobalAddressMap(locked)[GV]; 348996fe010SChris Lattner } 349996fe010SChris Lattner 3506c38f0bbSReid Spencer /// This function converts a Constant* into a GenericValue. The interesting 3516c38f0bbSReid Spencer /// part is if C is a ConstantExpr. 3522dc9f132SReid Spencer /// @brief Get a GenericValue for a Constant* 353996fe010SChris Lattner GenericValue ExecutionEngine::getConstantValue(const Constant *C) { 3546c38f0bbSReid Spencer // If its undefined, return the garbage. 3554fd528f2SReid Spencer if (isa<UndefValue>(C)) 3564fd528f2SReid Spencer return GenericValue(); 3579de0d14dSChris Lattner 3586c38f0bbSReid Spencer // If the value is a ConstantExpr 3596c38f0bbSReid Spencer if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 3604fd528f2SReid Spencer Constant *Op0 = CE->getOperand(0); 3619de0d14dSChris Lattner switch (CE->getOpcode()) { 3629de0d14dSChris Lattner case Instruction::GetElementPtr: { 3636c38f0bbSReid Spencer // Compute the index 3644fd528f2SReid Spencer GenericValue Result = getConstantValue(Op0); 365c44bd78aSChris Lattner SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end()); 3669de0d14dSChris Lattner uint64_t Offset = 3674fd528f2SReid Spencer TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size()); 3689de0d14dSChris Lattner 36987aa65f4SReid Spencer char* tmp = (char*) Result.PointerVal; 37087aa65f4SReid Spencer Result = PTOGV(tmp + Offset); 3719de0d14dSChris Lattner return Result; 3729de0d14dSChris Lattner } 3734fd528f2SReid Spencer case Instruction::Trunc: { 3744fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 3754fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 3764fd528f2SReid Spencer GV.IntVal = GV.IntVal.trunc(BitWidth); 3774fd528f2SReid Spencer return GV; 3784fd528f2SReid Spencer } 3794fd528f2SReid Spencer case Instruction::ZExt: { 3804fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 3814fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 3824fd528f2SReid Spencer GV.IntVal = GV.IntVal.zext(BitWidth); 3834fd528f2SReid Spencer return GV; 3844fd528f2SReid Spencer } 3854fd528f2SReid Spencer case Instruction::SExt: { 3864fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 3874fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 3884fd528f2SReid Spencer GV.IntVal = GV.IntVal.sext(BitWidth); 3894fd528f2SReid Spencer return GV; 3904fd528f2SReid Spencer } 3914fd528f2SReid Spencer case Instruction::FPTrunc: { 392a1336cf5SDale Johannesen // FIXME long double 3934fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 3944fd528f2SReid Spencer GV.FloatVal = float(GV.DoubleVal); 3954fd528f2SReid Spencer return GV; 3964fd528f2SReid Spencer } 3974fd528f2SReid Spencer case Instruction::FPExt:{ 398a1336cf5SDale Johannesen // FIXME long double 3994fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 4004fd528f2SReid Spencer GV.DoubleVal = double(GV.FloatVal); 4014fd528f2SReid Spencer return GV; 4024fd528f2SReid Spencer } 4034fd528f2SReid Spencer case Instruction::UIToFP: { 4044fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 4054fd528f2SReid Spencer if (CE->getType() == Type::FloatTy) 4064fd528f2SReid Spencer GV.FloatVal = float(GV.IntVal.roundToDouble()); 407a1336cf5SDale Johannesen else if (CE->getType() == Type::DoubleTy) 4084fd528f2SReid Spencer GV.DoubleVal = GV.IntVal.roundToDouble(); 409a1336cf5SDale Johannesen else if (CE->getType() == Type::X86_FP80Ty) { 410a1336cf5SDale Johannesen const uint64_t zero[] = {0, 0}; 411a1336cf5SDale Johannesen APFloat apf = APFloat(APInt(80, 2, zero)); 4125f009733SNeil Booth (void)apf.convertFromZeroExtendedInteger(GV.IntVal.getRawData(), 4134230512fSDale Johannesen GV.IntVal.getBitWidth(), false, 4149150652bSDale Johannesen APFloat::rmNearestTiesToEven); 415a1336cf5SDale Johannesen GV.IntVal = apf.convertToAPInt(); 416a1336cf5SDale Johannesen } 4174fd528f2SReid Spencer return GV; 4184fd528f2SReid Spencer } 4194fd528f2SReid Spencer case Instruction::SIToFP: { 4204fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 4214fd528f2SReid Spencer if (CE->getType() == Type::FloatTy) 4224fd528f2SReid Spencer GV.FloatVal = float(GV.IntVal.signedRoundToDouble()); 423a1336cf5SDale Johannesen else if (CE->getType() == Type::DoubleTy) 4244fd528f2SReid Spencer GV.DoubleVal = GV.IntVal.signedRoundToDouble(); 425a1336cf5SDale Johannesen else if (CE->getType() == Type::X86_FP80Ty) { 426a1336cf5SDale Johannesen const uint64_t zero[] = { 0, 0}; 427a1336cf5SDale Johannesen APFloat apf = APFloat(APInt(80, 2, zero)); 4285f009733SNeil Booth (void)apf.convertFromZeroExtendedInteger(GV.IntVal.getRawData(), 4294230512fSDale Johannesen GV.IntVal.getBitWidth(), true, 4309150652bSDale Johannesen APFloat::rmNearestTiesToEven); 431a1336cf5SDale Johannesen GV.IntVal = apf.convertToAPInt(); 432a1336cf5SDale Johannesen } 4334fd528f2SReid Spencer return GV; 4344fd528f2SReid Spencer } 4354fd528f2SReid Spencer case Instruction::FPToUI: // double->APInt conversion handles sign 4364fd528f2SReid Spencer case Instruction::FPToSI: { 4374fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 4384fd528f2SReid Spencer uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 4394fd528f2SReid Spencer if (Op0->getType() == Type::FloatTy) 4404fd528f2SReid Spencer GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth); 441a1336cf5SDale Johannesen else if (Op0->getType() == Type::DoubleTy) 4424fd528f2SReid Spencer GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth); 443a1336cf5SDale Johannesen else if (Op0->getType() == Type::X86_FP80Ty) { 444a1336cf5SDale Johannesen APFloat apf = APFloat(GV.IntVal); 445a1336cf5SDale Johannesen uint64_t v; 446a1336cf5SDale Johannesen (void)apf.convertToInteger(&v, BitWidth, 447a1336cf5SDale Johannesen CE->getOpcode()==Instruction::FPToSI, 448a1336cf5SDale Johannesen APFloat::rmTowardZero); 449a1336cf5SDale Johannesen GV.IntVal = v; // endian? 450a1336cf5SDale Johannesen } 4514fd528f2SReid Spencer return GV; 4524fd528f2SReid Spencer } 4536c38f0bbSReid Spencer case Instruction::PtrToInt: { 4544fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 4554fd528f2SReid Spencer uint32_t PtrWidth = TD->getPointerSizeInBits(); 4564fd528f2SReid Spencer GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal)); 4574fd528f2SReid Spencer return GV; 4584fd528f2SReid Spencer } 4594fd528f2SReid Spencer case Instruction::IntToPtr: { 4604fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 4614fd528f2SReid Spencer uint32_t PtrWidth = TD->getPointerSizeInBits(); 4624fd528f2SReid Spencer if (PtrWidth != GV.IntVal.getBitWidth()) 4634fd528f2SReid Spencer GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth); 4644fd528f2SReid Spencer assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width"); 4654fd528f2SReid Spencer GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue())); 4666c38f0bbSReid Spencer return GV; 4676c38f0bbSReid Spencer } 4686c38f0bbSReid Spencer case Instruction::BitCast: { 4694fd528f2SReid Spencer GenericValue GV = getConstantValue(Op0); 4704fd528f2SReid Spencer const Type* DestTy = CE->getType(); 4714fd528f2SReid Spencer switch (Op0->getType()->getTypeID()) { 4724fd528f2SReid Spencer default: assert(0 && "Invalid bitcast operand"); 4734fd528f2SReid Spencer case Type::IntegerTyID: 4744fd528f2SReid Spencer assert(DestTy->isFloatingPoint() && "invalid bitcast"); 4754fd528f2SReid Spencer if (DestTy == Type::FloatTy) 4764fd528f2SReid Spencer GV.FloatVal = GV.IntVal.bitsToFloat(); 4774fd528f2SReid Spencer else if (DestTy == Type::DoubleTy) 4784fd528f2SReid Spencer GV.DoubleVal = GV.IntVal.bitsToDouble(); 4796c38f0bbSReid Spencer break; 4804fd528f2SReid Spencer case Type::FloatTyID: 4814fd528f2SReid Spencer assert(DestTy == Type::Int32Ty && "Invalid bitcast"); 4824fd528f2SReid Spencer GV.IntVal.floatToBits(GV.FloatVal); 4834fd528f2SReid Spencer break; 4844fd528f2SReid Spencer case Type::DoubleTyID: 4854fd528f2SReid Spencer assert(DestTy == Type::Int64Ty && "Invalid bitcast"); 4864fd528f2SReid Spencer GV.IntVal.doubleToBits(GV.DoubleVal); 4874fd528f2SReid Spencer break; 4884fd528f2SReid Spencer case Type::PointerTyID: 4894fd528f2SReid Spencer assert(isa<PointerType>(DestTy) && "Invalid bitcast"); 4904fd528f2SReid Spencer break; // getConstantValue(Op0) above already converted it 4916c38f0bbSReid Spencer } 4924fd528f2SReid Spencer return GV; 49368cbcc3eSChris Lattner } 49468cbcc3eSChris Lattner case Instruction::Add: 4954fd528f2SReid Spencer case Instruction::Sub: 4964fd528f2SReid Spencer case Instruction::Mul: 4974fd528f2SReid Spencer case Instruction::UDiv: 4984fd528f2SReid Spencer case Instruction::SDiv: 4994fd528f2SReid Spencer case Instruction::URem: 5004fd528f2SReid Spencer case Instruction::SRem: 5014fd528f2SReid Spencer case Instruction::And: 5024fd528f2SReid Spencer case Instruction::Or: 5034fd528f2SReid Spencer case Instruction::Xor: { 5044fd528f2SReid Spencer GenericValue LHS = getConstantValue(Op0); 5054fd528f2SReid Spencer GenericValue RHS = getConstantValue(CE->getOperand(1)); 5064fd528f2SReid Spencer GenericValue GV; 507c4e6bb5fSChris Lattner switch (CE->getOperand(0)->getType()->getTypeID()) { 508c4e6bb5fSChris Lattner default: assert(0 && "Bad add type!"); abort(); 5097a9c62baSReid Spencer case Type::IntegerTyID: 5104fd528f2SReid Spencer switch (CE->getOpcode()) { 5114fd528f2SReid Spencer default: assert(0 && "Invalid integer opcode"); 5124fd528f2SReid Spencer case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break; 5134fd528f2SReid Spencer case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break; 5144fd528f2SReid Spencer case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break; 5154fd528f2SReid Spencer case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break; 5164fd528f2SReid Spencer case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break; 5174fd528f2SReid Spencer case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break; 5184fd528f2SReid Spencer case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break; 5194fd528f2SReid Spencer case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break; 5204fd528f2SReid Spencer case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break; 5214fd528f2SReid Spencer case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break; 5224fd528f2SReid Spencer } 523c4e6bb5fSChris Lattner break; 524c4e6bb5fSChris Lattner case Type::FloatTyID: 5254fd528f2SReid Spencer switch (CE->getOpcode()) { 5264fd528f2SReid Spencer default: assert(0 && "Invalid float opcode"); abort(); 5274fd528f2SReid Spencer case Instruction::Add: 5284fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break; 5294fd528f2SReid Spencer case Instruction::Sub: 5304fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break; 5314fd528f2SReid Spencer case Instruction::Mul: 5324fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break; 5334fd528f2SReid Spencer case Instruction::FDiv: 5344fd528f2SReid Spencer GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break; 5354fd528f2SReid Spencer case Instruction::FRem: 5364fd528f2SReid Spencer GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break; 5374fd528f2SReid Spencer } 538c4e6bb5fSChris Lattner break; 539c4e6bb5fSChris Lattner case Type::DoubleTyID: 5404fd528f2SReid Spencer switch (CE->getOpcode()) { 5414fd528f2SReid Spencer default: assert(0 && "Invalid double opcode"); abort(); 5424fd528f2SReid Spencer case Instruction::Add: 5434fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break; 5444fd528f2SReid Spencer case Instruction::Sub: 5454fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break; 5464fd528f2SReid Spencer case Instruction::Mul: 5474fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break; 5484fd528f2SReid Spencer case Instruction::FDiv: 5494fd528f2SReid Spencer GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break; 5504fd528f2SReid Spencer case Instruction::FRem: 5514fd528f2SReid Spencer GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break; 5524fd528f2SReid Spencer } 553c4e6bb5fSChris Lattner break; 554a1336cf5SDale Johannesen case Type::X86_FP80TyID: 555a1336cf5SDale Johannesen case Type::PPC_FP128TyID: 556a1336cf5SDale Johannesen case Type::FP128TyID: { 557a1336cf5SDale Johannesen APFloat apfLHS = APFloat(LHS.IntVal); 558a1336cf5SDale Johannesen switch (CE->getOpcode()) { 559a1336cf5SDale Johannesen default: assert(0 && "Invalid long double opcode"); abort(); 560a1336cf5SDale Johannesen case Instruction::Add: 561a1336cf5SDale Johannesen apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 562a1336cf5SDale Johannesen GV.IntVal = apfLHS.convertToAPInt(); 563a1336cf5SDale Johannesen break; 564a1336cf5SDale Johannesen case Instruction::Sub: 565a1336cf5SDale Johannesen apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 566a1336cf5SDale Johannesen GV.IntVal = apfLHS.convertToAPInt(); 567a1336cf5SDale Johannesen break; 568a1336cf5SDale Johannesen case Instruction::Mul: 569a1336cf5SDale Johannesen apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 570a1336cf5SDale Johannesen GV.IntVal = apfLHS.convertToAPInt(); 571a1336cf5SDale Johannesen break; 572a1336cf5SDale Johannesen case Instruction::FDiv: 573a1336cf5SDale Johannesen apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 574a1336cf5SDale Johannesen GV.IntVal = apfLHS.convertToAPInt(); 575a1336cf5SDale Johannesen break; 576a1336cf5SDale Johannesen case Instruction::FRem: 577a1336cf5SDale Johannesen apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven); 578a1336cf5SDale Johannesen GV.IntVal = apfLHS.convertToAPInt(); 579a1336cf5SDale Johannesen break; 580a1336cf5SDale Johannesen } 581a1336cf5SDale Johannesen } 582a1336cf5SDale Johannesen break; 583c4e6bb5fSChris Lattner } 5844fd528f2SReid Spencer return GV; 5854fd528f2SReid Spencer } 5869de0d14dSChris Lattner default: 58768cbcc3eSChris Lattner break; 58868cbcc3eSChris Lattner } 5894fd528f2SReid Spencer cerr << "ConstantExpr not handled: " << *CE << "\n"; 5909de0d14dSChris Lattner abort(); 5919de0d14dSChris Lattner } 592996fe010SChris Lattner 5934fd528f2SReid Spencer GenericValue Result; 5946b727599SChris Lattner switch (C->getType()->getTypeID()) { 59587aa65f4SReid Spencer case Type::FloatTyID: 596bed9dc42SDale Johannesen Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat(); 5977a9c62baSReid Spencer break; 59887aa65f4SReid Spencer case Type::DoubleTyID: 599bed9dc42SDale Johannesen Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble(); 60087aa65f4SReid Spencer break; 601a1336cf5SDale Johannesen case Type::X86_FP80TyID: 602a1336cf5SDale Johannesen case Type::FP128TyID: 603a1336cf5SDale Johannesen case Type::PPC_FP128TyID: 604a1336cf5SDale Johannesen Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt(); 605a1336cf5SDale Johannesen break; 60687aa65f4SReid Spencer case Type::IntegerTyID: 60787aa65f4SReid Spencer Result.IntVal = cast<ConstantInt>(C)->getValue(); 60887aa65f4SReid Spencer break; 609996fe010SChris Lattner case Type::PointerTyID: 6106a0fd73bSReid Spencer if (isa<ConstantPointerNull>(C)) 611996fe010SChris Lattner Result.PointerVal = 0; 6126a0fd73bSReid Spencer else if (const Function *F = dyn_cast<Function>(C)) 6136a0fd73bSReid Spencer Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F))); 6146a0fd73bSReid Spencer else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C)) 6156a0fd73bSReid Spencer Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV))); 616e6492f10SChris Lattner else 617996fe010SChris Lattner assert(0 && "Unknown constant pointer type!"); 618996fe010SChris Lattner break; 619996fe010SChris Lattner default: 6204fd528f2SReid Spencer cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n"; 6219de0d14dSChris Lattner abort(); 622996fe010SChris Lattner } 623996fe010SChris Lattner return Result; 624996fe010SChris Lattner } 625996fe010SChris Lattner 6264ca2ea5bSNate Begeman /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr 6274ca2ea5bSNate Begeman /// is the address of the memory at which to store Val, cast to GenericValue *. 6284ca2ea5bSNate Begeman /// It is not a pointer to a GenericValue containing the address at which to 6294ca2ea5bSNate Begeman /// store Val. 630857c21b4SMisha Brukman /// 6314e42790cSReid Spencer void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr, 632996fe010SChris Lattner const Type *Ty) { 6336b727599SChris Lattner switch (Ty->getTypeID()) { 6347a9c62baSReid Spencer case Type::IntegerTyID: { 6357a9c62baSReid Spencer unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth(); 636*5c65cb46SDuncan Sands unsigned StoreBytes = (BitWidth + 7)/8; 637*5c65cb46SDuncan Sands uint8_t *Src = (uint8_t *)Val.IntVal.getRawData(); 638*5c65cb46SDuncan Sands uint8_t *Dst = (uint8_t *)Ptr; 639*5c65cb46SDuncan Sands 640*5c65cb46SDuncan Sands if (getTargetData()->hostIsLittleEndian()) 641*5c65cb46SDuncan Sands // Little-endian host - the source is ordered from LSB to MSB. 642*5c65cb46SDuncan Sands // Order the destination from LSB to MSB: Do a straight copy. 643*5c65cb46SDuncan Sands memcpy(Dst, Src, StoreBytes); 644*5c65cb46SDuncan Sands else { 645*5c65cb46SDuncan Sands // Big-endian host - the source is an array of 64 bit words ordered from 646*5c65cb46SDuncan Sands // LSW to MSW. Each word is ordered from MSB to LSB. 647*5c65cb46SDuncan Sands // Order the destination from MSB to LSB: Reverse the word order, but not 648*5c65cb46SDuncan Sands // the bytes in a word. 649*5c65cb46SDuncan Sands while (StoreBytes > sizeof(uint64_t)) { 650*5c65cb46SDuncan Sands StoreBytes -= sizeof(uint64_t); 651*5c65cb46SDuncan Sands // May not be aligned so use memcpy. 652*5c65cb46SDuncan Sands memcpy(Dst + StoreBytes, Src, sizeof(uint64_t)); 653*5c65cb46SDuncan Sands Src += sizeof(uint64_t); 654*5c65cb46SDuncan Sands } 655*5c65cb46SDuncan Sands 656*5c65cb46SDuncan Sands memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes); 657815f8dd2SReid Spencer } 658996fe010SChris Lattner break; 6597a9c62baSReid Spencer } 660996fe010SChris Lattner case Type::FloatTyID: 66187aa65f4SReid Spencer *((float*)Ptr) = Val.FloatVal; 66287aa65f4SReid Spencer break; 66387aa65f4SReid Spencer case Type::DoubleTyID: 66487aa65f4SReid Spencer *((double*)Ptr) = Val.DoubleVal; 665996fe010SChris Lattner break; 666a1336cf5SDale Johannesen case Type::X86_FP80TyID: { 667a1336cf5SDale Johannesen uint16_t *Dest = (uint16_t*)Ptr; 668a1336cf5SDale Johannesen const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData(); 669a1336cf5SDale Johannesen // This is endian dependent, but it will only work on x86 anyway. 670a1336cf5SDale Johannesen Dest[0] = Src[4]; 671a1336cf5SDale Johannesen Dest[1] = Src[0]; 672a1336cf5SDale Johannesen Dest[2] = Src[1]; 673a1336cf5SDale Johannesen Dest[3] = Src[2]; 674a1336cf5SDale Johannesen Dest[4] = Src[3]; 675a1336cf5SDale Johannesen break; 676a1336cf5SDale Johannesen } 6777a9c62baSReid Spencer case Type::PointerTyID: 67887aa65f4SReid Spencer *((PointerTy*)Ptr) = Val.PointerVal; 679996fe010SChris Lattner break; 680996fe010SChris Lattner default: 681f3baad3eSBill Wendling cerr << "Cannot store value of type " << *Ty << "!\n"; 682996fe010SChris Lattner } 683996fe010SChris Lattner } 684996fe010SChris Lattner 685857c21b4SMisha Brukman /// FIXME: document 686857c21b4SMisha Brukman /// 68700919f57SReid Spencer void ExecutionEngine::LoadValueFromMemory(GenericValue &Result, 68800919f57SReid Spencer GenericValue *Ptr, 6897f389e8cSChris Lattner const Type *Ty) { 6906b727599SChris Lattner switch (Ty->getTypeID()) { 6917a9c62baSReid Spencer case Type::IntegerTyID: { 6927a9c62baSReid Spencer unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth(); 693*5c65cb46SDuncan Sands unsigned LoadBytes = (BitWidth + 7)/8; 694*5c65cb46SDuncan Sands 695*5c65cb46SDuncan Sands // An APInt with all words initially zero. 696*5c65cb46SDuncan Sands Result.IntVal = APInt(BitWidth, 0); 697*5c65cb46SDuncan Sands 698*5c65cb46SDuncan Sands uint8_t *Src = (uint8_t *)Ptr; 699*5c65cb46SDuncan Sands uint8_t *Dst = (uint8_t *)Result.IntVal.getRawData(); 700*5c65cb46SDuncan Sands 701*5c65cb46SDuncan Sands if (getTargetData()->hostIsLittleEndian()) 702*5c65cb46SDuncan Sands // Little-endian host - the destination must be ordered from LSB to MSB. 703*5c65cb46SDuncan Sands // The source is ordered from LSB to MSB: Do a straight copy. 704*5c65cb46SDuncan Sands memcpy(Dst, Src, LoadBytes); 705*5c65cb46SDuncan Sands else { 706*5c65cb46SDuncan Sands // Big-endian - the destination is an array of 64 bit words ordered from 707*5c65cb46SDuncan Sands // LSW to MSW. Each word must be ordered from MSB to LSB. The source is 708*5c65cb46SDuncan Sands // ordered from MSB to LSB: Reverse the word order, but not the bytes in 709*5c65cb46SDuncan Sands // a word. 710*5c65cb46SDuncan Sands while (LoadBytes > sizeof(uint64_t)) { 711*5c65cb46SDuncan Sands LoadBytes -= sizeof(uint64_t); 712*5c65cb46SDuncan Sands // May not be aligned so use memcpy. 713*5c65cb46SDuncan Sands memcpy(Dst, Src + LoadBytes, sizeof(uint64_t)); 714*5c65cb46SDuncan Sands Dst += sizeof(uint64_t); 715*5c65cb46SDuncan Sands } 716*5c65cb46SDuncan Sands 717*5c65cb46SDuncan Sands memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes); 718*5c65cb46SDuncan Sands } 7197f389e8cSChris Lattner break; 7207a9c62baSReid Spencer } 7217f389e8cSChris Lattner case Type::FloatTyID: 72287aa65f4SReid Spencer Result.FloatVal = *((float*)Ptr); 72387aa65f4SReid Spencer break; 72487aa65f4SReid Spencer case Type::DoubleTyID: 72587aa65f4SReid Spencer Result.DoubleVal = *((double*)Ptr); 7267f389e8cSChris Lattner break; 7277a9c62baSReid Spencer case Type::PointerTyID: 72887aa65f4SReid Spencer Result.PointerVal = *((PointerTy*)Ptr); 7297f389e8cSChris Lattner break; 730a1336cf5SDale Johannesen case Type::X86_FP80TyID: { 731a1336cf5SDale Johannesen // This is endian dependent, but it will only work on x86 anyway. 732ff306287SDuncan Sands uint16_t *p = (uint16_t*)Ptr; 733ff306287SDuncan Sands union { 734ff306287SDuncan Sands uint16_t x[8]; 735ff306287SDuncan Sands uint64_t y[2]; 736ff306287SDuncan Sands }; 737a1336cf5SDale Johannesen x[0] = p[1]; 738a1336cf5SDale Johannesen x[1] = p[2]; 739a1336cf5SDale Johannesen x[2] = p[3]; 740a1336cf5SDale Johannesen x[3] = p[4]; 741a1336cf5SDale Johannesen x[4] = p[0]; 742ff306287SDuncan Sands Result.IntVal = APInt(80, 2, y); 743a1336cf5SDale Johannesen break; 744a1336cf5SDale Johannesen } 7457f389e8cSChris Lattner default: 746f3baad3eSBill Wendling cerr << "Cannot load value of type " << *Ty << "!\n"; 7477f389e8cSChris Lattner abort(); 7487f389e8cSChris Lattner } 7497f389e8cSChris Lattner } 7507f389e8cSChris Lattner 751996fe010SChris Lattner // InitializeMemory - Recursive function to apply a Constant value into the 752996fe010SChris Lattner // specified memory location... 753996fe010SChris Lattner // 754996fe010SChris Lattner void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) { 75561753bf8SChris Lattner if (isa<UndefValue>(Init)) { 75661753bf8SChris Lattner return; 757d84d35baSReid Spencer } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) { 75869d62138SRobert Bocchino unsigned ElementSize = 75944b8721dSDuncan Sands getTargetData()->getABITypeSize(CP->getType()->getElementType()); 76069d62138SRobert Bocchino for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) 76169d62138SRobert Bocchino InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize); 76269d62138SRobert Bocchino return; 76361753bf8SChris Lattner } else if (Init->getType()->isFirstClassType()) { 764996fe010SChris Lattner GenericValue Val = getConstantValue(Init); 765996fe010SChris Lattner StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType()); 766996fe010SChris Lattner return; 767834b1272SChris Lattner } else if (isa<ConstantAggregateZero>(Init)) { 76844b8721dSDuncan Sands memset(Addr, 0, (size_t)getTargetData()->getABITypeSize(Init->getType())); 769834b1272SChris Lattner return; 770996fe010SChris Lattner } 771996fe010SChris Lattner 7726b727599SChris Lattner switch (Init->getType()->getTypeID()) { 773996fe010SChris Lattner case Type::ArrayTyID: { 774996fe010SChris Lattner const ConstantArray *CPA = cast<ConstantArray>(Init); 775996fe010SChris Lattner unsigned ElementSize = 77644b8721dSDuncan Sands getTargetData()->getABITypeSize(CPA->getType()->getElementType()); 77783243725SAlkis Evlogimenos for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) 77883243725SAlkis Evlogimenos InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize); 779996fe010SChris Lattner return; 780996fe010SChris Lattner } 781996fe010SChris Lattner 782996fe010SChris Lattner case Type::StructTyID: { 783996fe010SChris Lattner const ConstantStruct *CPS = cast<ConstantStruct>(Init); 784996fe010SChris Lattner const StructLayout *SL = 78520a631fdSOwen Anderson getTargetData()->getStructLayout(cast<StructType>(CPS->getType())); 78683243725SAlkis Evlogimenos for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) 787c473d8e4SChris Lattner InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i)); 788996fe010SChris Lattner return; 789996fe010SChris Lattner } 790996fe010SChris Lattner 791996fe010SChris Lattner default: 792f3baad3eSBill Wendling cerr << "Bad Type: " << *Init->getType() << "\n"; 793996fe010SChris Lattner assert(0 && "Unknown constant type to initialize memory with!"); 794996fe010SChris Lattner } 795996fe010SChris Lattner } 796996fe010SChris Lattner 797996fe010SChris Lattner /// EmitGlobals - Emit all of the global variables to memory, storing their 798996fe010SChris Lattner /// addresses into GlobalAddress. This must make sure to copy the contents of 799996fe010SChris Lattner /// their initializers into the memory. 800996fe010SChris Lattner /// 801996fe010SChris Lattner void ExecutionEngine::emitGlobals() { 80220a631fdSOwen Anderson const TargetData *TD = getTargetData(); 803996fe010SChris Lattner 804996fe010SChris Lattner // Loop over all of the global variables in the program, allocating the memory 8050621caefSChris Lattner // to hold them. If there is more than one module, do a prepass over globals 8060621caefSChris Lattner // to figure out how the different modules should link together. 8070621caefSChris Lattner // 8080621caefSChris Lattner std::map<std::pair<std::string, const Type*>, 8090621caefSChris Lattner const GlobalValue*> LinkedGlobalsMap; 8100621caefSChris Lattner 8110621caefSChris Lattner if (Modules.size() != 1) { 8120621caefSChris Lattner for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 8130621caefSChris Lattner Module &M = *Modules[m]->getModule(); 8140621caefSChris Lattner for (Module::const_global_iterator I = M.global_begin(), 8150621caefSChris Lattner E = M.global_end(); I != E; ++I) { 8160621caefSChris Lattner const GlobalValue *GV = I; 8175301e7c6SReid Spencer if (GV->hasInternalLinkage() || GV->isDeclaration() || 8180621caefSChris Lattner GV->hasAppendingLinkage() || !GV->hasName()) 8190621caefSChris Lattner continue;// Ignore external globals and globals with internal linkage. 8200621caefSChris Lattner 8210621caefSChris Lattner const GlobalValue *&GVEntry = 8220621caefSChris Lattner LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())]; 8230621caefSChris Lattner 8240621caefSChris Lattner // If this is the first time we've seen this global, it is the canonical 8250621caefSChris Lattner // version. 8260621caefSChris Lattner if (!GVEntry) { 8270621caefSChris Lattner GVEntry = GV; 8280621caefSChris Lattner continue; 8290621caefSChris Lattner } 8300621caefSChris Lattner 8310621caefSChris Lattner // If the existing global is strong, never replace it. 832d61d39ecSAnton Korobeynikov if (GVEntry->hasExternalLinkage() || 833d61d39ecSAnton Korobeynikov GVEntry->hasDLLImportLinkage() || 834d61d39ecSAnton Korobeynikov GVEntry->hasDLLExportLinkage()) 8350621caefSChris Lattner continue; 8360621caefSChris Lattner 8370621caefSChris Lattner // Otherwise, we know it's linkonce/weak, replace it if this is a strong 8380621caefSChris Lattner // symbol. 83912c94949SAnton Korobeynikov if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage()) 8400621caefSChris Lattner GVEntry = GV; 8410621caefSChris Lattner } 8420621caefSChris Lattner } 8430621caefSChris Lattner } 8440621caefSChris Lattner 8450621caefSChris Lattner std::vector<const GlobalValue*> NonCanonicalGlobals; 8460621caefSChris Lattner for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 8470621caefSChris Lattner Module &M = *Modules[m]->getModule(); 8488ffb6611SChris Lattner for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 8490621caefSChris Lattner I != E; ++I) { 8500621caefSChris Lattner // In the multi-module case, see what this global maps to. 8510621caefSChris Lattner if (!LinkedGlobalsMap.empty()) { 8520621caefSChris Lattner if (const GlobalValue *GVEntry = 8530621caefSChris Lattner LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) { 8540621caefSChris Lattner // If something else is the canonical global, ignore this one. 8550621caefSChris Lattner if (GVEntry != &*I) { 8560621caefSChris Lattner NonCanonicalGlobals.push_back(I); 8570621caefSChris Lattner continue; 8580621caefSChris Lattner } 8590621caefSChris Lattner } 8600621caefSChris Lattner } 8610621caefSChris Lattner 8625301e7c6SReid Spencer if (!I->isDeclaration()) { 8630621caefSChris Lattner // Get the type of the global. 864996fe010SChris Lattner const Type *Ty = I->getType()->getElementType(); 865996fe010SChris Lattner 866996fe010SChris Lattner // Allocate some memory for it! 86744b8721dSDuncan Sands unsigned Size = TD->getABITypeSize(Ty); 8686bbe3eceSChris Lattner addGlobalMapping(I, new char[Size]); 869996fe010SChris Lattner } else { 870e8bbcfc2SBrian Gaeke // External variable reference. Try to use the dynamic loader to 871e8bbcfc2SBrian Gaeke // get a pointer to it. 8720621caefSChris Lattner if (void *SymAddr = 8730621caefSChris Lattner sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str())) 874748e8579SChris Lattner addGlobalMapping(I, SymAddr); 8759de0d14dSChris Lattner else { 876f3baad3eSBill Wendling cerr << "Could not resolve external global address: " 8779de0d14dSChris Lattner << I->getName() << "\n"; 8789de0d14dSChris Lattner abort(); 8799de0d14dSChris Lattner } 880996fe010SChris Lattner } 8810621caefSChris Lattner } 8820621caefSChris Lattner 8830621caefSChris Lattner // If there are multiple modules, map the non-canonical globals to their 8840621caefSChris Lattner // canonical location. 8850621caefSChris Lattner if (!NonCanonicalGlobals.empty()) { 8860621caefSChris Lattner for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) { 8870621caefSChris Lattner const GlobalValue *GV = NonCanonicalGlobals[i]; 8880621caefSChris Lattner const GlobalValue *CGV = 8890621caefSChris Lattner LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())]; 8900621caefSChris Lattner void *Ptr = getPointerToGlobalIfAvailable(CGV); 8910621caefSChris Lattner assert(Ptr && "Canonical global wasn't codegen'd!"); 8920621caefSChris Lattner addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV)); 8930621caefSChris Lattner } 8940621caefSChris Lattner } 895996fe010SChris Lattner 8967a9c62baSReid Spencer // Now that all of the globals are set up in memory, loop through them all 8977a9c62baSReid Spencer // and initialize their contents. 8988ffb6611SChris Lattner for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 8990621caefSChris Lattner I != E; ++I) { 9005301e7c6SReid Spencer if (!I->isDeclaration()) { 9010621caefSChris Lattner if (!LinkedGlobalsMap.empty()) { 9020621caefSChris Lattner if (const GlobalValue *GVEntry = 9030621caefSChris Lattner LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) 9040621caefSChris Lattner if (GVEntry != &*I) // Not the canonical variable. 9050621caefSChris Lattner continue; 9060621caefSChris Lattner } 9076bbe3eceSChris Lattner EmitGlobalVariable(I); 9086bbe3eceSChris Lattner } 9090621caefSChris Lattner } 9100621caefSChris Lattner } 9110621caefSChris Lattner } 9126bbe3eceSChris Lattner 9136bbe3eceSChris Lattner // EmitGlobalVariable - This method emits the specified global variable to the 9146bbe3eceSChris Lattner // address specified in GlobalAddresses, or allocates new memory if it's not 9156bbe3eceSChris Lattner // already in the map. 916fbcc0aa1SChris Lattner void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) { 917748e8579SChris Lattner void *GA = getPointerToGlobalIfAvailable(GV); 9185834fdb3SBill Wendling DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n"; 919dc631735SChris Lattner 920fbcc0aa1SChris Lattner const Type *ElTy = GV->getType()->getElementType(); 92144b8721dSDuncan Sands size_t GVSize = (size_t)getTargetData()->getABITypeSize(ElTy); 9226bbe3eceSChris Lattner if (GA == 0) { 9236bbe3eceSChris Lattner // If it's not already specified, allocate memory for the global. 924d215992bSChris Lattner GA = new char[GVSize]; 925748e8579SChris Lattner addGlobalMapping(GV, GA); 9266bbe3eceSChris Lattner } 927fbcc0aa1SChris Lattner 9286bbe3eceSChris Lattner InitializeMemory(GV->getInitializer(), GA); 929df1f1524SChris Lattner NumInitBytes += (unsigned)GVSize; 9306bbe3eceSChris Lattner ++NumGlobals; 931996fe010SChris Lattner } 932