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/STLExtras.h" 17 #include "llvm/ADT/SmallString.h" 18 #include "llvm/ADT/Statistic.h" 19 #include "llvm/ExecutionEngine/GenericValue.h" 20 #include "llvm/ExecutionEngine/JITEventListener.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/Archive.h" 28 #include "llvm/Object/ObjectFile.h" 29 #include "llvm/Support/Debug.h" 30 #include "llvm/Support/DynamicLibrary.h" 31 #include "llvm/Support/ErrorHandling.h" 32 #include "llvm/Support/Host.h" 33 #include "llvm/Support/MutexGuard.h" 34 #include "llvm/Support/TargetRegistry.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include "llvm/Target/TargetMachine.h" 37 #include <cmath> 38 #include <cstring> 39 using namespace llvm; 40 41 #define DEBUG_TYPE "jit" 42 43 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized"); 44 STATISTIC(NumGlobals , "Number of global vars initialized"); 45 46 ExecutionEngine *(*ExecutionEngine::MCJITCtor)( 47 std::unique_ptr<Module> M, std::string *ErrorStr, 48 std::unique_ptr<RTDyldMemoryManager> MCJMM, 49 std::unique_ptr<TargetMachine> TM) = nullptr; 50 51 ExecutionEngine *(*ExecutionEngine::OrcMCJITReplacementCtor)( 52 std::string *ErrorStr, std::unique_ptr<RTDyldMemoryManager> OrcJMM, 53 std::unique_ptr<TargetMachine> TM) = nullptr; 54 55 ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M, 56 std::string *ErrorStr) =nullptr; 57 58 void JITEventListener::anchor() {} 59 60 ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M) 61 : EEState(*this), 62 LazyFunctionCreator(nullptr) { 63 CompilingLazily = false; 64 GVCompilationDisabled = false; 65 SymbolSearchingDisabled = false; 66 67 // IR module verification is enabled by default in debug builds, and disabled 68 // by default in release builds. 69 #ifndef NDEBUG 70 VerifyModules = true; 71 #else 72 VerifyModules = false; 73 #endif 74 75 assert(M && "Module is null?"); 76 Modules.push_back(std::move(M)); 77 } 78 79 ExecutionEngine::~ExecutionEngine() { 80 clearAllGlobalMappings(); 81 } 82 83 namespace { 84 /// \brief Helper class which uses a value handler to automatically deletes the 85 /// memory block when the GlobalVariable is destroyed. 86 class GVMemoryBlock : public CallbackVH { 87 GVMemoryBlock(const GlobalVariable *GV) 88 : CallbackVH(const_cast<GlobalVariable*>(GV)) {} 89 90 public: 91 /// \brief Returns the address the GlobalVariable should be written into. The 92 /// GVMemoryBlock object prefixes that. 93 static char *Create(const GlobalVariable *GV, const DataLayout& TD) { 94 Type *ElTy = GV->getType()->getElementType(); 95 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy); 96 void *RawMemory = ::operator new( 97 RoundUpToAlignment(sizeof(GVMemoryBlock), 98 TD.getPreferredAlignment(GV)) 99 + GVSize); 100 new(RawMemory) GVMemoryBlock(GV); 101 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock); 102 } 103 104 void deleted() override { 105 // We allocated with operator new and with some extra memory hanging off the 106 // end, so don't just delete this. I'm not sure if this is actually 107 // required. 108 this->~GVMemoryBlock(); 109 ::operator delete(this); 110 } 111 }; 112 } // anonymous namespace 113 114 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) { 115 return GVMemoryBlock::Create(GV, *getDataLayout()); 116 } 117 118 void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) { 119 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile."); 120 } 121 122 void 123 ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) { 124 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile."); 125 } 126 127 void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) { 128 llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive."); 129 } 130 131 bool ExecutionEngine::removeModule(Module *M) { 132 for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) { 133 Module *Found = I->get(); 134 if (Found == M) { 135 I->release(); 136 Modules.erase(I); 137 clearGlobalMappingsFromModule(M); 138 return true; 139 } 140 } 141 return false; 142 } 143 144 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) { 145 for (unsigned i = 0, e = Modules.size(); i != e; ++i) { 146 Function *F = Modules[i]->getFunction(FnName); 147 if (F && !F->isDeclaration()) 148 return F; 149 } 150 return nullptr; 151 } 152 153 154 void *ExecutionEngineState::RemoveMapping(const GlobalValue *ToUnmap) { 155 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap); 156 void *OldVal; 157 158 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the 159 // GlobalAddressMap. 160 if (I == GlobalAddressMap.end()) 161 OldVal = nullptr; 162 else { 163 OldVal = I->second; 164 GlobalAddressMap.erase(I); 165 } 166 167 GlobalAddressReverseMap.erase(OldVal); 168 return OldVal; 169 } 170 171 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) { 172 MutexGuard locked(lock); 173 174 DEBUG(dbgs() << "JIT: Map \'" << GV->getName() 175 << "\' to [" << Addr << "]\n";); 176 void *&CurVal = EEState.getGlobalAddressMap()[GV]; 177 assert((!CurVal || !Addr) && "GlobalMapping already established!"); 178 CurVal = Addr; 179 180 // If we are using the reverse mapping, add it too. 181 if (!EEState.getGlobalAddressReverseMap().empty()) { 182 AssertingVH<const GlobalValue> &V = 183 EEState.getGlobalAddressReverseMap()[Addr]; 184 assert((!V || !GV) && "GlobalMapping already established!"); 185 V = GV; 186 } 187 } 188 189 void ExecutionEngine::clearAllGlobalMappings() { 190 MutexGuard locked(lock); 191 192 EEState.getGlobalAddressMap().clear(); 193 EEState.getGlobalAddressReverseMap().clear(); 194 } 195 196 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) { 197 MutexGuard locked(lock); 198 199 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) 200 EEState.RemoveMapping(FI); 201 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end(); 202 GI != GE; ++GI) 203 EEState.RemoveMapping(GI); 204 } 205 206 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) { 207 MutexGuard locked(lock); 208 209 ExecutionEngineState::GlobalAddressMapTy &Map = 210 EEState.getGlobalAddressMap(); 211 212 // Deleting from the mapping? 213 if (!Addr) 214 return EEState.RemoveMapping(GV); 215 216 void *&CurVal = Map[GV]; 217 void *OldVal = CurVal; 218 219 if (CurVal && !EEState.getGlobalAddressReverseMap().empty()) 220 EEState.getGlobalAddressReverseMap().erase(CurVal); 221 CurVal = Addr; 222 223 // If we are using the reverse mapping, add it too. 224 if (!EEState.getGlobalAddressReverseMap().empty()) { 225 AssertingVH<const GlobalValue> &V = 226 EEState.getGlobalAddressReverseMap()[Addr]; 227 assert((!V || !GV) && "GlobalMapping already established!"); 228 V = GV; 229 } 230 return OldVal; 231 } 232 233 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) { 234 MutexGuard locked(lock); 235 236 ExecutionEngineState::GlobalAddressMapTy::iterator I = 237 EEState.getGlobalAddressMap().find(GV); 238 return I != EEState.getGlobalAddressMap().end() ? I->second : nullptr; 239 } 240 241 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) { 242 MutexGuard locked(lock); 243 244 // If we haven't computed the reverse mapping yet, do so first. 245 if (EEState.getGlobalAddressReverseMap().empty()) { 246 for (ExecutionEngineState::GlobalAddressMapTy::iterator 247 I = EEState.getGlobalAddressMap().begin(), 248 E = EEState.getGlobalAddressMap().end(); I != E; ++I) 249 EEState.getGlobalAddressReverseMap().insert(std::make_pair( 250 I->second, I->first)); 251 } 252 253 std::map<void *, AssertingVH<const GlobalValue> >::iterator I = 254 EEState.getGlobalAddressReverseMap().find(Addr); 255 return I != EEState.getGlobalAddressReverseMap().end() ? I->second : nullptr; 256 } 257 258 namespace { 259 class ArgvArray { 260 std::unique_ptr<char[]> Array; 261 std::vector<std::unique_ptr<char[]>> Values; 262 public: 263 /// Turn a vector of strings into a nice argv style array of pointers to null 264 /// terminated strings. 265 void *reset(LLVMContext &C, ExecutionEngine *EE, 266 const std::vector<std::string> &InputArgv); 267 }; 268 } // anonymous namespace 269 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE, 270 const std::vector<std::string> &InputArgv) { 271 Values.clear(); // Free the old contents. 272 Values.reserve(InputArgv.size()); 273 unsigned PtrSize = EE->getDataLayout()->getPointerSize(); 274 Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize); 275 276 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array.get() << "\n"); 277 Type *SBytePtr = Type::getInt8PtrTy(C); 278 279 for (unsigned i = 0; i != InputArgv.size(); ++i) { 280 unsigned Size = InputArgv[i].size()+1; 281 auto Dest = make_unique<char[]>(Size); 282 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest.get() << "\n"); 283 284 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get()); 285 Dest[Size-1] = 0; 286 287 // Endian safe: Array[i] = (PointerTy)Dest; 288 EE->StoreValueToMemory(PTOGV(Dest.get()), 289 (GenericValue*)(&Array[i*PtrSize]), SBytePtr); 290 Values.push_back(std::move(Dest)); 291 } 292 293 // Null terminate it 294 EE->StoreValueToMemory(PTOGV(nullptr), 295 (GenericValue*)(&Array[InputArgv.size()*PtrSize]), 296 SBytePtr); 297 return Array.get(); 298 } 299 300 void ExecutionEngine::runStaticConstructorsDestructors(Module &module, 301 bool isDtors) { 302 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors"; 303 GlobalVariable *GV = module.getNamedGlobal(Name); 304 305 // If this global has internal linkage, or if it has a use, then it must be 306 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If 307 // this is the case, don't execute any of the global ctors, __main will do 308 // it. 309 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return; 310 311 // Should be an array of '{ i32, void ()* }' structs. The first value is 312 // the init priority, which we ignore. 313 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer()); 314 if (!InitList) 315 return; 316 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 317 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i)); 318 if (!CS) continue; 319 320 Constant *FP = CS->getOperand(1); 321 if (FP->isNullValue()) 322 continue; // Found a sentinal value, ignore. 323 324 // Strip off constant expression casts. 325 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP)) 326 if (CE->isCast()) 327 FP = CE->getOperand(0); 328 329 // Execute the ctor/dtor function! 330 if (Function *F = dyn_cast<Function>(FP)) 331 runFunction(F, std::vector<GenericValue>()); 332 333 // FIXME: It is marginally lame that we just do nothing here if we see an 334 // entry we don't recognize. It might not be unreasonable for the verifier 335 // to not even allow this and just assert here. 336 } 337 } 338 339 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) { 340 // Execute global ctors/dtors for each module in the program. 341 for (std::unique_ptr<Module> &M : Modules) 342 runStaticConstructorsDestructors(*M, isDtors); 343 } 344 345 #ifndef NDEBUG 346 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null. 347 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) { 348 unsigned PtrSize = EE->getDataLayout()->getPointerSize(); 349 for (unsigned i = 0; i < PtrSize; ++i) 350 if (*(i + (uint8_t*)Loc)) 351 return false; 352 return true; 353 } 354 #endif 355 356 int ExecutionEngine::runFunctionAsMain(Function *Fn, 357 const std::vector<std::string> &argv, 358 const char * const * envp) { 359 std::vector<GenericValue> GVArgs; 360 GenericValue GVArgc; 361 GVArgc.IntVal = APInt(32, argv.size()); 362 363 // Check main() type 364 unsigned NumArgs = Fn->getFunctionType()->getNumParams(); 365 FunctionType *FTy = Fn->getFunctionType(); 366 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo(); 367 368 // Check the argument types. 369 if (NumArgs > 3) 370 report_fatal_error("Invalid number of arguments of main() supplied"); 371 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty) 372 report_fatal_error("Invalid type for third argument of main() supplied"); 373 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty) 374 report_fatal_error("Invalid type for second argument of main() supplied"); 375 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32)) 376 report_fatal_error("Invalid type for first argument of main() supplied"); 377 if (!FTy->getReturnType()->isIntegerTy() && 378 !FTy->getReturnType()->isVoidTy()) 379 report_fatal_error("Invalid return type of main() supplied"); 380 381 ArgvArray CArgv; 382 ArgvArray CEnv; 383 if (NumArgs) { 384 GVArgs.push_back(GVArgc); // Arg #0 = argc. 385 if (NumArgs > 1) { 386 // Arg #1 = argv. 387 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv))); 388 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) && 389 "argv[0] was null after CreateArgv"); 390 if (NumArgs > 2) { 391 std::vector<std::string> EnvVars; 392 for (unsigned i = 0; envp[i]; ++i) 393 EnvVars.push_back(envp[i]); 394 // Arg #2 = envp. 395 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars))); 396 } 397 } 398 } 399 400 return runFunction(Fn, GVArgs).IntVal.getZExtValue(); 401 } 402 403 EngineBuilder::EngineBuilder() { 404 InitEngine(); 405 } 406 407 EngineBuilder::EngineBuilder(std::unique_ptr<Module> M) 408 : M(std::move(M)), MCJMM(nullptr) { 409 InitEngine(); 410 } 411 412 EngineBuilder::~EngineBuilder() {} 413 414 EngineBuilder &EngineBuilder::setMCJITMemoryManager( 415 std::unique_ptr<RTDyldMemoryManager> mcjmm) { 416 MCJMM = std::move(mcjmm); 417 return *this; 418 } 419 420 void EngineBuilder::InitEngine() { 421 WhichEngine = EngineKind::Either; 422 ErrorStr = nullptr; 423 OptLevel = CodeGenOpt::Default; 424 MCJMM = nullptr; 425 Options = TargetOptions(); 426 RelocModel = Reloc::Default; 427 CMModel = CodeModel::JITDefault; 428 UseOrcMCJITReplacement = false; 429 430 // IR module verification is enabled by default in debug builds, and disabled 431 // by default in release builds. 432 #ifndef NDEBUG 433 VerifyModules = true; 434 #else 435 VerifyModules = false; 436 #endif 437 } 438 439 ExecutionEngine *EngineBuilder::create(TargetMachine *TM) { 440 std::unique_ptr<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(nullptr, ErrorStr)) 445 return nullptr; 446 447 // If the user specified a memory manager but didn't specify which engine to 448 // create, we assume they only want the JIT, and we fail if they only want 449 // the interpreter. 450 if (MCJMM) { 451 if (WhichEngine & EngineKind::JIT) 452 WhichEngine = EngineKind::JIT; 453 else { 454 if (ErrorStr) 455 *ErrorStr = "Cannot create an interpreter with a memory manager."; 456 return nullptr; 457 } 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 (ExecutionEngine::OrcMCJITReplacementCtor && UseOrcMCJITReplacement) { 472 EE = ExecutionEngine::OrcMCJITReplacementCtor(ErrorStr, std::move(MCJMM), 473 std::move(TheTM)); 474 EE->addModule(std::move(M)); 475 } else if (ExecutionEngine::MCJITCtor) 476 EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MCJMM), 477 std::move(TheTM)); 478 479 if (EE) { 480 EE->setVerifyModules(VerifyModules); 481 return EE; 482 } 483 } 484 485 // If we can't make a JIT and we didn't request one specifically, try making 486 // an interpreter instead. 487 if (WhichEngine & EngineKind::Interpreter) { 488 if (ExecutionEngine::InterpCtor) 489 return ExecutionEngine::InterpCtor(std::move(M), ErrorStr); 490 if (ErrorStr) 491 *ErrorStr = "Interpreter has not been linked in."; 492 return nullptr; 493 } 494 495 if ((WhichEngine & EngineKind::JIT) && !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 842 llvm_unreachable("Unknown constant pointer type!"); 843 break; 844 case Type::VectorTyID: { 845 unsigned elemNum; 846 Type* ElemTy; 847 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C); 848 const ConstantVector *CV = dyn_cast<ConstantVector>(C); 849 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C); 850 851 if (CDV) { 852 elemNum = CDV->getNumElements(); 853 ElemTy = CDV->getElementType(); 854 } else if (CV || CAZ) { 855 VectorType* VTy = dyn_cast<VectorType>(C->getType()); 856 elemNum = VTy->getNumElements(); 857 ElemTy = VTy->getElementType(); 858 } else { 859 llvm_unreachable("Unknown constant vector type!"); 860 } 861 862 Result.AggregateVal.resize(elemNum); 863 // Check if vector holds floats. 864 if(ElemTy->isFloatTy()) { 865 if (CAZ) { 866 GenericValue floatZero; 867 floatZero.FloatVal = 0.f; 868 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(), 869 floatZero); 870 break; 871 } 872 if(CV) { 873 for (unsigned i = 0; i < elemNum; ++i) 874 if (!isa<UndefValue>(CV->getOperand(i))) 875 Result.AggregateVal[i].FloatVal = cast<ConstantFP>( 876 CV->getOperand(i))->getValueAPF().convertToFloat(); 877 break; 878 } 879 if(CDV) 880 for (unsigned i = 0; i < elemNum; ++i) 881 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i); 882 883 break; 884 } 885 // Check if vector holds doubles. 886 if (ElemTy->isDoubleTy()) { 887 if (CAZ) { 888 GenericValue doubleZero; 889 doubleZero.DoubleVal = 0.0; 890 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(), 891 doubleZero); 892 break; 893 } 894 if(CV) { 895 for (unsigned i = 0; i < elemNum; ++i) 896 if (!isa<UndefValue>(CV->getOperand(i))) 897 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>( 898 CV->getOperand(i))->getValueAPF().convertToDouble(); 899 break; 900 } 901 if(CDV) 902 for (unsigned i = 0; i < elemNum; ++i) 903 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i); 904 905 break; 906 } 907 // Check if vector holds integers. 908 if (ElemTy->isIntegerTy()) { 909 if (CAZ) { 910 GenericValue intZero; 911 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull); 912 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(), 913 intZero); 914 break; 915 } 916 if(CV) { 917 for (unsigned i = 0; i < elemNum; ++i) 918 if (!isa<UndefValue>(CV->getOperand(i))) 919 Result.AggregateVal[i].IntVal = cast<ConstantInt>( 920 CV->getOperand(i))->getValue(); 921 else { 922 Result.AggregateVal[i].IntVal = 923 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0); 924 } 925 break; 926 } 927 if(CDV) 928 for (unsigned i = 0; i < elemNum; ++i) 929 Result.AggregateVal[i].IntVal = APInt( 930 CDV->getElementType()->getPrimitiveSizeInBits(), 931 CDV->getElementAsInteger(i)); 932 933 break; 934 } 935 llvm_unreachable("Unknown constant pointer type!"); 936 } 937 break; 938 939 default: 940 SmallString<256> Msg; 941 raw_svector_ostream OS(Msg); 942 OS << "ERROR: Constant unimplemented for type: " << *C->getType(); 943 report_fatal_error(OS.str()); 944 } 945 946 return Result; 947 } 948 949 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst 950 /// with the integer held in IntVal. 951 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst, 952 unsigned StoreBytes) { 953 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!"); 954 const uint8_t *Src = (const uint8_t *)IntVal.getRawData(); 955 956 if (sys::IsLittleEndianHost) { 957 // Little-endian host - the source is ordered from LSB to MSB. Order the 958 // destination from LSB to MSB: Do a straight copy. 959 memcpy(Dst, Src, StoreBytes); 960 } else { 961 // Big-endian host - the source is an array of 64 bit words ordered from 962 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination 963 // from MSB to LSB: Reverse the word order, but not the bytes in a word. 964 while (StoreBytes > sizeof(uint64_t)) { 965 StoreBytes -= sizeof(uint64_t); 966 // May not be aligned so use memcpy. 967 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t)); 968 Src += sizeof(uint64_t); 969 } 970 971 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes); 972 } 973 } 974 975 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, 976 GenericValue *Ptr, Type *Ty) { 977 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty); 978 979 switch (Ty->getTypeID()) { 980 default: 981 dbgs() << "Cannot store value of type " << *Ty << "!\n"; 982 break; 983 case Type::IntegerTyID: 984 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes); 985 break; 986 case Type::FloatTyID: 987 *((float*)Ptr) = Val.FloatVal; 988 break; 989 case Type::DoubleTyID: 990 *((double*)Ptr) = Val.DoubleVal; 991 break; 992 case Type::X86_FP80TyID: 993 memcpy(Ptr, Val.IntVal.getRawData(), 10); 994 break; 995 case Type::PointerTyID: 996 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts. 997 if (StoreBytes != sizeof(PointerTy)) 998 memset(&(Ptr->PointerVal), 0, StoreBytes); 999 1000 *((PointerTy*)Ptr) = Val.PointerVal; 1001 break; 1002 case Type::VectorTyID: 1003 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) { 1004 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy()) 1005 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal; 1006 if (cast<VectorType>(Ty)->getElementType()->isFloatTy()) 1007 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal; 1008 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) { 1009 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8; 1010 StoreIntToMemory(Val.AggregateVal[i].IntVal, 1011 (uint8_t*)Ptr + numOfBytes*i, numOfBytes); 1012 } 1013 } 1014 break; 1015 } 1016 1017 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian()) 1018 // Host and target are different endian - reverse the stored bytes. 1019 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr); 1020 } 1021 1022 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting 1023 /// from Src into IntVal, which is assumed to be wide enough and to hold zero. 1024 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) { 1025 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!"); 1026 uint8_t *Dst = reinterpret_cast<uint8_t *>( 1027 const_cast<uint64_t *>(IntVal.getRawData())); 1028 1029 if (sys::IsLittleEndianHost) 1030 // Little-endian host - the destination must be ordered from LSB to MSB. 1031 // The source is ordered from LSB to MSB: Do a straight copy. 1032 memcpy(Dst, Src, LoadBytes); 1033 else { 1034 // Big-endian - the destination is an array of 64 bit words ordered from 1035 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is 1036 // ordered from MSB to LSB: Reverse the word order, but not the bytes in 1037 // a word. 1038 while (LoadBytes > sizeof(uint64_t)) { 1039 LoadBytes -= sizeof(uint64_t); 1040 // May not be aligned so use memcpy. 1041 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t)); 1042 Dst += sizeof(uint64_t); 1043 } 1044 1045 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes); 1046 } 1047 } 1048 1049 /// FIXME: document 1050 /// 1051 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result, 1052 GenericValue *Ptr, 1053 Type *Ty) { 1054 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty); 1055 1056 switch (Ty->getTypeID()) { 1057 case Type::IntegerTyID: 1058 // An APInt with all words initially zero. 1059 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0); 1060 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes); 1061 break; 1062 case Type::FloatTyID: 1063 Result.FloatVal = *((float*)Ptr); 1064 break; 1065 case Type::DoubleTyID: 1066 Result.DoubleVal = *((double*)Ptr); 1067 break; 1068 case Type::PointerTyID: 1069 Result.PointerVal = *((PointerTy*)Ptr); 1070 break; 1071 case Type::X86_FP80TyID: { 1072 // This is endian dependent, but it will only work on x86 anyway. 1073 // FIXME: Will not trap if loading a signaling NaN. 1074 uint64_t y[2]; 1075 memcpy(y, Ptr, 10); 1076 Result.IntVal = APInt(80, y); 1077 break; 1078 } 1079 case Type::VectorTyID: { 1080 const VectorType *VT = cast<VectorType>(Ty); 1081 const Type *ElemT = VT->getElementType(); 1082 const unsigned numElems = VT->getNumElements(); 1083 if (ElemT->isFloatTy()) { 1084 Result.AggregateVal.resize(numElems); 1085 for (unsigned i = 0; i < numElems; ++i) 1086 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i); 1087 } 1088 if (ElemT->isDoubleTy()) { 1089 Result.AggregateVal.resize(numElems); 1090 for (unsigned i = 0; i < numElems; ++i) 1091 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i); 1092 } 1093 if (ElemT->isIntegerTy()) { 1094 GenericValue intZero; 1095 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth(); 1096 intZero.IntVal = APInt(elemBitWidth, 0); 1097 Result.AggregateVal.resize(numElems, intZero); 1098 for (unsigned i = 0; i < numElems; ++i) 1099 LoadIntFromMemory(Result.AggregateVal[i].IntVal, 1100 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8); 1101 } 1102 break; 1103 } 1104 default: 1105 SmallString<256> Msg; 1106 raw_svector_ostream OS(Msg); 1107 OS << "Cannot load value of type " << *Ty << "!"; 1108 report_fatal_error(OS.str()); 1109 } 1110 } 1111 1112 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) { 1113 DEBUG(dbgs() << "JIT: Initializing " << Addr << " "); 1114 DEBUG(Init->dump()); 1115 if (isa<UndefValue>(Init)) 1116 return; 1117 1118 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) { 1119 unsigned ElementSize = 1120 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType()); 1121 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) 1122 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize); 1123 return; 1124 } 1125 1126 if (isa<ConstantAggregateZero>(Init)) { 1127 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType())); 1128 return; 1129 } 1130 1131 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) { 1132 unsigned ElementSize = 1133 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType()); 1134 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) 1135 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize); 1136 return; 1137 } 1138 1139 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) { 1140 const StructLayout *SL = 1141 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType())); 1142 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) 1143 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i)); 1144 return; 1145 } 1146 1147 if (const ConstantDataSequential *CDS = 1148 dyn_cast<ConstantDataSequential>(Init)) { 1149 // CDS is already laid out in host memory order. 1150 StringRef Data = CDS->getRawDataValues(); 1151 memcpy(Addr, Data.data(), Data.size()); 1152 return; 1153 } 1154 1155 if (Init->getType()->isFirstClassType()) { 1156 GenericValue Val = getConstantValue(Init); 1157 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType()); 1158 return; 1159 } 1160 1161 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n"); 1162 llvm_unreachable("Unknown constant type to initialize memory with!"); 1163 } 1164 1165 /// EmitGlobals - Emit all of the global variables to memory, storing their 1166 /// addresses into GlobalAddress. This must make sure to copy the contents of 1167 /// their initializers into the memory. 1168 void ExecutionEngine::emitGlobals() { 1169 // Loop over all of the global variables in the program, allocating the memory 1170 // to hold them. If there is more than one module, do a prepass over globals 1171 // to figure out how the different modules should link together. 1172 std::map<std::pair<std::string, Type*>, 1173 const GlobalValue*> LinkedGlobalsMap; 1174 1175 if (Modules.size() != 1) { 1176 for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 1177 Module &M = *Modules[m]; 1178 for (const auto &GV : M.globals()) { 1179 if (GV.hasLocalLinkage() || GV.isDeclaration() || 1180 GV.hasAppendingLinkage() || !GV.hasName()) 1181 continue;// Ignore external globals and globals with internal linkage. 1182 1183 const GlobalValue *&GVEntry = 1184 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]; 1185 1186 // If this is the first time we've seen this global, it is the canonical 1187 // version. 1188 if (!GVEntry) { 1189 GVEntry = &GV; 1190 continue; 1191 } 1192 1193 // If the existing global is strong, never replace it. 1194 if (GVEntry->hasExternalLinkage()) 1195 continue; 1196 1197 // Otherwise, we know it's linkonce/weak, replace it if this is a strong 1198 // symbol. FIXME is this right for common? 1199 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage()) 1200 GVEntry = &GV; 1201 } 1202 } 1203 } 1204 1205 std::vector<const GlobalValue*> NonCanonicalGlobals; 1206 for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 1207 Module &M = *Modules[m]; 1208 for (const auto &GV : M.globals()) { 1209 // In the multi-module case, see what this global maps to. 1210 if (!LinkedGlobalsMap.empty()) { 1211 if (const GlobalValue *GVEntry = 1212 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) { 1213 // If something else is the canonical global, ignore this one. 1214 if (GVEntry != &GV) { 1215 NonCanonicalGlobals.push_back(&GV); 1216 continue; 1217 } 1218 } 1219 } 1220 1221 if (!GV.isDeclaration()) { 1222 addGlobalMapping(&GV, getMemoryForGV(&GV)); 1223 } else { 1224 // External variable reference. Try to use the dynamic loader to 1225 // get a pointer to it. 1226 if (void *SymAddr = 1227 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName())) 1228 addGlobalMapping(&GV, SymAddr); 1229 else { 1230 report_fatal_error("Could not resolve external global address: " 1231 +GV.getName()); 1232 } 1233 } 1234 } 1235 1236 // If there are multiple modules, map the non-canonical globals to their 1237 // canonical location. 1238 if (!NonCanonicalGlobals.empty()) { 1239 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) { 1240 const GlobalValue *GV = NonCanonicalGlobals[i]; 1241 const GlobalValue *CGV = 1242 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())]; 1243 void *Ptr = getPointerToGlobalIfAvailable(CGV); 1244 assert(Ptr && "Canonical global wasn't codegen'd!"); 1245 addGlobalMapping(GV, Ptr); 1246 } 1247 } 1248 1249 // Now that all of the globals are set up in memory, loop through them all 1250 // and initialize their contents. 1251 for (const auto &GV : M.globals()) { 1252 if (!GV.isDeclaration()) { 1253 if (!LinkedGlobalsMap.empty()) { 1254 if (const GlobalValue *GVEntry = 1255 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) 1256 if (GVEntry != &GV) // Not the canonical variable. 1257 continue; 1258 } 1259 EmitGlobalVariable(&GV); 1260 } 1261 } 1262 } 1263 } 1264 1265 // EmitGlobalVariable - This method emits the specified global variable to the 1266 // address specified in GlobalAddresses, or allocates new memory if it's not 1267 // already in the map. 1268 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) { 1269 void *GA = getPointerToGlobalIfAvailable(GV); 1270 1271 if (!GA) { 1272 // If it's not already specified, allocate memory for the global. 1273 GA = getMemoryForGV(GV); 1274 1275 // If we failed to allocate memory for this global, return. 1276 if (!GA) return; 1277 1278 addGlobalMapping(GV, GA); 1279 } 1280 1281 // Don't initialize if it's thread local, let the client do it. 1282 if (!GV->isThreadLocal()) 1283 InitializeMemory(GV->getInitializer(), GA); 1284 1285 Type *ElTy = GV->getType()->getElementType(); 1286 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy); 1287 NumInitBytes += (unsigned)GVSize; 1288 ++NumGlobals; 1289 } 1290 1291 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE) 1292 : EE(EE), GlobalAddressMap(this) { 1293 } 1294 1295 sys::Mutex * 1296 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) { 1297 return &EES->EE.lock; 1298 } 1299 1300 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES, 1301 const GlobalValue *Old) { 1302 void *OldVal = EES->GlobalAddressMap.lookup(Old); 1303 EES->GlobalAddressReverseMap.erase(OldVal); 1304 } 1305 1306 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *, 1307 const GlobalValue *, 1308 const GlobalValue *) { 1309 llvm_unreachable("The ExecutionEngine doesn't know how to handle a" 1310 " RAUW on a value it has a global mapping for."); 1311 } 1312