1 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the common interface used by the various execution engine
13 //===----------------------------------------------------------------------===//
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"
40 #define DEBUG_TYPE "jit"
42 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
43 STATISTIC(NumGlobals , "Number of global vars initialized");
45 // Pin the vtable to this file.
46 void ObjectCache::anchor() {}
47 void ObjectBuffer::anchor() {}
48 void ObjectBufferStream::anchor() {}
50 ExecutionEngine *(*ExecutionEngine::JITCtor)(
52 std::string *ErrorStr,
53 JITMemoryManager *JMM,
55 TargetMachine *TM) = nullptr;
56 ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
58 std::string *ErrorStr,
59 RTDyldMemoryManager *MCJMM,
61 TargetMachine *TM) = nullptr;
62 ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
63 std::string *ErrorStr) =nullptr;
65 ExecutionEngine::ExecutionEngine(Module *M)
67 LazyFunctionCreator(nullptr) {
68 CompilingLazily = false;
69 GVCompilationDisabled = false;
70 SymbolSearchingDisabled = false;
72 // IR module verification is enabled by default in debug builds, and disabled
73 // by default in release builds.
77 VerifyModules = false;
81 assert(M && "Module is null?");
84 ExecutionEngine::~ExecutionEngine() {
85 clearAllGlobalMappings();
86 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
91 /// \brief Helper class which uses a value handler to automatically deletes the
92 /// memory block when the GlobalVariable is destroyed.
93 class GVMemoryBlock : public CallbackVH {
94 GVMemoryBlock(const GlobalVariable *GV)
95 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
98 /// \brief Returns the address the GlobalVariable should be written into. The
99 /// GVMemoryBlock object prefixes that.
100 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
101 Type *ElTy = GV->getType()->getElementType();
102 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
103 void *RawMemory = ::operator new(
104 DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock),
105 TD.getPreferredAlignment(GV))
107 new(RawMemory) GVMemoryBlock(GV);
108 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
111 void deleted() override {
112 // We allocated with operator new and with some extra memory hanging off the
113 // end, so don't just delete this. I'm not sure if this is actually
115 this->~GVMemoryBlock();
116 ::operator delete(this);
119 } // anonymous namespace
121 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
122 return GVMemoryBlock::Create(GV, *getDataLayout());
125 void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
126 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
129 bool ExecutionEngine::removeModule(Module *M) {
130 for(SmallVectorImpl<Module *>::iterator I = Modules.begin(),
131 E = Modules.end(); I != E; ++I) {
135 clearGlobalMappingsFromModule(M);
142 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
143 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
144 if (Function *F = Modules[i]->getFunction(FnName))
151 void *ExecutionEngineState::RemoveMapping(const GlobalValue *ToUnmap) {
152 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
155 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
157 if (I == GlobalAddressMap.end())
161 GlobalAddressMap.erase(I);
164 GlobalAddressReverseMap.erase(OldVal);
168 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
169 std::lock_guard<std::recursive_mutex> locked(lock);
171 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
172 << "\' to [" << Addr << "]\n";);
173 void *&CurVal = EEState.getGlobalAddressMap()[GV];
174 assert((!CurVal || !Addr) && "GlobalMapping already established!");
177 // If we are using the reverse mapping, add it too.
178 if (!EEState.getGlobalAddressReverseMap().empty()) {
179 AssertingVH<const GlobalValue> &V =
180 EEState.getGlobalAddressReverseMap()[Addr];
181 assert((!V || !GV) && "GlobalMapping already established!");
186 void ExecutionEngine::clearAllGlobalMappings() {
187 std::lock_guard<std::recursive_mutex> locked(lock);
189 EEState.getGlobalAddressMap().clear();
190 EEState.getGlobalAddressReverseMap().clear();
193 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
194 std::lock_guard<std::recursive_mutex> locked(lock);
196 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
197 EEState.RemoveMapping(FI);
198 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
200 EEState.RemoveMapping(GI);
203 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
204 std::lock_guard<std::recursive_mutex> locked(lock);
206 ExecutionEngineState::GlobalAddressMapTy &Map =
207 EEState.getGlobalAddressMap();
209 // Deleting from the mapping?
211 return EEState.RemoveMapping(GV);
213 void *&CurVal = Map[GV];
214 void *OldVal = CurVal;
216 if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
217 EEState.getGlobalAddressReverseMap().erase(CurVal);
220 // If we are using the reverse mapping, add it too.
221 if (!EEState.getGlobalAddressReverseMap().empty()) {
222 AssertingVH<const GlobalValue> &V =
223 EEState.getGlobalAddressReverseMap()[Addr];
224 assert((!V || !GV) && "GlobalMapping already established!");
230 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
231 std::lock_guard<std::recursive_mutex> locked(lock);
233 ExecutionEngineState::GlobalAddressMapTy::iterator I =
234 EEState.getGlobalAddressMap().find(GV);
235 return I != EEState.getGlobalAddressMap().end() ? I->second : nullptr;
238 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
239 std::lock_guard<std::recursive_mutex> locked(lock);
241 // If we haven't computed the reverse mapping yet, do so first.
242 if (EEState.getGlobalAddressReverseMap().empty()) {
243 for (ExecutionEngineState::GlobalAddressMapTy::iterator
244 I = EEState.getGlobalAddressMap().begin(),
245 E = EEState.getGlobalAddressMap().end(); I != E; ++I)
246 EEState.getGlobalAddressReverseMap().insert(std::make_pair(
247 I->second, I->first));
250 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
251 EEState.getGlobalAddressReverseMap().find(Addr);
252 return I != EEState.getGlobalAddressReverseMap().end() ? I->second : nullptr;
258 std::vector<char*> Values;
260 ArgvArray() : Array(nullptr) {}
261 ~ArgvArray() { clear(); }
265 for (size_t I = 0, E = Values.size(); I != E; ++I) {
270 /// Turn a vector of strings into a nice argv style array of pointers to null
271 /// terminated strings.
272 void *reset(LLVMContext &C, ExecutionEngine *EE,
273 const std::vector<std::string> &InputArgv);
275 } // anonymous namespace
276 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
277 const std::vector<std::string> &InputArgv) {
278 clear(); // Free the old contents.
279 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
280 Array = new char[(InputArgv.size()+1)*PtrSize];
282 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
283 Type *SBytePtr = Type::getInt8PtrTy(C);
285 for (unsigned i = 0; i != InputArgv.size(); ++i) {
286 unsigned Size = InputArgv[i].size()+1;
287 char *Dest = new char[Size];
288 Values.push_back(Dest);
289 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
291 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
294 // Endian safe: Array[i] = (PointerTy)Dest;
295 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
300 EE->StoreValueToMemory(PTOGV(nullptr),
301 (GenericValue*)(Array+InputArgv.size()*PtrSize),
306 void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
308 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
309 GlobalVariable *GV = module->getNamedGlobal(Name);
311 // If this global has internal linkage, or if it has a use, then it must be
312 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
313 // this is the case, don't execute any of the global ctors, __main will do
315 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
317 // Should be an array of '{ i32, void ()* }' structs. The first value is
318 // the init priority, which we ignore.
319 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
322 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
323 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
326 Constant *FP = CS->getOperand(1);
327 if (FP->isNullValue())
328 continue; // Found a sentinal value, ignore.
330 // Strip off constant expression casts.
331 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
333 FP = CE->getOperand(0);
335 // Execute the ctor/dtor function!
336 if (Function *F = dyn_cast<Function>(FP))
337 runFunction(F, std::vector<GenericValue>());
339 // FIXME: It is marginally lame that we just do nothing here if we see an
340 // entry we don't recognize. It might not be unreasonable for the verifier
341 // to not even allow this and just assert here.
345 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
346 // Execute global ctors/dtors for each module in the program.
347 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
348 runStaticConstructorsDestructors(Modules[i], isDtors);
352 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
353 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
354 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
355 for (unsigned i = 0; i < PtrSize; ++i)
356 if (*(i + (uint8_t*)Loc))
362 int ExecutionEngine::runFunctionAsMain(Function *Fn,
363 const std::vector<std::string> &argv,
364 const char * const * envp) {
365 std::vector<GenericValue> GVArgs;
367 GVArgc.IntVal = APInt(32, argv.size());
370 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
371 FunctionType *FTy = Fn->getFunctionType();
372 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
374 // Check the argument types.
376 report_fatal_error("Invalid number of arguments of main() supplied");
377 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
378 report_fatal_error("Invalid type for third argument of main() supplied");
379 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
380 report_fatal_error("Invalid type for second argument of main() supplied");
381 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
382 report_fatal_error("Invalid type for first argument of main() supplied");
383 if (!FTy->getReturnType()->isIntegerTy() &&
384 !FTy->getReturnType()->isVoidTy())
385 report_fatal_error("Invalid return type of main() supplied");
390 GVArgs.push_back(GVArgc); // Arg #0 = argc.
393 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
394 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
395 "argv[0] was null after CreateArgv");
397 std::vector<std::string> EnvVars;
398 for (unsigned i = 0; envp[i]; ++i)
399 EnvVars.push_back(envp[i]);
401 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
406 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
409 ExecutionEngine *ExecutionEngine::create(Module *M,
410 bool ForceInterpreter,
411 std::string *ErrorStr,
412 CodeGenOpt::Level OptLevel,
414 EngineBuilder EB = EngineBuilder(M)
415 .setEngineKind(ForceInterpreter
416 ? EngineKind::Interpreter
418 .setErrorStr(ErrorStr)
419 .setOptLevel(OptLevel)
420 .setAllocateGVsWithCode(GVsWithCode);
425 /// createJIT - This is the factory method for creating a JIT for the current
426 /// machine, it does not fall back to the interpreter. This takes ownership
428 ExecutionEngine *ExecutionEngine::createJIT(Module *M,
429 std::string *ErrorStr,
430 JITMemoryManager *JMM,
431 CodeGenOpt::Level OL,
434 CodeModel::Model CMM) {
435 if (!ExecutionEngine::JITCtor) {
437 *ErrorStr = "JIT has not been linked in.";
441 // Use the defaults for extra parameters. Users can use EngineBuilder to
444 EB.setEngineKind(EngineKind::JIT);
445 EB.setErrorStr(ErrorStr);
446 EB.setRelocationModel(RM);
447 EB.setCodeModel(CMM);
448 EB.setAllocateGVsWithCode(GVsWithCode);
450 EB.setJITMemoryManager(JMM);
452 // TODO: permit custom TargetOptions here
453 TargetMachine *TM = EB.selectTarget();
454 if (!TM || (ErrorStr && ErrorStr->length() > 0)) return nullptr;
456 return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
459 void EngineBuilder::InitEngine() {
460 WhichEngine = EngineKind::Either;
462 OptLevel = CodeGenOpt::Default;
465 Options = TargetOptions();
466 AllocateGVsWithCode = false;
467 RelocModel = Reloc::Default;
468 CMModel = CodeModel::JITDefault;
471 // IR module verification is enabled by default in debug builds, and disabled
472 // by default in release builds.
474 VerifyModules = true;
476 VerifyModules = false;
480 ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
481 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
483 // Make sure we can resolve symbols in the program as well. The zero arg
484 // to the function tells DynamicLibrary to load the program, not a library.
485 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
488 assert(!(JMM && MCJMM));
490 // If the user specified a memory manager but didn't specify which engine to
491 // create, we assume they only want the JIT, and we fail if they only want
494 if (WhichEngine & EngineKind::JIT)
495 WhichEngine = EngineKind::JIT;
498 *ErrorStr = "Cannot create an interpreter with a memory manager.";
503 if (MCJMM && ! UseMCJIT) {
506 "Cannot create a legacy JIT with a runtime dyld memory "
511 // Unless the interpreter was explicitly selected or the JIT is not linked,
513 if ((WhichEngine & EngineKind::JIT) && TheTM) {
514 Triple TT(M->getTargetTriple());
515 if (!TM->getTarget().hasJIT()) {
516 errs() << "WARNING: This target JIT is not designed for the host"
517 << " you are running. If bad things happen, please choose"
518 << " a different -march switch.\n";
521 ExecutionEngine *EE = nullptr;
522 if (UseMCJIT && ExecutionEngine::MCJITCtor)
523 EE = ExecutionEngine::MCJITCtor(M, ErrorStr, MCJMM ? MCJMM : JMM,
524 AllocateGVsWithCode, TheTM.release());
525 else if (ExecutionEngine::JITCtor)
526 EE = ExecutionEngine::JITCtor(M, ErrorStr, JMM,
527 AllocateGVsWithCode, TheTM.release());
530 EE->setVerifyModules(VerifyModules);
535 // If we can't make a JIT and we didn't request one specifically, try making
536 // an interpreter instead.
537 if (WhichEngine & EngineKind::Interpreter) {
538 if (ExecutionEngine::InterpCtor)
539 return ExecutionEngine::InterpCtor(M, ErrorStr);
541 *ErrorStr = "Interpreter has not been linked in.";
545 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::JITCtor &&
546 !ExecutionEngine::MCJITCtor) {
548 *ErrorStr = "JIT has not been linked in.";
554 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
555 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
556 return getPointerToFunction(F);
558 std::lock_guard<std::recursive_mutex> locked(lock);
559 if (void *P = EEState.getGlobalAddressMap()[GV])
562 // Global variable might have been added since interpreter started.
563 if (GlobalVariable *GVar =
564 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
565 EmitGlobalVariable(GVar);
567 llvm_unreachable("Global hasn't had an address allocated yet!");
569 return EEState.getGlobalAddressMap()[GV];
572 /// \brief Converts a Constant* into a GenericValue, including handling of
573 /// ConstantExpr values.
574 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
575 // If its undefined, return the garbage.
576 if (isa<UndefValue>(C)) {
578 switch (C->getType()->getTypeID()) {
581 case Type::IntegerTyID:
582 case Type::X86_FP80TyID:
583 case Type::FP128TyID:
584 case Type::PPC_FP128TyID:
585 // Although the value is undefined, we still have to construct an APInt
586 // with the correct bit width.
587 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
589 case Type::StructTyID: {
590 // if the whole struct is 'undef' just reserve memory for the value.
591 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
592 unsigned int elemNum = STy->getNumElements();
593 Result.AggregateVal.resize(elemNum);
594 for (unsigned int i = 0; i < elemNum; ++i) {
595 Type *ElemTy = STy->getElementType(i);
596 if (ElemTy->isIntegerTy())
597 Result.AggregateVal[i].IntVal =
598 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
599 else if (ElemTy->isAggregateType()) {
600 const Constant *ElemUndef = UndefValue::get(ElemTy);
601 Result.AggregateVal[i] = getConstantValue(ElemUndef);
607 case Type::VectorTyID:
608 // if the whole vector is 'undef' just reserve memory for the value.
609 const VectorType* VTy = dyn_cast<VectorType>(C->getType());
610 const Type *ElemTy = VTy->getElementType();
611 unsigned int elemNum = VTy->getNumElements();
612 Result.AggregateVal.resize(elemNum);
613 if (ElemTy->isIntegerTy())
614 for (unsigned int i = 0; i < elemNum; ++i)
615 Result.AggregateVal[i].IntVal =
616 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
622 // Otherwise, if the value is a ConstantExpr...
623 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
624 Constant *Op0 = CE->getOperand(0);
625 switch (CE->getOpcode()) {
626 case Instruction::GetElementPtr: {
628 GenericValue Result = getConstantValue(Op0);
629 APInt Offset(DL->getPointerSizeInBits(), 0);
630 cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset);
632 char* tmp = (char*) Result.PointerVal;
633 Result = PTOGV(tmp + Offset.getSExtValue());
636 case Instruction::Trunc: {
637 GenericValue GV = getConstantValue(Op0);
638 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
639 GV.IntVal = GV.IntVal.trunc(BitWidth);
642 case Instruction::ZExt: {
643 GenericValue GV = getConstantValue(Op0);
644 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
645 GV.IntVal = GV.IntVal.zext(BitWidth);
648 case Instruction::SExt: {
649 GenericValue GV = getConstantValue(Op0);
650 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
651 GV.IntVal = GV.IntVal.sext(BitWidth);
654 case Instruction::FPTrunc: {
656 GenericValue GV = getConstantValue(Op0);
657 GV.FloatVal = float(GV.DoubleVal);
660 case Instruction::FPExt:{
662 GenericValue GV = getConstantValue(Op0);
663 GV.DoubleVal = double(GV.FloatVal);
666 case Instruction::UIToFP: {
667 GenericValue GV = getConstantValue(Op0);
668 if (CE->getType()->isFloatTy())
669 GV.FloatVal = float(GV.IntVal.roundToDouble());
670 else if (CE->getType()->isDoubleTy())
671 GV.DoubleVal = GV.IntVal.roundToDouble();
672 else if (CE->getType()->isX86_FP80Ty()) {
673 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
674 (void)apf.convertFromAPInt(GV.IntVal,
676 APFloat::rmNearestTiesToEven);
677 GV.IntVal = apf.bitcastToAPInt();
681 case Instruction::SIToFP: {
682 GenericValue GV = getConstantValue(Op0);
683 if (CE->getType()->isFloatTy())
684 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
685 else if (CE->getType()->isDoubleTy())
686 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
687 else if (CE->getType()->isX86_FP80Ty()) {
688 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
689 (void)apf.convertFromAPInt(GV.IntVal,
691 APFloat::rmNearestTiesToEven);
692 GV.IntVal = apf.bitcastToAPInt();
696 case Instruction::FPToUI: // double->APInt conversion handles sign
697 case Instruction::FPToSI: {
698 GenericValue GV = getConstantValue(Op0);
699 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
700 if (Op0->getType()->isFloatTy())
701 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
702 else if (Op0->getType()->isDoubleTy())
703 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
704 else if (Op0->getType()->isX86_FP80Ty()) {
705 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
708 (void)apf.convertToInteger(&v, BitWidth,
709 CE->getOpcode()==Instruction::FPToSI,
710 APFloat::rmTowardZero, &ignored);
711 GV.IntVal = v; // endian?
715 case Instruction::PtrToInt: {
716 GenericValue GV = getConstantValue(Op0);
717 uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType());
718 assert(PtrWidth <= 64 && "Bad pointer width");
719 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
720 uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType());
721 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
724 case Instruction::IntToPtr: {
725 GenericValue GV = getConstantValue(Op0);
726 uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType());
727 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
728 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
729 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
732 case Instruction::BitCast: {
733 GenericValue GV = getConstantValue(Op0);
734 Type* DestTy = CE->getType();
735 switch (Op0->getType()->getTypeID()) {
736 default: llvm_unreachable("Invalid bitcast operand");
737 case Type::IntegerTyID:
738 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
739 if (DestTy->isFloatTy())
740 GV.FloatVal = GV.IntVal.bitsToFloat();
741 else if (DestTy->isDoubleTy())
742 GV.DoubleVal = GV.IntVal.bitsToDouble();
744 case Type::FloatTyID:
745 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
746 GV.IntVal = APInt::floatToBits(GV.FloatVal);
748 case Type::DoubleTyID:
749 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
750 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
752 case Type::PointerTyID:
753 assert(DestTy->isPointerTy() && "Invalid bitcast");
754 break; // getConstantValue(Op0) above already converted it
758 case Instruction::Add:
759 case Instruction::FAdd:
760 case Instruction::Sub:
761 case Instruction::FSub:
762 case Instruction::Mul:
763 case Instruction::FMul:
764 case Instruction::UDiv:
765 case Instruction::SDiv:
766 case Instruction::URem:
767 case Instruction::SRem:
768 case Instruction::And:
769 case Instruction::Or:
770 case Instruction::Xor: {
771 GenericValue LHS = getConstantValue(Op0);
772 GenericValue RHS = getConstantValue(CE->getOperand(1));
774 switch (CE->getOperand(0)->getType()->getTypeID()) {
775 default: llvm_unreachable("Bad add type!");
776 case Type::IntegerTyID:
777 switch (CE->getOpcode()) {
778 default: llvm_unreachable("Invalid integer opcode");
779 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
780 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
781 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
782 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
783 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
784 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
785 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
786 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
787 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
788 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
791 case Type::FloatTyID:
792 switch (CE->getOpcode()) {
793 default: llvm_unreachable("Invalid float opcode");
794 case Instruction::FAdd:
795 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
796 case Instruction::FSub:
797 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
798 case Instruction::FMul:
799 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
800 case Instruction::FDiv:
801 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
802 case Instruction::FRem:
803 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
806 case Type::DoubleTyID:
807 switch (CE->getOpcode()) {
808 default: llvm_unreachable("Invalid double opcode");
809 case Instruction::FAdd:
810 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
811 case Instruction::FSub:
812 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
813 case Instruction::FMul:
814 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
815 case Instruction::FDiv:
816 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
817 case Instruction::FRem:
818 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
821 case Type::X86_FP80TyID:
822 case Type::PPC_FP128TyID:
823 case Type::FP128TyID: {
824 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
825 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
826 switch (CE->getOpcode()) {
827 default: llvm_unreachable("Invalid long double opcode");
828 case Instruction::FAdd:
829 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
830 GV.IntVal = apfLHS.bitcastToAPInt();
832 case Instruction::FSub:
833 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
834 APFloat::rmNearestTiesToEven);
835 GV.IntVal = apfLHS.bitcastToAPInt();
837 case Instruction::FMul:
838 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
839 APFloat::rmNearestTiesToEven);
840 GV.IntVal = apfLHS.bitcastToAPInt();
842 case Instruction::FDiv:
843 apfLHS.divide(APFloat(Sem, RHS.IntVal),
844 APFloat::rmNearestTiesToEven);
845 GV.IntVal = apfLHS.bitcastToAPInt();
847 case Instruction::FRem:
848 apfLHS.mod(APFloat(Sem, RHS.IntVal),
849 APFloat::rmNearestTiesToEven);
850 GV.IntVal = apfLHS.bitcastToAPInt();
862 SmallString<256> Msg;
863 raw_svector_ostream OS(Msg);
864 OS << "ConstantExpr not handled: " << *CE;
865 report_fatal_error(OS.str());
868 // Otherwise, we have a simple constant.
870 switch (C->getType()->getTypeID()) {
871 case Type::FloatTyID:
872 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
874 case Type::DoubleTyID:
875 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
877 case Type::X86_FP80TyID:
878 case Type::FP128TyID:
879 case Type::PPC_FP128TyID:
880 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
882 case Type::IntegerTyID:
883 Result.IntVal = cast<ConstantInt>(C)->getValue();
885 case Type::PointerTyID:
886 if (isa<ConstantPointerNull>(C))
887 Result.PointerVal = nullptr;
888 else if (const Function *F = dyn_cast<Function>(C))
889 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
890 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
891 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
892 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
893 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
894 BA->getBasicBlock())));
896 llvm_unreachable("Unknown constant pointer type!");
898 case Type::VectorTyID: {
901 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
902 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
903 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
906 elemNum = CDV->getNumElements();
907 ElemTy = CDV->getElementType();
908 } else if (CV || CAZ) {
909 VectorType* VTy = dyn_cast<VectorType>(C->getType());
910 elemNum = VTy->getNumElements();
911 ElemTy = VTy->getElementType();
913 llvm_unreachable("Unknown constant vector type!");
916 Result.AggregateVal.resize(elemNum);
917 // Check if vector holds floats.
918 if(ElemTy->isFloatTy()) {
920 GenericValue floatZero;
921 floatZero.FloatVal = 0.f;
922 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
927 for (unsigned i = 0; i < elemNum; ++i)
928 if (!isa<UndefValue>(CV->getOperand(i)))
929 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
930 CV->getOperand(i))->getValueAPF().convertToFloat();
934 for (unsigned i = 0; i < elemNum; ++i)
935 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
939 // Check if vector holds doubles.
940 if (ElemTy->isDoubleTy()) {
942 GenericValue doubleZero;
943 doubleZero.DoubleVal = 0.0;
944 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
949 for (unsigned i = 0; i < elemNum; ++i)
950 if (!isa<UndefValue>(CV->getOperand(i)))
951 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
952 CV->getOperand(i))->getValueAPF().convertToDouble();
956 for (unsigned i = 0; i < elemNum; ++i)
957 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
961 // Check if vector holds integers.
962 if (ElemTy->isIntegerTy()) {
964 GenericValue intZero;
965 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
966 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
971 for (unsigned i = 0; i < elemNum; ++i)
972 if (!isa<UndefValue>(CV->getOperand(i)))
973 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
974 CV->getOperand(i))->getValue();
976 Result.AggregateVal[i].IntVal =
977 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
982 for (unsigned i = 0; i < elemNum; ++i)
983 Result.AggregateVal[i].IntVal = APInt(
984 CDV->getElementType()->getPrimitiveSizeInBits(),
985 CDV->getElementAsInteger(i));
989 llvm_unreachable("Unknown constant pointer type!");
994 SmallString<256> Msg;
995 raw_svector_ostream OS(Msg);
996 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
997 report_fatal_error(OS.str());
1003 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
1004 /// with the integer held in IntVal.
1005 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
1006 unsigned StoreBytes) {
1007 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
1008 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
1010 if (sys::IsLittleEndianHost) {
1011 // Little-endian host - the source is ordered from LSB to MSB. Order the
1012 // destination from LSB to MSB: Do a straight copy.
1013 memcpy(Dst, Src, StoreBytes);
1015 // Big-endian host - the source is an array of 64 bit words ordered from
1016 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
1017 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
1018 while (StoreBytes > sizeof(uint64_t)) {
1019 StoreBytes -= sizeof(uint64_t);
1020 // May not be aligned so use memcpy.
1021 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
1022 Src += sizeof(uint64_t);
1025 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1029 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
1030 GenericValue *Ptr, Type *Ty) {
1031 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
1033 switch (Ty->getTypeID()) {
1035 dbgs() << "Cannot store value of type " << *Ty << "!\n";
1037 case Type::IntegerTyID:
1038 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
1040 case Type::FloatTyID:
1041 *((float*)Ptr) = Val.FloatVal;
1043 case Type::DoubleTyID:
1044 *((double*)Ptr) = Val.DoubleVal;
1046 case Type::X86_FP80TyID:
1047 memcpy(Ptr, Val.IntVal.getRawData(), 10);
1049 case Type::PointerTyID:
1050 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1051 if (StoreBytes != sizeof(PointerTy))
1052 memset(&(Ptr->PointerVal), 0, StoreBytes);
1054 *((PointerTy*)Ptr) = Val.PointerVal;
1056 case Type::VectorTyID:
1057 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1058 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1059 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1060 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1061 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1062 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1063 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1064 StoreIntToMemory(Val.AggregateVal[i].IntVal,
1065 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1071 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
1072 // Host and target are different endian - reverse the stored bytes.
1073 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1076 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1077 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1078 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1079 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
1080 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1081 const_cast<uint64_t *>(IntVal.getRawData()));
1083 if (sys::IsLittleEndianHost)
1084 // Little-endian host - the destination must be ordered from LSB to MSB.
1085 // The source is ordered from LSB to MSB: Do a straight copy.
1086 memcpy(Dst, Src, LoadBytes);
1088 // Big-endian - the destination is an array of 64 bit words ordered from
1089 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1090 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1092 while (LoadBytes > sizeof(uint64_t)) {
1093 LoadBytes -= sizeof(uint64_t);
1094 // May not be aligned so use memcpy.
1095 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1096 Dst += sizeof(uint64_t);
1099 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1105 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
1108 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
1110 switch (Ty->getTypeID()) {
1111 case Type::IntegerTyID:
1112 // An APInt with all words initially zero.
1113 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1114 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1116 case Type::FloatTyID:
1117 Result.FloatVal = *((float*)Ptr);
1119 case Type::DoubleTyID:
1120 Result.DoubleVal = *((double*)Ptr);
1122 case Type::PointerTyID:
1123 Result.PointerVal = *((PointerTy*)Ptr);
1125 case Type::X86_FP80TyID: {
1126 // This is endian dependent, but it will only work on x86 anyway.
1127 // FIXME: Will not trap if loading a signaling NaN.
1130 Result.IntVal = APInt(80, y);
1133 case Type::VectorTyID: {
1134 const VectorType *VT = cast<VectorType>(Ty);
1135 const Type *ElemT = VT->getElementType();
1136 const unsigned numElems = VT->getNumElements();
1137 if (ElemT->isFloatTy()) {
1138 Result.AggregateVal.resize(numElems);
1139 for (unsigned i = 0; i < numElems; ++i)
1140 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1142 if (ElemT->isDoubleTy()) {
1143 Result.AggregateVal.resize(numElems);
1144 for (unsigned i = 0; i < numElems; ++i)
1145 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1147 if (ElemT->isIntegerTy()) {
1148 GenericValue intZero;
1149 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1150 intZero.IntVal = APInt(elemBitWidth, 0);
1151 Result.AggregateVal.resize(numElems, intZero);
1152 for (unsigned i = 0; i < numElems; ++i)
1153 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1154 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1159 SmallString<256> Msg;
1160 raw_svector_ostream OS(Msg);
1161 OS << "Cannot load value of type " << *Ty << "!";
1162 report_fatal_error(OS.str());
1166 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
1167 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
1168 DEBUG(Init->dump());
1169 if (isa<UndefValue>(Init))
1172 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
1173 unsigned ElementSize =
1174 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
1175 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1176 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1180 if (isa<ConstantAggregateZero>(Init)) {
1181 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
1185 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
1186 unsigned ElementSize =
1187 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
1188 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1189 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1193 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
1194 const StructLayout *SL =
1195 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
1196 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1197 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1201 if (const ConstantDataSequential *CDS =
1202 dyn_cast<ConstantDataSequential>(Init)) {
1203 // CDS is already laid out in host memory order.
1204 StringRef Data = CDS->getRawDataValues();
1205 memcpy(Addr, Data.data(), Data.size());
1209 if (Init->getType()->isFirstClassType()) {
1210 GenericValue Val = getConstantValue(Init);
1211 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1215 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1216 llvm_unreachable("Unknown constant type to initialize memory with!");
1219 /// EmitGlobals - Emit all of the global variables to memory, storing their
1220 /// addresses into GlobalAddress. This must make sure to copy the contents of
1221 /// their initializers into the memory.
1222 void ExecutionEngine::emitGlobals() {
1223 // Loop over all of the global variables in the program, allocating the memory
1224 // to hold them. If there is more than one module, do a prepass over globals
1225 // to figure out how the different modules should link together.
1226 std::map<std::pair<std::string, Type*>,
1227 const GlobalValue*> LinkedGlobalsMap;
1229 if (Modules.size() != 1) {
1230 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1231 Module &M = *Modules[m];
1232 for (const auto &GV : M.globals()) {
1233 if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1234 GV.hasAppendingLinkage() || !GV.hasName())
1235 continue;// Ignore external globals and globals with internal linkage.
1237 const GlobalValue *&GVEntry =
1238 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
1240 // If this is the first time we've seen this global, it is the canonical
1247 // If the existing global is strong, never replace it.
1248 if (GVEntry->hasExternalLinkage())
1251 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1252 // symbol. FIXME is this right for common?
1253 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1259 std::vector<const GlobalValue*> NonCanonicalGlobals;
1260 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1261 Module &M = *Modules[m];
1262 for (const auto &GV : M.globals()) {
1263 // In the multi-module case, see what this global maps to.
1264 if (!LinkedGlobalsMap.empty()) {
1265 if (const GlobalValue *GVEntry =
1266 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
1267 // If something else is the canonical global, ignore this one.
1268 if (GVEntry != &GV) {
1269 NonCanonicalGlobals.push_back(&GV);
1275 if (!GV.isDeclaration()) {
1276 addGlobalMapping(&GV, getMemoryForGV(&GV));
1278 // External variable reference. Try to use the dynamic loader to
1279 // get a pointer to it.
1281 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1282 addGlobalMapping(&GV, SymAddr);
1284 report_fatal_error("Could not resolve external global address: "
1290 // If there are multiple modules, map the non-canonical globals to their
1291 // canonical location.
1292 if (!NonCanonicalGlobals.empty()) {
1293 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1294 const GlobalValue *GV = NonCanonicalGlobals[i];
1295 const GlobalValue *CGV =
1296 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1297 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1298 assert(Ptr && "Canonical global wasn't codegen'd!");
1299 addGlobalMapping(GV, Ptr);
1303 // Now that all of the globals are set up in memory, loop through them all
1304 // and initialize their contents.
1305 for (const auto &GV : M.globals()) {
1306 if (!GV.isDeclaration()) {
1307 if (!LinkedGlobalsMap.empty()) {
1308 if (const GlobalValue *GVEntry =
1309 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1310 if (GVEntry != &GV) // Not the canonical variable.
1313 EmitGlobalVariable(&GV);
1319 // EmitGlobalVariable - This method emits the specified global variable to the
1320 // address specified in GlobalAddresses, or allocates new memory if it's not
1321 // already in the map.
1322 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1323 void *GA = getPointerToGlobalIfAvailable(GV);
1326 // If it's not already specified, allocate memory for the global.
1327 GA = getMemoryForGV(GV);
1329 // If we failed to allocate memory for this global, return.
1332 addGlobalMapping(GV, GA);
1335 // Don't initialize if it's thread local, let the client do it.
1336 if (!GV->isThreadLocal())
1337 InitializeMemory(GV->getInitializer(), GA);
1339 Type *ElTy = GV->getType()->getElementType();
1340 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
1341 NumInitBytes += (unsigned)GVSize;
1345 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1346 : EE(EE), GlobalAddressMap(this) {
1349 std::recursive_mutex *
1350 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1351 return &EES->EE.lock;
1354 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1355 const GlobalValue *Old) {
1356 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1357 EES->GlobalAddressReverseMap.erase(OldVal);
1360 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1361 const GlobalValue *,
1362 const GlobalValue *) {
1363 llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1364 " RAUW on a value it has a global mapping for.");