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