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