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 #define DEBUG_TYPE "jit"
16 #include "llvm/ExecutionEngine/ExecutionEngine.h"
17 #include "llvm/ExecutionEngine/JITMemoryManager.h"
18 #include "llvm/ExecutionEngine/ObjectCache.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ExecutionEngine/GenericValue.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/DynamicLibrary.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/MutexGuard.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Support/ValueHandle.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetMachine.h"
40 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
41 STATISTIC(NumGlobals , "Number of global vars initialized");
43 // pin vtable to this file
44 void ObjectCache::anchor() {}
46 ExecutionEngine *(*ExecutionEngine::JITCtor)(
48 std::string *ErrorStr,
49 JITMemoryManager *JMM,
51 TargetMachine *TM) = 0;
52 ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
54 std::string *ErrorStr,
55 RTDyldMemoryManager *MCJMM,
57 TargetMachine *TM) = 0;
58 ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
59 std::string *ErrorStr) = 0;
61 ExecutionEngine::ExecutionEngine(Module *M)
63 LazyFunctionCreator(0) {
64 CompilingLazily = false;
65 GVCompilationDisabled = false;
66 SymbolSearchingDisabled = false;
68 assert(M && "Module is null?");
71 ExecutionEngine::~ExecutionEngine() {
72 clearAllGlobalMappings();
73 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
78 /// \brief Helper class which uses a value handler to automatically deletes the
79 /// memory block when the GlobalVariable is destroyed.
80 class GVMemoryBlock : public CallbackVH {
81 GVMemoryBlock(const GlobalVariable *GV)
82 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
85 /// \brief Returns the address the GlobalVariable should be written into. The
86 /// GVMemoryBlock object prefixes that.
87 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
88 Type *ElTy = GV->getType()->getElementType();
89 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
90 void *RawMemory = ::operator new(
91 DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock),
92 TD.getPreferredAlignment(GV))
94 new(RawMemory) GVMemoryBlock(GV);
95 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
98 virtual void deleted() {
99 // We allocated with operator new and with some extra memory hanging off the
100 // end, so don't just delete this. I'm not sure if this is actually
102 this->~GVMemoryBlock();
103 ::operator delete(this);
106 } // anonymous namespace
108 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
109 return GVMemoryBlock::Create(GV, *getDataLayout());
112 bool ExecutionEngine::removeModule(Module *M) {
113 for(SmallVectorImpl<Module *>::iterator I = Modules.begin(),
114 E = Modules.end(); I != E; ++I) {
118 clearGlobalMappingsFromModule(M);
125 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
126 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
127 if (Function *F = Modules[i]->getFunction(FnName))
134 void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
135 const GlobalValue *ToUnmap) {
136 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
139 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
141 if (I == GlobalAddressMap.end())
145 GlobalAddressMap.erase(I);
148 GlobalAddressReverseMap.erase(OldVal);
152 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
153 MutexGuard locked(lock);
155 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
156 << "\' to [" << Addr << "]\n";);
157 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
158 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
161 // If we are using the reverse mapping, add it too.
162 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
163 AssertingVH<const GlobalValue> &V =
164 EEState.getGlobalAddressReverseMap(locked)[Addr];
165 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
170 void ExecutionEngine::clearAllGlobalMappings() {
171 MutexGuard locked(lock);
173 EEState.getGlobalAddressMap(locked).clear();
174 EEState.getGlobalAddressReverseMap(locked).clear();
177 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
178 MutexGuard locked(lock);
180 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
181 EEState.RemoveMapping(locked, FI);
182 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
184 EEState.RemoveMapping(locked, GI);
187 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
188 MutexGuard locked(lock);
190 ExecutionEngineState::GlobalAddressMapTy &Map =
191 EEState.getGlobalAddressMap(locked);
193 // Deleting from the mapping?
195 return EEState.RemoveMapping(locked, GV);
197 void *&CurVal = Map[GV];
198 void *OldVal = CurVal;
200 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
201 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
204 // If we are using the reverse mapping, add it too.
205 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
206 AssertingVH<const GlobalValue> &V =
207 EEState.getGlobalAddressReverseMap(locked)[Addr];
208 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
214 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
215 MutexGuard locked(lock);
217 ExecutionEngineState::GlobalAddressMapTy::iterator I =
218 EEState.getGlobalAddressMap(locked).find(GV);
219 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
222 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
223 MutexGuard locked(lock);
225 // If we haven't computed the reverse mapping yet, do so first.
226 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
227 for (ExecutionEngineState::GlobalAddressMapTy::iterator
228 I = EEState.getGlobalAddressMap(locked).begin(),
229 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
230 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
231 I->second, I->first));
234 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
235 EEState.getGlobalAddressReverseMap(locked).find(Addr);
236 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
242 std::vector<char*> Values;
244 ArgvArray() : Array(NULL) {}
245 ~ArgvArray() { clear(); }
249 for (size_t I = 0, E = Values.size(); I != E; ++I) {
254 /// Turn a vector of strings into a nice argv style array of pointers to null
255 /// terminated strings.
256 void *reset(LLVMContext &C, ExecutionEngine *EE,
257 const std::vector<std::string> &InputArgv);
259 } // anonymous namespace
260 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
261 const std::vector<std::string> &InputArgv) {
262 clear(); // Free the old contents.
263 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
264 Array = new char[(InputArgv.size()+1)*PtrSize];
266 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
267 Type *SBytePtr = Type::getInt8PtrTy(C);
269 for (unsigned i = 0; i != InputArgv.size(); ++i) {
270 unsigned Size = InputArgv[i].size()+1;
271 char *Dest = new char[Size];
272 Values.push_back(Dest);
273 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
275 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
278 // Endian safe: Array[i] = (PointerTy)Dest;
279 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
284 EE->StoreValueToMemory(PTOGV(0),
285 (GenericValue*)(Array+InputArgv.size()*PtrSize),
290 void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
292 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
293 GlobalVariable *GV = module->getNamedGlobal(Name);
295 // If this global has internal linkage, or if it has a use, then it must be
296 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
297 // this is the case, don't execute any of the global ctors, __main will do
299 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
301 // Should be an array of '{ i32, void ()* }' structs. The first value is
302 // the init priority, which we ignore.
303 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
306 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
307 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
308 if (CS == 0) continue;
310 Constant *FP = CS->getOperand(1);
311 if (FP->isNullValue())
312 continue; // Found a sentinal value, ignore.
314 // Strip off constant expression casts.
315 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
317 FP = CE->getOperand(0);
319 // Execute the ctor/dtor function!
320 if (Function *F = dyn_cast<Function>(FP))
321 runFunction(F, std::vector<GenericValue>());
323 // FIXME: It is marginally lame that we just do nothing here if we see an
324 // entry we don't recognize. It might not be unreasonable for the verifier
325 // to not even allow this and just assert here.
329 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
330 // Execute global ctors/dtors for each module in the program.
331 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
332 runStaticConstructorsDestructors(Modules[i], isDtors);
336 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
337 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
338 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
339 for (unsigned i = 0; i < PtrSize; ++i)
340 if (*(i + (uint8_t*)Loc))
346 int ExecutionEngine::runFunctionAsMain(Function *Fn,
347 const std::vector<std::string> &argv,
348 const char * const * envp) {
349 std::vector<GenericValue> GVArgs;
351 GVArgc.IntVal = APInt(32, argv.size());
354 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
355 FunctionType *FTy = Fn->getFunctionType();
356 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
358 // Check the argument types.
360 report_fatal_error("Invalid number of arguments of main() supplied");
361 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
362 report_fatal_error("Invalid type for third argument of main() supplied");
363 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
364 report_fatal_error("Invalid type for second argument of main() supplied");
365 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
366 report_fatal_error("Invalid type for first argument of main() supplied");
367 if (!FTy->getReturnType()->isIntegerTy() &&
368 !FTy->getReturnType()->isVoidTy())
369 report_fatal_error("Invalid return type of main() supplied");
374 GVArgs.push_back(GVArgc); // Arg #0 = argc.
377 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
378 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
379 "argv[0] was null after CreateArgv");
381 std::vector<std::string> EnvVars;
382 for (unsigned i = 0; envp[i]; ++i)
383 EnvVars.push_back(envp[i]);
385 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
390 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
393 ExecutionEngine *ExecutionEngine::create(Module *M,
394 bool ForceInterpreter,
395 std::string *ErrorStr,
396 CodeGenOpt::Level OptLevel,
398 EngineBuilder EB = EngineBuilder(M)
399 .setEngineKind(ForceInterpreter
400 ? EngineKind::Interpreter
402 .setErrorStr(ErrorStr)
403 .setOptLevel(OptLevel)
404 .setAllocateGVsWithCode(GVsWithCode);
409 /// createJIT - This is the factory method for creating a JIT for the current
410 /// machine, it does not fall back to the interpreter. This takes ownership
412 ExecutionEngine *ExecutionEngine::createJIT(Module *M,
413 std::string *ErrorStr,
414 JITMemoryManager *JMM,
415 CodeGenOpt::Level OL,
418 CodeModel::Model CMM) {
419 if (ExecutionEngine::JITCtor == 0) {
421 *ErrorStr = "JIT has not been linked in.";
425 // Use the defaults for extra parameters. Users can use EngineBuilder to
428 EB.setEngineKind(EngineKind::JIT);
429 EB.setErrorStr(ErrorStr);
430 EB.setRelocationModel(RM);
431 EB.setCodeModel(CMM);
432 EB.setAllocateGVsWithCode(GVsWithCode);
434 EB.setJITMemoryManager(JMM);
436 // TODO: permit custom TargetOptions here
437 TargetMachine *TM = EB.selectTarget();
438 if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
440 return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
443 ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
444 OwningPtr<TargetMachine> TheTM(TM); // Take ownership.
446 // Make sure we can resolve symbols in the program as well. The zero arg
447 // to the function tells DynamicLibrary to load the program, not a library.
448 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
451 assert(!(JMM && MCJMM));
453 // If the user specified a memory manager but didn't specify which engine to
454 // create, we assume they only want the JIT, and we fail if they only want
457 if (WhichEngine & EngineKind::JIT)
458 WhichEngine = EngineKind::JIT;
461 *ErrorStr = "Cannot create an interpreter with a memory manager.";
466 if (MCJMM && ! UseMCJIT) {
469 "Cannot create a legacy JIT with a runtime dyld memory "
474 // Unless the interpreter was explicitly selected or the JIT is not linked,
476 if ((WhichEngine & EngineKind::JIT) && TheTM) {
477 Triple TT(M->getTargetTriple());
478 if (!TM->getTarget().hasJIT()) {
479 errs() << "WARNING: This target JIT is not designed for the host"
480 << " you are running. If bad things happen, please choose"
481 << " a different -march switch.\n";
484 if (UseMCJIT && ExecutionEngine::MCJITCtor) {
485 ExecutionEngine *EE =
486 ExecutionEngine::MCJITCtor(M, ErrorStr, MCJMM ? MCJMM : JMM,
487 AllocateGVsWithCode, TheTM.take());
489 } else if (ExecutionEngine::JITCtor) {
490 ExecutionEngine *EE =
491 ExecutionEngine::JITCtor(M, ErrorStr, JMM,
492 AllocateGVsWithCode, TheTM.take());
497 // If we can't make a JIT and we didn't request one specifically, try making
498 // an interpreter instead.
499 if (WhichEngine & EngineKind::Interpreter) {
500 if (ExecutionEngine::InterpCtor)
501 return ExecutionEngine::InterpCtor(M, ErrorStr);
503 *ErrorStr = "Interpreter has not been linked in.";
507 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0 &&
508 ExecutionEngine::MCJITCtor == 0) {
510 *ErrorStr = "JIT has not been linked in.";
516 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
517 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
518 return getPointerToFunction(F);
520 MutexGuard locked(lock);
521 if (void *P = EEState.getGlobalAddressMap(locked)[GV])
524 // Global variable might have been added since interpreter started.
525 if (GlobalVariable *GVar =
526 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
527 EmitGlobalVariable(GVar);
529 llvm_unreachable("Global hasn't had an address allocated yet!");
531 return EEState.getGlobalAddressMap(locked)[GV];
534 /// \brief Converts a Constant* into a GenericValue, including handling of
535 /// ConstantExpr values.
536 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
537 // If its undefined, return the garbage.
538 if (isa<UndefValue>(C)) {
540 switch (C->getType()->getTypeID()) {
543 case Type::IntegerTyID:
544 case Type::X86_FP80TyID:
545 case Type::FP128TyID:
546 case Type::PPC_FP128TyID:
547 // Although the value is undefined, we still have to construct an APInt
548 // with the correct bit width.
549 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
551 case Type::StructTyID: {
552 // if the whole struct is 'undef' just reserve memory for the value.
553 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
554 unsigned int elemNum = STy->getNumElements();
555 Result.AggregateVal.resize(elemNum);
556 for (unsigned int i = 0; i < elemNum; ++i) {
557 Type *ElemTy = STy->getElementType(i);
558 if (ElemTy->isIntegerTy())
559 Result.AggregateVal[i].IntVal =
560 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
561 else if (ElemTy->isAggregateType()) {
562 const Constant *ElemUndef = UndefValue::get(ElemTy);
563 Result.AggregateVal[i] = getConstantValue(ElemUndef);
569 case Type::VectorTyID:
570 // if the whole vector is 'undef' just reserve memory for the value.
571 const VectorType* VTy = dyn_cast<VectorType>(C->getType());
572 const Type *ElemTy = VTy->getElementType();
573 unsigned int elemNum = VTy->getNumElements();
574 Result.AggregateVal.resize(elemNum);
575 if (ElemTy->isIntegerTy())
576 for (unsigned int i = 0; i < elemNum; ++i)
577 Result.AggregateVal[i].IntVal =
578 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
584 // Otherwise, if the value is a ConstantExpr...
585 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
586 Constant *Op0 = CE->getOperand(0);
587 switch (CE->getOpcode()) {
588 case Instruction::GetElementPtr: {
590 GenericValue Result = getConstantValue(Op0);
591 APInt Offset(TD->getPointerSizeInBits(), 0);
592 cast<GEPOperator>(CE)->accumulateConstantOffset(*TD, Offset);
594 char* tmp = (char*) Result.PointerVal;
595 Result = PTOGV(tmp + Offset.getSExtValue());
598 case Instruction::Trunc: {
599 GenericValue GV = getConstantValue(Op0);
600 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
601 GV.IntVal = GV.IntVal.trunc(BitWidth);
604 case Instruction::ZExt: {
605 GenericValue GV = getConstantValue(Op0);
606 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
607 GV.IntVal = GV.IntVal.zext(BitWidth);
610 case Instruction::SExt: {
611 GenericValue GV = getConstantValue(Op0);
612 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
613 GV.IntVal = GV.IntVal.sext(BitWidth);
616 case Instruction::FPTrunc: {
618 GenericValue GV = getConstantValue(Op0);
619 GV.FloatVal = float(GV.DoubleVal);
622 case Instruction::FPExt:{
624 GenericValue GV = getConstantValue(Op0);
625 GV.DoubleVal = double(GV.FloatVal);
628 case Instruction::UIToFP: {
629 GenericValue GV = getConstantValue(Op0);
630 if (CE->getType()->isFloatTy())
631 GV.FloatVal = float(GV.IntVal.roundToDouble());
632 else if (CE->getType()->isDoubleTy())
633 GV.DoubleVal = GV.IntVal.roundToDouble();
634 else if (CE->getType()->isX86_FP80Ty()) {
635 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
636 (void)apf.convertFromAPInt(GV.IntVal,
638 APFloat::rmNearestTiesToEven);
639 GV.IntVal = apf.bitcastToAPInt();
643 case Instruction::SIToFP: {
644 GenericValue GV = getConstantValue(Op0);
645 if (CE->getType()->isFloatTy())
646 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
647 else if (CE->getType()->isDoubleTy())
648 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
649 else if (CE->getType()->isX86_FP80Ty()) {
650 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
651 (void)apf.convertFromAPInt(GV.IntVal,
653 APFloat::rmNearestTiesToEven);
654 GV.IntVal = apf.bitcastToAPInt();
658 case Instruction::FPToUI: // double->APInt conversion handles sign
659 case Instruction::FPToSI: {
660 GenericValue GV = getConstantValue(Op0);
661 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
662 if (Op0->getType()->isFloatTy())
663 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
664 else if (Op0->getType()->isDoubleTy())
665 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
666 else if (Op0->getType()->isX86_FP80Ty()) {
667 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
670 (void)apf.convertToInteger(&v, BitWidth,
671 CE->getOpcode()==Instruction::FPToSI,
672 APFloat::rmTowardZero, &ignored);
673 GV.IntVal = v; // endian?
677 case Instruction::PtrToInt: {
678 GenericValue GV = getConstantValue(Op0);
679 uint32_t PtrWidth = TD->getTypeSizeInBits(Op0->getType());
680 assert(PtrWidth <= 64 && "Bad pointer width");
681 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
682 uint32_t IntWidth = TD->getTypeSizeInBits(CE->getType());
683 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
686 case Instruction::IntToPtr: {
687 GenericValue GV = getConstantValue(Op0);
688 uint32_t PtrWidth = TD->getTypeSizeInBits(CE->getType());
689 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
690 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
691 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
694 case Instruction::BitCast: {
695 GenericValue GV = getConstantValue(Op0);
696 Type* DestTy = CE->getType();
697 switch (Op0->getType()->getTypeID()) {
698 default: llvm_unreachable("Invalid bitcast operand");
699 case Type::IntegerTyID:
700 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
701 if (DestTy->isFloatTy())
702 GV.FloatVal = GV.IntVal.bitsToFloat();
703 else if (DestTy->isDoubleTy())
704 GV.DoubleVal = GV.IntVal.bitsToDouble();
706 case Type::FloatTyID:
707 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
708 GV.IntVal = APInt::floatToBits(GV.FloatVal);
710 case Type::DoubleTyID:
711 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
712 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
714 case Type::PointerTyID:
715 assert(DestTy->isPointerTy() && "Invalid bitcast");
716 break; // getConstantValue(Op0) above already converted it
720 case Instruction::Add:
721 case Instruction::FAdd:
722 case Instruction::Sub:
723 case Instruction::FSub:
724 case Instruction::Mul:
725 case Instruction::FMul:
726 case Instruction::UDiv:
727 case Instruction::SDiv:
728 case Instruction::URem:
729 case Instruction::SRem:
730 case Instruction::And:
731 case Instruction::Or:
732 case Instruction::Xor: {
733 GenericValue LHS = getConstantValue(Op0);
734 GenericValue RHS = getConstantValue(CE->getOperand(1));
736 switch (CE->getOperand(0)->getType()->getTypeID()) {
737 default: llvm_unreachable("Bad add type!");
738 case Type::IntegerTyID:
739 switch (CE->getOpcode()) {
740 default: llvm_unreachable("Invalid integer opcode");
741 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
742 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
743 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
744 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
745 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
746 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
747 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
748 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
749 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
750 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
753 case Type::FloatTyID:
754 switch (CE->getOpcode()) {
755 default: llvm_unreachable("Invalid float opcode");
756 case Instruction::FAdd:
757 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
758 case Instruction::FSub:
759 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
760 case Instruction::FMul:
761 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
762 case Instruction::FDiv:
763 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
764 case Instruction::FRem:
765 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
768 case Type::DoubleTyID:
769 switch (CE->getOpcode()) {
770 default: llvm_unreachable("Invalid double opcode");
771 case Instruction::FAdd:
772 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
773 case Instruction::FSub:
774 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
775 case Instruction::FMul:
776 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
777 case Instruction::FDiv:
778 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
779 case Instruction::FRem:
780 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
783 case Type::X86_FP80TyID:
784 case Type::PPC_FP128TyID:
785 case Type::FP128TyID: {
786 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
787 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
788 switch (CE->getOpcode()) {
789 default: llvm_unreachable("Invalid long double opcode");
790 case Instruction::FAdd:
791 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
792 GV.IntVal = apfLHS.bitcastToAPInt();
794 case Instruction::FSub:
795 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
796 APFloat::rmNearestTiesToEven);
797 GV.IntVal = apfLHS.bitcastToAPInt();
799 case Instruction::FMul:
800 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
801 APFloat::rmNearestTiesToEven);
802 GV.IntVal = apfLHS.bitcastToAPInt();
804 case Instruction::FDiv:
805 apfLHS.divide(APFloat(Sem, RHS.IntVal),
806 APFloat::rmNearestTiesToEven);
807 GV.IntVal = apfLHS.bitcastToAPInt();
809 case Instruction::FRem:
810 apfLHS.mod(APFloat(Sem, RHS.IntVal),
811 APFloat::rmNearestTiesToEven);
812 GV.IntVal = apfLHS.bitcastToAPInt();
824 SmallString<256> Msg;
825 raw_svector_ostream OS(Msg);
826 OS << "ConstantExpr not handled: " << *CE;
827 report_fatal_error(OS.str());
830 // Otherwise, we have a simple constant.
832 switch (C->getType()->getTypeID()) {
833 case Type::FloatTyID:
834 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
836 case Type::DoubleTyID:
837 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
839 case Type::X86_FP80TyID:
840 case Type::FP128TyID:
841 case Type::PPC_FP128TyID:
842 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
844 case Type::IntegerTyID:
845 Result.IntVal = cast<ConstantInt>(C)->getValue();
847 case Type::PointerTyID:
848 if (isa<ConstantPointerNull>(C))
849 Result.PointerVal = 0;
850 else if (const Function *F = dyn_cast<Function>(C))
851 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
852 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
853 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
854 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
855 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
856 BA->getBasicBlock())));
858 llvm_unreachable("Unknown constant pointer type!");
860 case Type::VectorTyID: {
863 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
864 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
865 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
868 elemNum = CDV->getNumElements();
869 ElemTy = CDV->getElementType();
870 } else if (CV || CAZ) {
871 VectorType* VTy = dyn_cast<VectorType>(C->getType());
872 elemNum = VTy->getNumElements();
873 ElemTy = VTy->getElementType();
875 llvm_unreachable("Unknown constant vector type!");
878 Result.AggregateVal.resize(elemNum);
879 // Check if vector holds floats.
880 if(ElemTy->isFloatTy()) {
882 GenericValue floatZero;
883 floatZero.FloatVal = 0.f;
884 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
889 for (unsigned i = 0; i < elemNum; ++i)
890 if (!isa<UndefValue>(CV->getOperand(i)))
891 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
892 CV->getOperand(i))->getValueAPF().convertToFloat();
896 for (unsigned i = 0; i < elemNum; ++i)
897 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
901 // Check if vector holds doubles.
902 if (ElemTy->isDoubleTy()) {
904 GenericValue doubleZero;
905 doubleZero.DoubleVal = 0.0;
906 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
911 for (unsigned i = 0; i < elemNum; ++i)
912 if (!isa<UndefValue>(CV->getOperand(i)))
913 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
914 CV->getOperand(i))->getValueAPF().convertToDouble();
918 for (unsigned i = 0; i < elemNum; ++i)
919 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
923 // Check if vector holds integers.
924 if (ElemTy->isIntegerTy()) {
926 GenericValue intZero;
927 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
928 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
933 for (unsigned i = 0; i < elemNum; ++i)
934 if (!isa<UndefValue>(CV->getOperand(i)))
935 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
936 CV->getOperand(i))->getValue();
938 Result.AggregateVal[i].IntVal =
939 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
944 for (unsigned i = 0; i < elemNum; ++i)
945 Result.AggregateVal[i].IntVal = APInt(
946 CDV->getElementType()->getPrimitiveSizeInBits(),
947 CDV->getElementAsInteger(i));
951 llvm_unreachable("Unknown constant pointer type!");
956 SmallString<256> Msg;
957 raw_svector_ostream OS(Msg);
958 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
959 report_fatal_error(OS.str());
965 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
966 /// with the integer held in IntVal.
967 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
968 unsigned StoreBytes) {
969 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
970 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
972 if (sys::IsLittleEndianHost) {
973 // Little-endian host - the source is ordered from LSB to MSB. Order the
974 // destination from LSB to MSB: Do a straight copy.
975 memcpy(Dst, Src, StoreBytes);
977 // Big-endian host - the source is an array of 64 bit words ordered from
978 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
979 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
980 while (StoreBytes > sizeof(uint64_t)) {
981 StoreBytes -= sizeof(uint64_t);
982 // May not be aligned so use memcpy.
983 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
984 Src += sizeof(uint64_t);
987 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
991 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
992 GenericValue *Ptr, Type *Ty) {
993 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
995 switch (Ty->getTypeID()) {
997 dbgs() << "Cannot store value of type " << *Ty << "!\n";
999 case Type::IntegerTyID:
1000 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
1002 case Type::FloatTyID:
1003 *((float*)Ptr) = Val.FloatVal;
1005 case Type::DoubleTyID:
1006 *((double*)Ptr) = Val.DoubleVal;
1008 case Type::X86_FP80TyID:
1009 memcpy(Ptr, Val.IntVal.getRawData(), 10);
1011 case Type::PointerTyID:
1012 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1013 if (StoreBytes != sizeof(PointerTy))
1014 memset(&(Ptr->PointerVal), 0, StoreBytes);
1016 *((PointerTy*)Ptr) = Val.PointerVal;
1018 case Type::VectorTyID:
1019 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1020 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1021 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1022 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1023 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1024 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1025 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1026 StoreIntToMemory(Val.AggregateVal[i].IntVal,
1027 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1033 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
1034 // Host and target are different endian - reverse the stored bytes.
1035 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1038 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1039 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1040 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1041 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
1042 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1043 const_cast<uint64_t *>(IntVal.getRawData()));
1045 if (sys::IsLittleEndianHost)
1046 // Little-endian host - the destination must be ordered from LSB to MSB.
1047 // The source is ordered from LSB to MSB: Do a straight copy.
1048 memcpy(Dst, Src, LoadBytes);
1050 // Big-endian - the destination is an array of 64 bit words ordered from
1051 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1052 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1054 while (LoadBytes > sizeof(uint64_t)) {
1055 LoadBytes -= sizeof(uint64_t);
1056 // May not be aligned so use memcpy.
1057 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1058 Dst += sizeof(uint64_t);
1061 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1067 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
1070 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
1072 switch (Ty->getTypeID()) {
1073 case Type::IntegerTyID:
1074 // An APInt with all words initially zero.
1075 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1076 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1078 case Type::FloatTyID:
1079 Result.FloatVal = *((float*)Ptr);
1081 case Type::DoubleTyID:
1082 Result.DoubleVal = *((double*)Ptr);
1084 case Type::PointerTyID:
1085 Result.PointerVal = *((PointerTy*)Ptr);
1087 case Type::X86_FP80TyID: {
1088 // This is endian dependent, but it will only work on x86 anyway.
1089 // FIXME: Will not trap if loading a signaling NaN.
1092 Result.IntVal = APInt(80, y);
1095 case Type::VectorTyID: {
1096 const VectorType *VT = cast<VectorType>(Ty);
1097 const Type *ElemT = VT->getElementType();
1098 const unsigned numElems = VT->getNumElements();
1099 if (ElemT->isFloatTy()) {
1100 Result.AggregateVal.resize(numElems);
1101 for (unsigned i = 0; i < numElems; ++i)
1102 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1104 if (ElemT->isDoubleTy()) {
1105 Result.AggregateVal.resize(numElems);
1106 for (unsigned i = 0; i < numElems; ++i)
1107 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1109 if (ElemT->isIntegerTy()) {
1110 GenericValue intZero;
1111 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1112 intZero.IntVal = APInt(elemBitWidth, 0);
1113 Result.AggregateVal.resize(numElems, intZero);
1114 for (unsigned i = 0; i < numElems; ++i)
1115 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1116 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1121 SmallString<256> Msg;
1122 raw_svector_ostream OS(Msg);
1123 OS << "Cannot load value of type " << *Ty << "!";
1124 report_fatal_error(OS.str());
1128 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
1129 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
1130 DEBUG(Init->dump());
1131 if (isa<UndefValue>(Init))
1134 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
1135 unsigned ElementSize =
1136 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
1137 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1138 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1142 if (isa<ConstantAggregateZero>(Init)) {
1143 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
1147 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
1148 unsigned ElementSize =
1149 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
1150 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1151 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1155 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
1156 const StructLayout *SL =
1157 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
1158 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1159 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1163 if (const ConstantDataSequential *CDS =
1164 dyn_cast<ConstantDataSequential>(Init)) {
1165 // CDS is already laid out in host memory order.
1166 StringRef Data = CDS->getRawDataValues();
1167 memcpy(Addr, Data.data(), Data.size());
1171 if (Init->getType()->isFirstClassType()) {
1172 GenericValue Val = getConstantValue(Init);
1173 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1177 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1178 llvm_unreachable("Unknown constant type to initialize memory with!");
1181 /// EmitGlobals - Emit all of the global variables to memory, storing their
1182 /// addresses into GlobalAddress. This must make sure to copy the contents of
1183 /// their initializers into the memory.
1184 void ExecutionEngine::emitGlobals() {
1185 // Loop over all of the global variables in the program, allocating the memory
1186 // to hold them. If there is more than one module, do a prepass over globals
1187 // to figure out how the different modules should link together.
1188 std::map<std::pair<std::string, Type*>,
1189 const GlobalValue*> LinkedGlobalsMap;
1191 if (Modules.size() != 1) {
1192 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1193 Module &M = *Modules[m];
1194 for (Module::const_global_iterator I = M.global_begin(),
1195 E = M.global_end(); I != E; ++I) {
1196 const GlobalValue *GV = I;
1197 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
1198 GV->hasAppendingLinkage() || !GV->hasName())
1199 continue;// Ignore external globals and globals with internal linkage.
1201 const GlobalValue *&GVEntry =
1202 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1204 // If this is the first time we've seen this global, it is the canonical
1211 // If the existing global is strong, never replace it.
1212 if (GVEntry->hasExternalLinkage() ||
1213 GVEntry->hasDLLImportLinkage() ||
1214 GVEntry->hasDLLExportLinkage())
1217 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1218 // symbol. FIXME is this right for common?
1219 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1225 std::vector<const GlobalValue*> NonCanonicalGlobals;
1226 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1227 Module &M = *Modules[m];
1228 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1230 // In the multi-module case, see what this global maps to.
1231 if (!LinkedGlobalsMap.empty()) {
1232 if (const GlobalValue *GVEntry =
1233 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1234 // If something else is the canonical global, ignore this one.
1235 if (GVEntry != &*I) {
1236 NonCanonicalGlobals.push_back(I);
1242 if (!I->isDeclaration()) {
1243 addGlobalMapping(I, getMemoryForGV(I));
1245 // External variable reference. Try to use the dynamic loader to
1246 // get a pointer to it.
1248 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1249 addGlobalMapping(I, SymAddr);
1251 report_fatal_error("Could not resolve external global address: "
1257 // If there are multiple modules, map the non-canonical globals to their
1258 // canonical location.
1259 if (!NonCanonicalGlobals.empty()) {
1260 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1261 const GlobalValue *GV = NonCanonicalGlobals[i];
1262 const GlobalValue *CGV =
1263 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1264 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1265 assert(Ptr && "Canonical global wasn't codegen'd!");
1266 addGlobalMapping(GV, Ptr);
1270 // Now that all of the globals are set up in memory, loop through them all
1271 // and initialize their contents.
1272 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1274 if (!I->isDeclaration()) {
1275 if (!LinkedGlobalsMap.empty()) {
1276 if (const GlobalValue *GVEntry =
1277 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1278 if (GVEntry != &*I) // Not the canonical variable.
1281 EmitGlobalVariable(I);
1287 // EmitGlobalVariable - This method emits the specified global variable to the
1288 // address specified in GlobalAddresses, or allocates new memory if it's not
1289 // already in the map.
1290 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1291 void *GA = getPointerToGlobalIfAvailable(GV);
1294 // If it's not already specified, allocate memory for the global.
1295 GA = getMemoryForGV(GV);
1297 // If we failed to allocate memory for this global, return.
1298 if (GA == 0) return;
1300 addGlobalMapping(GV, GA);
1303 // Don't initialize if it's thread local, let the client do it.
1304 if (!GV->isThreadLocal())
1305 InitializeMemory(GV->getInitializer(), GA);
1307 Type *ElTy = GV->getType()->getElementType();
1308 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
1309 NumInitBytes += (unsigned)GVSize;
1313 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1314 : EE(EE), GlobalAddressMap(this) {
1318 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1319 return &EES->EE.lock;
1322 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1323 const GlobalValue *Old) {
1324 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1325 EES->GlobalAddressReverseMap.erase(OldVal);
1328 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1329 const GlobalValue *,
1330 const GlobalValue *) {
1331 llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1332 " RAUW on a value it has a global mapping for.");