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/ADT/SmallString.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ExecutionEngine/GenericValue.h"
20 #include "llvm/ExecutionEngine/JITMemoryManager.h"
21 #include "llvm/ExecutionEngine/ObjectCache.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/IR/ValueHandle.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 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
41 STATISTIC(NumGlobals , "Number of global vars initialized");
43 // Pin the vtable to this file.
44 void ObjectCache::anchor() {}
45 void ObjectBuffer::anchor() {}
46 void ObjectBufferStream::anchor() {}
48 ExecutionEngine *(*ExecutionEngine::JITCtor)(
50 std::string *ErrorStr,
51 JITMemoryManager *JMM,
53 TargetMachine *TM) = nullptr;
54 ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
56 std::string *ErrorStr,
57 RTDyldMemoryManager *MCJMM,
59 TargetMachine *TM) = nullptr;
60 ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
61 std::string *ErrorStr) =nullptr;
63 ExecutionEngine::ExecutionEngine(Module *M)
65 LazyFunctionCreator(nullptr) {
66 CompilingLazily = false;
67 GVCompilationDisabled = false;
68 SymbolSearchingDisabled = false;
70 // IR module verification is enabled by default in debug builds, and disabled
71 // by default in release builds.
75 VerifyModules = false;
79 assert(M && "Module is null?");
82 ExecutionEngine::~ExecutionEngine() {
83 clearAllGlobalMappings();
84 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
89 /// \brief Helper class which uses a value handler to automatically deletes the
90 /// memory block when the GlobalVariable is destroyed.
91 class GVMemoryBlock : public CallbackVH {
92 GVMemoryBlock(const GlobalVariable *GV)
93 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
96 /// \brief Returns the address the GlobalVariable should be written into. The
97 /// GVMemoryBlock object prefixes that.
98 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
99 Type *ElTy = GV->getType()->getElementType();
100 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
101 void *RawMemory = ::operator new(
102 DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock),
103 TD.getPreferredAlignment(GV))
105 new(RawMemory) GVMemoryBlock(GV);
106 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
109 void deleted() override {
110 // We allocated with operator new and with some extra memory hanging off the
111 // end, so don't just delete this. I'm not sure if this is actually
113 this->~GVMemoryBlock();
114 ::operator delete(this);
117 } // anonymous namespace
119 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
120 return GVMemoryBlock::Create(GV, *getDataLayout());
123 bool ExecutionEngine::removeModule(Module *M) {
124 for(SmallVectorImpl<Module *>::iterator I = Modules.begin(),
125 E = Modules.end(); I != E; ++I) {
129 clearGlobalMappingsFromModule(M);
136 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
137 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
138 if (Function *F = Modules[i]->getFunction(FnName))
145 void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
146 const GlobalValue *ToUnmap) {
147 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
150 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
152 if (I == GlobalAddressMap.end())
156 GlobalAddressMap.erase(I);
159 GlobalAddressReverseMap.erase(OldVal);
163 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
164 MutexGuard locked(lock);
166 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
167 << "\' to [" << Addr << "]\n";);
168 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
169 assert((!CurVal || !Addr) && "GlobalMapping already established!");
172 // If we are using the reverse mapping, add it too.
173 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
174 AssertingVH<const GlobalValue> &V =
175 EEState.getGlobalAddressReverseMap(locked)[Addr];
176 assert((!V || !GV) && "GlobalMapping already established!");
181 void ExecutionEngine::clearAllGlobalMappings() {
182 MutexGuard locked(lock);
184 EEState.getGlobalAddressMap(locked).clear();
185 EEState.getGlobalAddressReverseMap(locked).clear();
188 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
189 MutexGuard locked(lock);
191 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
192 EEState.RemoveMapping(locked, FI);
193 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
195 EEState.RemoveMapping(locked, GI);
198 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
199 MutexGuard locked(lock);
201 ExecutionEngineState::GlobalAddressMapTy &Map =
202 EEState.getGlobalAddressMap(locked);
204 // Deleting from the mapping?
206 return EEState.RemoveMapping(locked, GV);
208 void *&CurVal = Map[GV];
209 void *OldVal = CurVal;
211 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
212 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
215 // If we are using the reverse mapping, add it too.
216 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
217 AssertingVH<const GlobalValue> &V =
218 EEState.getGlobalAddressReverseMap(locked)[Addr];
219 assert((!V || !GV) && "GlobalMapping already established!");
225 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
226 MutexGuard locked(lock);
228 ExecutionEngineState::GlobalAddressMapTy::iterator I =
229 EEState.getGlobalAddressMap(locked).find(GV);
230 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : nullptr;
233 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
234 MutexGuard locked(lock);
236 // If we haven't computed the reverse mapping yet, do so first.
237 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
238 for (ExecutionEngineState::GlobalAddressMapTy::iterator
239 I = EEState.getGlobalAddressMap(locked).begin(),
240 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
241 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
242 I->second, I->first));
245 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
246 EEState.getGlobalAddressReverseMap(locked).find(Addr);
247 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : nullptr;
253 std::vector<char*> Values;
255 ArgvArray() : Array(nullptr) {}
256 ~ArgvArray() { clear(); }
260 for (size_t I = 0, E = Values.size(); I != E; ++I) {
265 /// Turn a vector of strings into a nice argv style array of pointers to null
266 /// terminated strings.
267 void *reset(LLVMContext &C, ExecutionEngine *EE,
268 const std::vector<std::string> &InputArgv);
270 } // anonymous namespace
271 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
272 const std::vector<std::string> &InputArgv) {
273 clear(); // Free the old contents.
274 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
275 Array = new char[(InputArgv.size()+1)*PtrSize];
277 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
278 Type *SBytePtr = Type::getInt8PtrTy(C);
280 for (unsigned i = 0; i != InputArgv.size(); ++i) {
281 unsigned Size = InputArgv[i].size()+1;
282 char *Dest = new char[Size];
283 Values.push_back(Dest);
284 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
286 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
289 // Endian safe: Array[i] = (PointerTy)Dest;
290 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
295 EE->StoreValueToMemory(PTOGV(nullptr),
296 (GenericValue*)(Array+InputArgv.size()*PtrSize),
301 void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
303 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
304 GlobalVariable *GV = module->getNamedGlobal(Name);
306 // If this global has internal linkage, or if it has a use, then it must be
307 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
308 // this is the case, don't execute any of the global ctors, __main will do
310 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
312 // Should be an array of '{ i32, void ()* }' structs. The first value is
313 // the init priority, which we ignore.
314 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
317 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
318 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
321 Constant *FP = CS->getOperand(1);
322 if (FP->isNullValue())
323 continue; // Found a sentinal value, ignore.
325 // Strip off constant expression casts.
326 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
328 FP = CE->getOperand(0);
330 // Execute the ctor/dtor function!
331 if (Function *F = dyn_cast<Function>(FP))
332 runFunction(F, std::vector<GenericValue>());
334 // FIXME: It is marginally lame that we just do nothing here if we see an
335 // entry we don't recognize. It might not be unreasonable for the verifier
336 // to not even allow this and just assert here.
340 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
341 // Execute global ctors/dtors for each module in the program.
342 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
343 runStaticConstructorsDestructors(Modules[i], isDtors);
347 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
348 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
349 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
350 for (unsigned i = 0; i < PtrSize; ++i)
351 if (*(i + (uint8_t*)Loc))
357 int ExecutionEngine::runFunctionAsMain(Function *Fn,
358 const std::vector<std::string> &argv,
359 const char * const * envp) {
360 std::vector<GenericValue> GVArgs;
362 GVArgc.IntVal = APInt(32, argv.size());
365 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
366 FunctionType *FTy = Fn->getFunctionType();
367 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
369 // Check the argument types.
371 report_fatal_error("Invalid number of arguments of main() supplied");
372 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
373 report_fatal_error("Invalid type for third argument of main() supplied");
374 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
375 report_fatal_error("Invalid type for second argument of main() supplied");
376 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
377 report_fatal_error("Invalid type for first argument of main() supplied");
378 if (!FTy->getReturnType()->isIntegerTy() &&
379 !FTy->getReturnType()->isVoidTy())
380 report_fatal_error("Invalid return type of main() supplied");
385 GVArgs.push_back(GVArgc); // Arg #0 = argc.
388 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
389 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
390 "argv[0] was null after CreateArgv");
392 std::vector<std::string> EnvVars;
393 for (unsigned i = 0; envp[i]; ++i)
394 EnvVars.push_back(envp[i]);
396 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
401 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
404 ExecutionEngine *ExecutionEngine::create(Module *M,
405 bool ForceInterpreter,
406 std::string *ErrorStr,
407 CodeGenOpt::Level OptLevel,
409 EngineBuilder EB = EngineBuilder(M)
410 .setEngineKind(ForceInterpreter
411 ? EngineKind::Interpreter
413 .setErrorStr(ErrorStr)
414 .setOptLevel(OptLevel)
415 .setAllocateGVsWithCode(GVsWithCode);
420 /// createJIT - This is the factory method for creating a JIT for the current
421 /// machine, it does not fall back to the interpreter. This takes ownership
423 ExecutionEngine *ExecutionEngine::createJIT(Module *M,
424 std::string *ErrorStr,
425 JITMemoryManager *JMM,
426 CodeGenOpt::Level OL,
429 CodeModel::Model CMM) {
430 if (!ExecutionEngine::JITCtor) {
432 *ErrorStr = "JIT has not been linked in.";
436 // Use the defaults for extra parameters. Users can use EngineBuilder to
439 EB.setEngineKind(EngineKind::JIT);
440 EB.setErrorStr(ErrorStr);
441 EB.setRelocationModel(RM);
442 EB.setCodeModel(CMM);
443 EB.setAllocateGVsWithCode(GVsWithCode);
445 EB.setJITMemoryManager(JMM);
447 // TODO: permit custom TargetOptions here
448 TargetMachine *TM = EB.selectTarget();
449 if (!TM || (ErrorStr && ErrorStr->length() > 0)) return nullptr;
451 return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
454 ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
455 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
457 // Make sure we can resolve symbols in the program as well. The zero arg
458 // to the function tells DynamicLibrary to load the program, not a library.
459 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
462 assert(!(JMM && MCJMM));
464 // If the user specified a memory manager but didn't specify which engine to
465 // create, we assume they only want the JIT, and we fail if they only want
468 if (WhichEngine & EngineKind::JIT)
469 WhichEngine = EngineKind::JIT;
472 *ErrorStr = "Cannot create an interpreter with a memory manager.";
477 if (MCJMM && ! UseMCJIT) {
480 "Cannot create a legacy JIT with a runtime dyld memory "
485 // Unless the interpreter was explicitly selected or the JIT is not linked,
487 if ((WhichEngine & EngineKind::JIT) && TheTM) {
488 Triple TT(M->getTargetTriple());
489 if (!TM->getTarget().hasJIT()) {
490 errs() << "WARNING: This target JIT is not designed for the host"
491 << " you are running. If bad things happen, please choose"
492 << " a different -march switch.\n";
495 ExecutionEngine *EE = nullptr;
496 if (UseMCJIT && ExecutionEngine::MCJITCtor)
497 EE = ExecutionEngine::MCJITCtor(M, ErrorStr, MCJMM ? MCJMM : JMM,
498 AllocateGVsWithCode, TheTM.release());
499 else if (ExecutionEngine::JITCtor)
500 EE = ExecutionEngine::JITCtor(M, ErrorStr, JMM,
501 AllocateGVsWithCode, TheTM.release());
504 EE->setVerifyModules(VerifyModules);
509 // If we can't make a JIT and we didn't request one specifically, try making
510 // an interpreter instead.
511 if (WhichEngine & EngineKind::Interpreter) {
512 if (ExecutionEngine::InterpCtor)
513 return ExecutionEngine::InterpCtor(M, ErrorStr);
515 *ErrorStr = "Interpreter has not been linked in.";
519 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::JITCtor &&
520 !ExecutionEngine::MCJITCtor) {
522 *ErrorStr = "JIT has not been linked in.";
528 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
529 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
530 return getPointerToFunction(F);
532 MutexGuard locked(lock);
533 if (void *P = EEState.getGlobalAddressMap(locked)[GV])
536 // Global variable might have been added since interpreter started.
537 if (GlobalVariable *GVar =
538 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
539 EmitGlobalVariable(GVar);
541 llvm_unreachable("Global hasn't had an address allocated yet!");
543 return EEState.getGlobalAddressMap(locked)[GV];
546 /// \brief Converts a Constant* into a GenericValue, including handling of
547 /// ConstantExpr values.
548 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
549 // If its undefined, return the garbage.
550 if (isa<UndefValue>(C)) {
552 switch (C->getType()->getTypeID()) {
555 case Type::IntegerTyID:
556 case Type::X86_FP80TyID:
557 case Type::FP128TyID:
558 case Type::PPC_FP128TyID:
559 // Although the value is undefined, we still have to construct an APInt
560 // with the correct bit width.
561 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
563 case Type::StructTyID: {
564 // if the whole struct is 'undef' just reserve memory for the value.
565 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
566 unsigned int elemNum = STy->getNumElements();
567 Result.AggregateVal.resize(elemNum);
568 for (unsigned int i = 0; i < elemNum; ++i) {
569 Type *ElemTy = STy->getElementType(i);
570 if (ElemTy->isIntegerTy())
571 Result.AggregateVal[i].IntVal =
572 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
573 else if (ElemTy->isAggregateType()) {
574 const Constant *ElemUndef = UndefValue::get(ElemTy);
575 Result.AggregateVal[i] = getConstantValue(ElemUndef);
581 case Type::VectorTyID:
582 // if the whole vector is 'undef' just reserve memory for the value.
583 const VectorType* VTy = dyn_cast<VectorType>(C->getType());
584 const Type *ElemTy = VTy->getElementType();
585 unsigned int elemNum = VTy->getNumElements();
586 Result.AggregateVal.resize(elemNum);
587 if (ElemTy->isIntegerTy())
588 for (unsigned int i = 0; i < elemNum; ++i)
589 Result.AggregateVal[i].IntVal =
590 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
596 // Otherwise, if the value is a ConstantExpr...
597 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
598 Constant *Op0 = CE->getOperand(0);
599 switch (CE->getOpcode()) {
600 case Instruction::GetElementPtr: {
602 GenericValue Result = getConstantValue(Op0);
603 APInt Offset(DL->getPointerSizeInBits(), 0);
604 cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset);
606 char* tmp = (char*) Result.PointerVal;
607 Result = PTOGV(tmp + Offset.getSExtValue());
610 case Instruction::Trunc: {
611 GenericValue GV = getConstantValue(Op0);
612 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
613 GV.IntVal = GV.IntVal.trunc(BitWidth);
616 case Instruction::ZExt: {
617 GenericValue GV = getConstantValue(Op0);
618 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
619 GV.IntVal = GV.IntVal.zext(BitWidth);
622 case Instruction::SExt: {
623 GenericValue GV = getConstantValue(Op0);
624 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
625 GV.IntVal = GV.IntVal.sext(BitWidth);
628 case Instruction::FPTrunc: {
630 GenericValue GV = getConstantValue(Op0);
631 GV.FloatVal = float(GV.DoubleVal);
634 case Instruction::FPExt:{
636 GenericValue GV = getConstantValue(Op0);
637 GV.DoubleVal = double(GV.FloatVal);
640 case Instruction::UIToFP: {
641 GenericValue GV = getConstantValue(Op0);
642 if (CE->getType()->isFloatTy())
643 GV.FloatVal = float(GV.IntVal.roundToDouble());
644 else if (CE->getType()->isDoubleTy())
645 GV.DoubleVal = GV.IntVal.roundToDouble();
646 else if (CE->getType()->isX86_FP80Ty()) {
647 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
648 (void)apf.convertFromAPInt(GV.IntVal,
650 APFloat::rmNearestTiesToEven);
651 GV.IntVal = apf.bitcastToAPInt();
655 case Instruction::SIToFP: {
656 GenericValue GV = getConstantValue(Op0);
657 if (CE->getType()->isFloatTy())
658 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
659 else if (CE->getType()->isDoubleTy())
660 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
661 else if (CE->getType()->isX86_FP80Ty()) {
662 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
663 (void)apf.convertFromAPInt(GV.IntVal,
665 APFloat::rmNearestTiesToEven);
666 GV.IntVal = apf.bitcastToAPInt();
670 case Instruction::FPToUI: // double->APInt conversion handles sign
671 case Instruction::FPToSI: {
672 GenericValue GV = getConstantValue(Op0);
673 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
674 if (Op0->getType()->isFloatTy())
675 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
676 else if (Op0->getType()->isDoubleTy())
677 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
678 else if (Op0->getType()->isX86_FP80Ty()) {
679 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
682 (void)apf.convertToInteger(&v, BitWidth,
683 CE->getOpcode()==Instruction::FPToSI,
684 APFloat::rmTowardZero, &ignored);
685 GV.IntVal = v; // endian?
689 case Instruction::PtrToInt: {
690 GenericValue GV = getConstantValue(Op0);
691 uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType());
692 assert(PtrWidth <= 64 && "Bad pointer width");
693 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
694 uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType());
695 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
698 case Instruction::IntToPtr: {
699 GenericValue GV = getConstantValue(Op0);
700 uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType());
701 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
702 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
703 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
706 case Instruction::BitCast: {
707 GenericValue GV = getConstantValue(Op0);
708 Type* DestTy = CE->getType();
709 switch (Op0->getType()->getTypeID()) {
710 default: llvm_unreachable("Invalid bitcast operand");
711 case Type::IntegerTyID:
712 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
713 if (DestTy->isFloatTy())
714 GV.FloatVal = GV.IntVal.bitsToFloat();
715 else if (DestTy->isDoubleTy())
716 GV.DoubleVal = GV.IntVal.bitsToDouble();
718 case Type::FloatTyID:
719 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
720 GV.IntVal = APInt::floatToBits(GV.FloatVal);
722 case Type::DoubleTyID:
723 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
724 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
726 case Type::PointerTyID:
727 assert(DestTy->isPointerTy() && "Invalid bitcast");
728 break; // getConstantValue(Op0) above already converted it
732 case Instruction::Add:
733 case Instruction::FAdd:
734 case Instruction::Sub:
735 case Instruction::FSub:
736 case Instruction::Mul:
737 case Instruction::FMul:
738 case Instruction::UDiv:
739 case Instruction::SDiv:
740 case Instruction::URem:
741 case Instruction::SRem:
742 case Instruction::And:
743 case Instruction::Or:
744 case Instruction::Xor: {
745 GenericValue LHS = getConstantValue(Op0);
746 GenericValue RHS = getConstantValue(CE->getOperand(1));
748 switch (CE->getOperand(0)->getType()->getTypeID()) {
749 default: llvm_unreachable("Bad add type!");
750 case Type::IntegerTyID:
751 switch (CE->getOpcode()) {
752 default: llvm_unreachable("Invalid integer opcode");
753 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
754 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
755 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
756 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
757 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
758 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
759 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
760 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
761 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
762 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
765 case Type::FloatTyID:
766 switch (CE->getOpcode()) {
767 default: llvm_unreachable("Invalid float opcode");
768 case Instruction::FAdd:
769 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
770 case Instruction::FSub:
771 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
772 case Instruction::FMul:
773 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
774 case Instruction::FDiv:
775 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
776 case Instruction::FRem:
777 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
780 case Type::DoubleTyID:
781 switch (CE->getOpcode()) {
782 default: llvm_unreachable("Invalid double opcode");
783 case Instruction::FAdd:
784 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
785 case Instruction::FSub:
786 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
787 case Instruction::FMul:
788 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
789 case Instruction::FDiv:
790 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
791 case Instruction::FRem:
792 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
795 case Type::X86_FP80TyID:
796 case Type::PPC_FP128TyID:
797 case Type::FP128TyID: {
798 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
799 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
800 switch (CE->getOpcode()) {
801 default: llvm_unreachable("Invalid long double opcode");
802 case Instruction::FAdd:
803 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
804 GV.IntVal = apfLHS.bitcastToAPInt();
806 case Instruction::FSub:
807 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
808 APFloat::rmNearestTiesToEven);
809 GV.IntVal = apfLHS.bitcastToAPInt();
811 case Instruction::FMul:
812 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
813 APFloat::rmNearestTiesToEven);
814 GV.IntVal = apfLHS.bitcastToAPInt();
816 case Instruction::FDiv:
817 apfLHS.divide(APFloat(Sem, RHS.IntVal),
818 APFloat::rmNearestTiesToEven);
819 GV.IntVal = apfLHS.bitcastToAPInt();
821 case Instruction::FRem:
822 apfLHS.mod(APFloat(Sem, RHS.IntVal),
823 APFloat::rmNearestTiesToEven);
824 GV.IntVal = apfLHS.bitcastToAPInt();
836 SmallString<256> Msg;
837 raw_svector_ostream OS(Msg);
838 OS << "ConstantExpr not handled: " << *CE;
839 report_fatal_error(OS.str());
842 // Otherwise, we have a simple constant.
844 switch (C->getType()->getTypeID()) {
845 case Type::FloatTyID:
846 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
848 case Type::DoubleTyID:
849 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
851 case Type::X86_FP80TyID:
852 case Type::FP128TyID:
853 case Type::PPC_FP128TyID:
854 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
856 case Type::IntegerTyID:
857 Result.IntVal = cast<ConstantInt>(C)->getValue();
859 case Type::PointerTyID:
860 if (isa<ConstantPointerNull>(C))
861 Result.PointerVal = nullptr;
862 else if (const Function *F = dyn_cast<Function>(C))
863 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
864 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
865 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
866 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
867 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
868 BA->getBasicBlock())));
870 llvm_unreachable("Unknown constant pointer type!");
872 case Type::VectorTyID: {
875 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
876 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
877 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
880 elemNum = CDV->getNumElements();
881 ElemTy = CDV->getElementType();
882 } else if (CV || CAZ) {
883 VectorType* VTy = dyn_cast<VectorType>(C->getType());
884 elemNum = VTy->getNumElements();
885 ElemTy = VTy->getElementType();
887 llvm_unreachable("Unknown constant vector type!");
890 Result.AggregateVal.resize(elemNum);
891 // Check if vector holds floats.
892 if(ElemTy->isFloatTy()) {
894 GenericValue floatZero;
895 floatZero.FloatVal = 0.f;
896 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
901 for (unsigned i = 0; i < elemNum; ++i)
902 if (!isa<UndefValue>(CV->getOperand(i)))
903 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
904 CV->getOperand(i))->getValueAPF().convertToFloat();
908 for (unsigned i = 0; i < elemNum; ++i)
909 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
913 // Check if vector holds doubles.
914 if (ElemTy->isDoubleTy()) {
916 GenericValue doubleZero;
917 doubleZero.DoubleVal = 0.0;
918 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
923 for (unsigned i = 0; i < elemNum; ++i)
924 if (!isa<UndefValue>(CV->getOperand(i)))
925 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
926 CV->getOperand(i))->getValueAPF().convertToDouble();
930 for (unsigned i = 0; i < elemNum; ++i)
931 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
935 // Check if vector holds integers.
936 if (ElemTy->isIntegerTy()) {
938 GenericValue intZero;
939 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
940 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
945 for (unsigned i = 0; i < elemNum; ++i)
946 if (!isa<UndefValue>(CV->getOperand(i)))
947 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
948 CV->getOperand(i))->getValue();
950 Result.AggregateVal[i].IntVal =
951 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
956 for (unsigned i = 0; i < elemNum; ++i)
957 Result.AggregateVal[i].IntVal = APInt(
958 CDV->getElementType()->getPrimitiveSizeInBits(),
959 CDV->getElementAsInteger(i));
963 llvm_unreachable("Unknown constant pointer type!");
968 SmallString<256> Msg;
969 raw_svector_ostream OS(Msg);
970 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
971 report_fatal_error(OS.str());
977 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
978 /// with the integer held in IntVal.
979 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
980 unsigned StoreBytes) {
981 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
982 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
984 if (sys::IsLittleEndianHost) {
985 // Little-endian host - the source is ordered from LSB to MSB. Order the
986 // destination from LSB to MSB: Do a straight copy.
987 memcpy(Dst, Src, StoreBytes);
989 // Big-endian host - the source is an array of 64 bit words ordered from
990 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
991 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
992 while (StoreBytes > sizeof(uint64_t)) {
993 StoreBytes -= sizeof(uint64_t);
994 // May not be aligned so use memcpy.
995 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
996 Src += sizeof(uint64_t);
999 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1003 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
1004 GenericValue *Ptr, Type *Ty) {
1005 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
1007 switch (Ty->getTypeID()) {
1009 dbgs() << "Cannot store value of type " << *Ty << "!\n";
1011 case Type::IntegerTyID:
1012 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
1014 case Type::FloatTyID:
1015 *((float*)Ptr) = Val.FloatVal;
1017 case Type::DoubleTyID:
1018 *((double*)Ptr) = Val.DoubleVal;
1020 case Type::X86_FP80TyID:
1021 memcpy(Ptr, Val.IntVal.getRawData(), 10);
1023 case Type::PointerTyID:
1024 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1025 if (StoreBytes != sizeof(PointerTy))
1026 memset(&(Ptr->PointerVal), 0, StoreBytes);
1028 *((PointerTy*)Ptr) = Val.PointerVal;
1030 case Type::VectorTyID:
1031 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1032 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1033 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1034 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1035 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1036 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1037 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1038 StoreIntToMemory(Val.AggregateVal[i].IntVal,
1039 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1045 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
1046 // Host and target are different endian - reverse the stored bytes.
1047 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1050 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1051 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1052 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1053 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
1054 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1055 const_cast<uint64_t *>(IntVal.getRawData()));
1057 if (sys::IsLittleEndianHost)
1058 // Little-endian host - the destination must be ordered from LSB to MSB.
1059 // The source is ordered from LSB to MSB: Do a straight copy.
1060 memcpy(Dst, Src, LoadBytes);
1062 // Big-endian - the destination is an array of 64 bit words ordered from
1063 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1064 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1066 while (LoadBytes > sizeof(uint64_t)) {
1067 LoadBytes -= sizeof(uint64_t);
1068 // May not be aligned so use memcpy.
1069 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1070 Dst += sizeof(uint64_t);
1073 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1079 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
1082 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
1084 switch (Ty->getTypeID()) {
1085 case Type::IntegerTyID:
1086 // An APInt with all words initially zero.
1087 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1088 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1090 case Type::FloatTyID:
1091 Result.FloatVal = *((float*)Ptr);
1093 case Type::DoubleTyID:
1094 Result.DoubleVal = *((double*)Ptr);
1096 case Type::PointerTyID:
1097 Result.PointerVal = *((PointerTy*)Ptr);
1099 case Type::X86_FP80TyID: {
1100 // This is endian dependent, but it will only work on x86 anyway.
1101 // FIXME: Will not trap if loading a signaling NaN.
1104 Result.IntVal = APInt(80, y);
1107 case Type::VectorTyID: {
1108 const VectorType *VT = cast<VectorType>(Ty);
1109 const Type *ElemT = VT->getElementType();
1110 const unsigned numElems = VT->getNumElements();
1111 if (ElemT->isFloatTy()) {
1112 Result.AggregateVal.resize(numElems);
1113 for (unsigned i = 0; i < numElems; ++i)
1114 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1116 if (ElemT->isDoubleTy()) {
1117 Result.AggregateVal.resize(numElems);
1118 for (unsigned i = 0; i < numElems; ++i)
1119 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1121 if (ElemT->isIntegerTy()) {
1122 GenericValue intZero;
1123 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1124 intZero.IntVal = APInt(elemBitWidth, 0);
1125 Result.AggregateVal.resize(numElems, intZero);
1126 for (unsigned i = 0; i < numElems; ++i)
1127 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1128 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1133 SmallString<256> Msg;
1134 raw_svector_ostream OS(Msg);
1135 OS << "Cannot load value of type " << *Ty << "!";
1136 report_fatal_error(OS.str());
1140 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
1141 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
1142 DEBUG(Init->dump());
1143 if (isa<UndefValue>(Init))
1146 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
1147 unsigned ElementSize =
1148 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
1149 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1150 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1154 if (isa<ConstantAggregateZero>(Init)) {
1155 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
1159 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
1160 unsigned ElementSize =
1161 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
1162 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1163 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1167 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
1168 const StructLayout *SL =
1169 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
1170 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1171 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1175 if (const ConstantDataSequential *CDS =
1176 dyn_cast<ConstantDataSequential>(Init)) {
1177 // CDS is already laid out in host memory order.
1178 StringRef Data = CDS->getRawDataValues();
1179 memcpy(Addr, Data.data(), Data.size());
1183 if (Init->getType()->isFirstClassType()) {
1184 GenericValue Val = getConstantValue(Init);
1185 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1189 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1190 llvm_unreachable("Unknown constant type to initialize memory with!");
1193 /// EmitGlobals - Emit all of the global variables to memory, storing their
1194 /// addresses into GlobalAddress. This must make sure to copy the contents of
1195 /// their initializers into the memory.
1196 void ExecutionEngine::emitGlobals() {
1197 // Loop over all of the global variables in the program, allocating the memory
1198 // to hold them. If there is more than one module, do a prepass over globals
1199 // to figure out how the different modules should link together.
1200 std::map<std::pair<std::string, Type*>,
1201 const GlobalValue*> LinkedGlobalsMap;
1203 if (Modules.size() != 1) {
1204 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1205 Module &M = *Modules[m];
1206 for (Module::const_global_iterator I = M.global_begin(),
1207 E = M.global_end(); I != E; ++I) {
1208 const GlobalValue *GV = I;
1209 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
1210 GV->hasAppendingLinkage() || !GV->hasName())
1211 continue;// Ignore external globals and globals with internal linkage.
1213 const GlobalValue *&GVEntry =
1214 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1216 // If this is the first time we've seen this global, it is the canonical
1223 // If the existing global is strong, never replace it.
1224 if (GVEntry->hasExternalLinkage())
1227 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1228 // symbol. FIXME is this right for common?
1229 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1235 std::vector<const GlobalValue*> NonCanonicalGlobals;
1236 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1237 Module &M = *Modules[m];
1238 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1240 // In the multi-module case, see what this global maps to.
1241 if (!LinkedGlobalsMap.empty()) {
1242 if (const GlobalValue *GVEntry =
1243 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1244 // If something else is the canonical global, ignore this one.
1245 if (GVEntry != &*I) {
1246 NonCanonicalGlobals.push_back(I);
1252 if (!I->isDeclaration()) {
1253 addGlobalMapping(I, getMemoryForGV(I));
1255 // External variable reference. Try to use the dynamic loader to
1256 // get a pointer to it.
1258 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1259 addGlobalMapping(I, SymAddr);
1261 report_fatal_error("Could not resolve external global address: "
1267 // If there are multiple modules, map the non-canonical globals to their
1268 // canonical location.
1269 if (!NonCanonicalGlobals.empty()) {
1270 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1271 const GlobalValue *GV = NonCanonicalGlobals[i];
1272 const GlobalValue *CGV =
1273 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1274 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1275 assert(Ptr && "Canonical global wasn't codegen'd!");
1276 addGlobalMapping(GV, Ptr);
1280 // Now that all of the globals are set up in memory, loop through them all
1281 // and initialize their contents.
1282 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1284 if (!I->isDeclaration()) {
1285 if (!LinkedGlobalsMap.empty()) {
1286 if (const GlobalValue *GVEntry =
1287 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1288 if (GVEntry != &*I) // Not the canonical variable.
1291 EmitGlobalVariable(I);
1297 // EmitGlobalVariable - This method emits the specified global variable to the
1298 // address specified in GlobalAddresses, or allocates new memory if it's not
1299 // already in the map.
1300 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1301 void *GA = getPointerToGlobalIfAvailable(GV);
1304 // If it's not already specified, allocate memory for the global.
1305 GA = getMemoryForGV(GV);
1307 // If we failed to allocate memory for this global, return.
1310 addGlobalMapping(GV, GA);
1313 // Don't initialize if it's thread local, let the client do it.
1314 if (!GV->isThreadLocal())
1315 InitializeMemory(GV->getInitializer(), GA);
1317 Type *ElTy = GV->getType()->getElementType();
1318 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
1319 NumInitBytes += (unsigned)GVSize;
1323 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1324 : EE(EE), GlobalAddressMap(this) {
1328 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1329 return &EES->EE.lock;
1332 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1333 const GlobalValue *Old) {
1334 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1335 EES->GlobalAddressReverseMap.erase(OldVal);
1338 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1339 const GlobalValue *,
1340 const GlobalValue *) {
1341 llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1342 " RAUW on a value it has a global mapping for.");