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