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/STLExtras.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ExecutionEngine/GenericValue.h"
20 #include "llvm/ExecutionEngine/JITEventListener.h"
21 #include "llvm/ExecutionEngine/ObjectCache.h"
22 #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Mangler.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/IR/ValueHandle.h"
30 #include "llvm/Object/Archive.h"
31 #include "llvm/Object/ObjectFile.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/DynamicLibrary.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/Host.h"
36 #include "llvm/Support/MutexGuard.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetMachine.h"
44 #define DEBUG_TYPE "jit"
46 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
47 STATISTIC(NumGlobals , "Number of global vars initialized");
49 ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
50 std::unique_ptr<Module> M, std::string *ErrorStr,
51 std::shared_ptr<MCJITMemoryManager> MemMgr,
53 std::shared_ptr<JITSymbolResolver> Resolver,
54 std::unique_ptr<TargetMachine> TM) = nullptr;
56 ExecutionEngine *(*ExecutionEngine::OrcMCJITReplacementCtor)(
57 std::string *ErrorStr, std::shared_ptr<MCJITMemoryManager> MemMgr,
58 std::shared_ptr<JITSymbolResolver> Resolver,
59 std::unique_ptr<TargetMachine> TM) = nullptr;
61 ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M,
62 std::string *ErrorStr) =nullptr;
64 void JITEventListener::anchor() {}
66 void ObjectCache::anchor() {}
68 void ExecutionEngine::Init(std::unique_ptr<Module> M) {
69 CompilingLazily = false;
70 GVCompilationDisabled = false;
71 SymbolSearchingDisabled = false;
73 // IR module verification is enabled by default in debug builds, and disabled
74 // by default in release builds.
78 VerifyModules = false;
81 assert(M && "Module is null?");
82 Modules.push_back(std::move(M));
85 ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)
86 : DL(M->getDataLayout()), LazyFunctionCreator(nullptr) {
90 ExecutionEngine::ExecutionEngine(DataLayout DL, std::unique_ptr<Module> M)
91 : DL(std::move(DL)), LazyFunctionCreator(nullptr) {
95 ExecutionEngine::~ExecutionEngine() {
96 clearAllGlobalMappings();
100 /// \brief Helper class which uses a value handler to automatically deletes the
101 /// memory block when the GlobalVariable is destroyed.
102 class GVMemoryBlock final : public CallbackVH {
103 GVMemoryBlock(const GlobalVariable *GV)
104 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
107 /// \brief Returns the address the GlobalVariable should be written into. The
108 /// GVMemoryBlock object prefixes that.
109 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
110 Type *ElTy = GV->getValueType();
111 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
112 void *RawMemory = ::operator new(
113 alignTo(sizeof(GVMemoryBlock), TD.getPreferredAlignment(GV)) + GVSize);
114 new(RawMemory) GVMemoryBlock(GV);
115 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
118 void deleted() override {
119 // We allocated with operator new and with some extra memory hanging off the
120 // end, so don't just delete this. I'm not sure if this is actually
122 this->~GVMemoryBlock();
123 ::operator delete(this);
126 } // anonymous namespace
128 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
129 return GVMemoryBlock::Create(GV, getDataLayout());
132 void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
133 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
137 ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
138 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
141 void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
142 llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
145 bool ExecutionEngine::removeModule(Module *M) {
146 for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
147 Module *Found = I->get();
151 clearGlobalMappingsFromModule(M);
158 Function *ExecutionEngine::FindFunctionNamed(StringRef FnName) {
159 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
160 Function *F = Modules[i]->getFunction(FnName);
161 if (F && !F->isDeclaration())
167 GlobalVariable *ExecutionEngine::FindGlobalVariableNamed(StringRef Name, bool AllowInternal) {
168 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
169 GlobalVariable *GV = Modules[i]->getGlobalVariable(Name,AllowInternal);
170 if (GV && !GV->isDeclaration())
176 uint64_t ExecutionEngineState::RemoveMapping(StringRef Name) {
177 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(Name);
180 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
182 if (I == GlobalAddressMap.end())
185 GlobalAddressReverseMap.erase(I->second);
187 GlobalAddressMap.erase(I);
193 std::string ExecutionEngine::getMangledName(const GlobalValue *GV) {
194 assert(GV->hasName() && "Global must have name.");
196 MutexGuard locked(lock);
197 SmallString<128> FullName;
199 const DataLayout &DL =
200 GV->getParent()->getDataLayout().isDefault()
202 : GV->getParent()->getDataLayout();
204 Mangler::getNameWithPrefix(FullName, GV->getName(), DL);
205 return FullName.str();
208 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
209 MutexGuard locked(lock);
210 addGlobalMapping(getMangledName(GV), (uint64_t) Addr);
213 void ExecutionEngine::addGlobalMapping(StringRef Name, uint64_t Addr) {
214 MutexGuard locked(lock);
216 assert(!Name.empty() && "Empty GlobalMapping symbol name!");
218 DEBUG(dbgs() << "JIT: Map \'" << Name << "\' to [" << Addr << "]\n";);
219 uint64_t &CurVal = EEState.getGlobalAddressMap()[Name];
220 assert((!CurVal || !Addr) && "GlobalMapping already established!");
223 // If we are using the reverse mapping, add it too.
224 if (!EEState.getGlobalAddressReverseMap().empty()) {
225 std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
226 assert((!V.empty() || !Name.empty()) &&
227 "GlobalMapping already established!");
232 void ExecutionEngine::clearAllGlobalMappings() {
233 MutexGuard locked(lock);
235 EEState.getGlobalAddressMap().clear();
236 EEState.getGlobalAddressReverseMap().clear();
239 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
240 MutexGuard locked(lock);
242 for (GlobalObject &GO : M->global_objects())
243 EEState.RemoveMapping(getMangledName(&GO));
246 uint64_t ExecutionEngine::updateGlobalMapping(const GlobalValue *GV,
248 MutexGuard locked(lock);
249 return updateGlobalMapping(getMangledName(GV), (uint64_t) Addr);
252 uint64_t ExecutionEngine::updateGlobalMapping(StringRef Name, uint64_t Addr) {
253 MutexGuard locked(lock);
255 ExecutionEngineState::GlobalAddressMapTy &Map =
256 EEState.getGlobalAddressMap();
258 // Deleting from the mapping?
260 return EEState.RemoveMapping(Name);
262 uint64_t &CurVal = Map[Name];
263 uint64_t OldVal = CurVal;
265 if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
266 EEState.getGlobalAddressReverseMap().erase(CurVal);
269 // If we are using the reverse mapping, add it too.
270 if (!EEState.getGlobalAddressReverseMap().empty()) {
271 std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
272 assert((!V.empty() || !Name.empty()) &&
273 "GlobalMapping already established!");
279 uint64_t ExecutionEngine::getAddressToGlobalIfAvailable(StringRef S) {
280 MutexGuard locked(lock);
281 uint64_t Address = 0;
282 ExecutionEngineState::GlobalAddressMapTy::iterator I =
283 EEState.getGlobalAddressMap().find(S);
284 if (I != EEState.getGlobalAddressMap().end())
290 void *ExecutionEngine::getPointerToGlobalIfAvailable(StringRef S) {
291 MutexGuard locked(lock);
292 if (void* Address = (void *) getAddressToGlobalIfAvailable(S))
297 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
298 MutexGuard locked(lock);
299 return getPointerToGlobalIfAvailable(getMangledName(GV));
302 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
303 MutexGuard locked(lock);
305 // If we haven't computed the reverse mapping yet, do so first.
306 if (EEState.getGlobalAddressReverseMap().empty()) {
307 for (ExecutionEngineState::GlobalAddressMapTy::iterator
308 I = EEState.getGlobalAddressMap().begin(),
309 E = EEState.getGlobalAddressMap().end(); I != E; ++I) {
310 StringRef Name = I->first();
311 uint64_t Addr = I->second;
312 EEState.getGlobalAddressReverseMap().insert(std::make_pair(
317 std::map<uint64_t, std::string>::iterator I =
318 EEState.getGlobalAddressReverseMap().find((uint64_t) Addr);
320 if (I != EEState.getGlobalAddressReverseMap().end()) {
321 StringRef Name = I->second;
322 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
323 if (GlobalValue *GV = Modules[i]->getNamedValue(Name))
331 std::unique_ptr<char[]> Array;
332 std::vector<std::unique_ptr<char[]>> Values;
334 /// Turn a vector of strings into a nice argv style array of pointers to null
335 /// terminated strings.
336 void *reset(LLVMContext &C, ExecutionEngine *EE,
337 const std::vector<std::string> &InputArgv);
339 } // anonymous namespace
340 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
341 const std::vector<std::string> &InputArgv) {
342 Values.clear(); // Free the old contents.
343 Values.reserve(InputArgv.size());
344 unsigned PtrSize = EE->getDataLayout().getPointerSize();
345 Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
347 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array.get() << "\n");
348 Type *SBytePtr = Type::getInt8PtrTy(C);
350 for (unsigned i = 0; i != InputArgv.size(); ++i) {
351 unsigned Size = InputArgv[i].size()+1;
352 auto Dest = make_unique<char[]>(Size);
353 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest.get() << "\n");
355 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
358 // Endian safe: Array[i] = (PointerTy)Dest;
359 EE->StoreValueToMemory(PTOGV(Dest.get()),
360 (GenericValue*)(&Array[i*PtrSize]), SBytePtr);
361 Values.push_back(std::move(Dest));
365 EE->StoreValueToMemory(PTOGV(nullptr),
366 (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
371 void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
373 StringRef Name(isDtors ? "llvm.global_dtors" : "llvm.global_ctors");
374 GlobalVariable *GV = module.getNamedGlobal(Name);
376 // If this global has internal linkage, or if it has a use, then it must be
377 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
378 // this is the case, don't execute any of the global ctors, __main will do
380 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
382 // Should be an array of '{ i32, void ()* }' structs. The first value is
383 // the init priority, which we ignore.
384 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
387 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
388 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
391 Constant *FP = CS->getOperand(1);
392 if (FP->isNullValue())
393 continue; // Found a sentinal value, ignore.
395 // Strip off constant expression casts.
396 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
398 FP = CE->getOperand(0);
400 // Execute the ctor/dtor function!
401 if (Function *F = dyn_cast<Function>(FP))
402 runFunction(F, None);
404 // FIXME: It is marginally lame that we just do nothing here if we see an
405 // entry we don't recognize. It might not be unreasonable for the verifier
406 // to not even allow this and just assert here.
410 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
411 // Execute global ctors/dtors for each module in the program.
412 for (std::unique_ptr<Module> &M : Modules)
413 runStaticConstructorsDestructors(*M, isDtors);
417 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
418 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
419 unsigned PtrSize = EE->getDataLayout().getPointerSize();
420 for (unsigned i = 0; i < PtrSize; ++i)
421 if (*(i + (uint8_t*)Loc))
427 int ExecutionEngine::runFunctionAsMain(Function *Fn,
428 const std::vector<std::string> &argv,
429 const char * const * envp) {
430 std::vector<GenericValue> GVArgs;
432 GVArgc.IntVal = APInt(32, argv.size());
435 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
436 FunctionType *FTy = Fn->getFunctionType();
437 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
439 // Check the argument types.
441 report_fatal_error("Invalid number of arguments of main() supplied");
442 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
443 report_fatal_error("Invalid type for third argument of main() supplied");
444 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
445 report_fatal_error("Invalid type for second argument of main() supplied");
446 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
447 report_fatal_error("Invalid type for first argument of main() supplied");
448 if (!FTy->getReturnType()->isIntegerTy() &&
449 !FTy->getReturnType()->isVoidTy())
450 report_fatal_error("Invalid return type of main() supplied");
455 GVArgs.push_back(GVArgc); // Arg #0 = argc.
458 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
459 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
460 "argv[0] was null after CreateArgv");
462 std::vector<std::string> EnvVars;
463 for (unsigned i = 0; envp[i]; ++i)
464 EnvVars.emplace_back(envp[i]);
466 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
471 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
474 EngineBuilder::EngineBuilder() : EngineBuilder(nullptr) {}
476 EngineBuilder::EngineBuilder(std::unique_ptr<Module> M)
477 : M(std::move(M)), WhichEngine(EngineKind::Either), ErrorStr(nullptr),
478 OptLevel(CodeGenOpt::Default), MemMgr(nullptr), Resolver(nullptr),
479 CMModel(CodeModel::JITDefault), UseOrcMCJITReplacement(false) {
480 // IR module verification is enabled by default in debug builds, and disabled
481 // by default in release builds.
483 VerifyModules = true;
485 VerifyModules = false;
489 EngineBuilder::~EngineBuilder() = default;
491 EngineBuilder &EngineBuilder::setMCJITMemoryManager(
492 std::unique_ptr<RTDyldMemoryManager> mcjmm) {
493 auto SharedMM = std::shared_ptr<RTDyldMemoryManager>(std::move(mcjmm));
500 EngineBuilder::setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM) {
501 MemMgr = std::shared_ptr<MCJITMemoryManager>(std::move(MM));
506 EngineBuilder::setSymbolResolver(std::unique_ptr<JITSymbolResolver> SR) {
507 Resolver = std::shared_ptr<JITSymbolResolver>(std::move(SR));
511 ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
512 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
514 // Make sure we can resolve symbols in the program as well. The zero arg
515 // to the function tells DynamicLibrary to load the program, not a library.
516 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
519 // If the user specified a memory manager but didn't specify which engine to
520 // create, we assume they only want the JIT, and we fail if they only want
523 if (WhichEngine & EngineKind::JIT)
524 WhichEngine = EngineKind::JIT;
527 *ErrorStr = "Cannot create an interpreter with a memory manager.";
532 // Unless the interpreter was explicitly selected or the JIT is not linked,
534 if ((WhichEngine & EngineKind::JIT) && TheTM) {
535 Triple TT(M->getTargetTriple());
536 if (!TM->getTarget().hasJIT()) {
537 errs() << "WARNING: This target JIT is not designed for the host"
538 << " you are running. If bad things happen, please choose"
539 << " a different -march switch.\n";
542 ExecutionEngine *EE = nullptr;
543 if (ExecutionEngine::OrcMCJITReplacementCtor && UseOrcMCJITReplacement) {
544 EE = ExecutionEngine::OrcMCJITReplacementCtor(ErrorStr, std::move(MemMgr),
547 EE->addModule(std::move(M));
548 } else if (ExecutionEngine::MCJITCtor)
549 EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MemMgr),
550 std::move(Resolver), std::move(TheTM));
553 EE->setVerifyModules(VerifyModules);
558 // If we can't make a JIT and we didn't request one specifically, try making
559 // an interpreter instead.
560 if (WhichEngine & EngineKind::Interpreter) {
561 if (ExecutionEngine::InterpCtor)
562 return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
564 *ErrorStr = "Interpreter has not been linked in.";
568 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
570 *ErrorStr = "JIT has not been linked in.";
576 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
577 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
578 return getPointerToFunction(F);
580 MutexGuard locked(lock);
581 if (void* P = getPointerToGlobalIfAvailable(GV))
584 // Global variable might have been added since interpreter started.
585 if (GlobalVariable *GVar =
586 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
587 EmitGlobalVariable(GVar);
589 llvm_unreachable("Global hasn't had an address allocated yet!");
591 return getPointerToGlobalIfAvailable(GV);
594 /// \brief Converts a Constant* into a GenericValue, including handling of
595 /// ConstantExpr values.
596 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
597 // If its undefined, return the garbage.
598 if (isa<UndefValue>(C)) {
600 switch (C->getType()->getTypeID()) {
603 case Type::IntegerTyID:
604 case Type::X86_FP80TyID:
605 case Type::FP128TyID:
606 case Type::PPC_FP128TyID:
607 // Although the value is undefined, we still have to construct an APInt
608 // with the correct bit width.
609 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
611 case Type::StructTyID: {
612 // if the whole struct is 'undef' just reserve memory for the value.
613 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
614 unsigned int elemNum = STy->getNumElements();
615 Result.AggregateVal.resize(elemNum);
616 for (unsigned int i = 0; i < elemNum; ++i) {
617 Type *ElemTy = STy->getElementType(i);
618 if (ElemTy->isIntegerTy())
619 Result.AggregateVal[i].IntVal =
620 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
621 else if (ElemTy->isAggregateType()) {
622 const Constant *ElemUndef = UndefValue::get(ElemTy);
623 Result.AggregateVal[i] = getConstantValue(ElemUndef);
629 case Type::VectorTyID:
630 // if the whole vector is 'undef' just reserve memory for the value.
631 auto* VTy = dyn_cast<VectorType>(C->getType());
632 Type *ElemTy = VTy->getElementType();
633 unsigned int elemNum = VTy->getNumElements();
634 Result.AggregateVal.resize(elemNum);
635 if (ElemTy->isIntegerTy())
636 for (unsigned int i = 0; i < elemNum; ++i)
637 Result.AggregateVal[i].IntVal =
638 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
644 // Otherwise, if the value is a ConstantExpr...
645 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
646 Constant *Op0 = CE->getOperand(0);
647 switch (CE->getOpcode()) {
648 case Instruction::GetElementPtr: {
650 GenericValue Result = getConstantValue(Op0);
651 APInt Offset(DL.getPointerSizeInBits(), 0);
652 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, Offset);
654 char* tmp = (char*) Result.PointerVal;
655 Result = PTOGV(tmp + Offset.getSExtValue());
658 case Instruction::Trunc: {
659 GenericValue GV = getConstantValue(Op0);
660 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
661 GV.IntVal = GV.IntVal.trunc(BitWidth);
664 case Instruction::ZExt: {
665 GenericValue GV = getConstantValue(Op0);
666 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
667 GV.IntVal = GV.IntVal.zext(BitWidth);
670 case Instruction::SExt: {
671 GenericValue GV = getConstantValue(Op0);
672 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
673 GV.IntVal = GV.IntVal.sext(BitWidth);
676 case Instruction::FPTrunc: {
678 GenericValue GV = getConstantValue(Op0);
679 GV.FloatVal = float(GV.DoubleVal);
682 case Instruction::FPExt:{
684 GenericValue GV = getConstantValue(Op0);
685 GV.DoubleVal = double(GV.FloatVal);
688 case Instruction::UIToFP: {
689 GenericValue GV = getConstantValue(Op0);
690 if (CE->getType()->isFloatTy())
691 GV.FloatVal = float(GV.IntVal.roundToDouble());
692 else if (CE->getType()->isDoubleTy())
693 GV.DoubleVal = GV.IntVal.roundToDouble();
694 else if (CE->getType()->isX86_FP80Ty()) {
695 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended());
696 (void)apf.convertFromAPInt(GV.IntVal,
698 APFloat::rmNearestTiesToEven);
699 GV.IntVal = apf.bitcastToAPInt();
703 case Instruction::SIToFP: {
704 GenericValue GV = getConstantValue(Op0);
705 if (CE->getType()->isFloatTy())
706 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
707 else if (CE->getType()->isDoubleTy())
708 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
709 else if (CE->getType()->isX86_FP80Ty()) {
710 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended());
711 (void)apf.convertFromAPInt(GV.IntVal,
713 APFloat::rmNearestTiesToEven);
714 GV.IntVal = apf.bitcastToAPInt();
718 case Instruction::FPToUI: // double->APInt conversion handles sign
719 case Instruction::FPToSI: {
720 GenericValue GV = getConstantValue(Op0);
721 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
722 if (Op0->getType()->isFloatTy())
723 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
724 else if (Op0->getType()->isDoubleTy())
725 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
726 else if (Op0->getType()->isX86_FP80Ty()) {
727 APFloat apf = APFloat(APFloat::x87DoubleExtended(), GV.IntVal);
730 (void)apf.convertToInteger(&v, BitWidth,
731 CE->getOpcode()==Instruction::FPToSI,
732 APFloat::rmTowardZero, &ignored);
733 GV.IntVal = v; // endian?
737 case Instruction::PtrToInt: {
738 GenericValue GV = getConstantValue(Op0);
739 uint32_t PtrWidth = DL.getTypeSizeInBits(Op0->getType());
740 assert(PtrWidth <= 64 && "Bad pointer width");
741 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
742 uint32_t IntWidth = DL.getTypeSizeInBits(CE->getType());
743 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
746 case Instruction::IntToPtr: {
747 GenericValue GV = getConstantValue(Op0);
748 uint32_t PtrWidth = DL.getTypeSizeInBits(CE->getType());
749 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
750 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
751 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
754 case Instruction::BitCast: {
755 GenericValue GV = getConstantValue(Op0);
756 Type* DestTy = CE->getType();
757 switch (Op0->getType()->getTypeID()) {
758 default: llvm_unreachable("Invalid bitcast operand");
759 case Type::IntegerTyID:
760 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
761 if (DestTy->isFloatTy())
762 GV.FloatVal = GV.IntVal.bitsToFloat();
763 else if (DestTy->isDoubleTy())
764 GV.DoubleVal = GV.IntVal.bitsToDouble();
766 case Type::FloatTyID:
767 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
768 GV.IntVal = APInt::floatToBits(GV.FloatVal);
770 case Type::DoubleTyID:
771 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
772 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
774 case Type::PointerTyID:
775 assert(DestTy->isPointerTy() && "Invalid bitcast");
776 break; // getConstantValue(Op0) above already converted it
780 case Instruction::Add:
781 case Instruction::FAdd:
782 case Instruction::Sub:
783 case Instruction::FSub:
784 case Instruction::Mul:
785 case Instruction::FMul:
786 case Instruction::UDiv:
787 case Instruction::SDiv:
788 case Instruction::URem:
789 case Instruction::SRem:
790 case Instruction::And:
791 case Instruction::Or:
792 case Instruction::Xor: {
793 GenericValue LHS = getConstantValue(Op0);
794 GenericValue RHS = getConstantValue(CE->getOperand(1));
796 switch (CE->getOperand(0)->getType()->getTypeID()) {
797 default: llvm_unreachable("Bad add type!");
798 case Type::IntegerTyID:
799 switch (CE->getOpcode()) {
800 default: llvm_unreachable("Invalid integer opcode");
801 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
802 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
803 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
804 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
805 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
806 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
807 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
808 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
809 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
810 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
813 case Type::FloatTyID:
814 switch (CE->getOpcode()) {
815 default: llvm_unreachable("Invalid float opcode");
816 case Instruction::FAdd:
817 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
818 case Instruction::FSub:
819 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
820 case Instruction::FMul:
821 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
822 case Instruction::FDiv:
823 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
824 case Instruction::FRem:
825 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
828 case Type::DoubleTyID:
829 switch (CE->getOpcode()) {
830 default: llvm_unreachable("Invalid double opcode");
831 case Instruction::FAdd:
832 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
833 case Instruction::FSub:
834 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
835 case Instruction::FMul:
836 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
837 case Instruction::FDiv:
838 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
839 case Instruction::FRem:
840 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
843 case Type::X86_FP80TyID:
844 case Type::PPC_FP128TyID:
845 case Type::FP128TyID: {
846 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
847 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
848 switch (CE->getOpcode()) {
849 default: llvm_unreachable("Invalid long double opcode");
850 case Instruction::FAdd:
851 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
852 GV.IntVal = apfLHS.bitcastToAPInt();
854 case Instruction::FSub:
855 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
856 APFloat::rmNearestTiesToEven);
857 GV.IntVal = apfLHS.bitcastToAPInt();
859 case Instruction::FMul:
860 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
861 APFloat::rmNearestTiesToEven);
862 GV.IntVal = apfLHS.bitcastToAPInt();
864 case Instruction::FDiv:
865 apfLHS.divide(APFloat(Sem, RHS.IntVal),
866 APFloat::rmNearestTiesToEven);
867 GV.IntVal = apfLHS.bitcastToAPInt();
869 case Instruction::FRem:
870 apfLHS.mod(APFloat(Sem, RHS.IntVal));
871 GV.IntVal = apfLHS.bitcastToAPInt();
883 SmallString<256> Msg;
884 raw_svector_ostream OS(Msg);
885 OS << "ConstantExpr not handled: " << *CE;
886 report_fatal_error(OS.str());
889 // Otherwise, we have a simple constant.
891 switch (C->getType()->getTypeID()) {
892 case Type::FloatTyID:
893 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
895 case Type::DoubleTyID:
896 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
898 case Type::X86_FP80TyID:
899 case Type::FP128TyID:
900 case Type::PPC_FP128TyID:
901 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
903 case Type::IntegerTyID:
904 Result.IntVal = cast<ConstantInt>(C)->getValue();
906 case Type::PointerTyID:
907 if (isa<ConstantPointerNull>(C))
908 Result.PointerVal = nullptr;
909 else if (const Function *F = dyn_cast<Function>(C))
910 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
911 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
912 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
914 llvm_unreachable("Unknown constant pointer type!");
916 case Type::VectorTyID: {
919 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
920 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
921 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
924 elemNum = CDV->getNumElements();
925 ElemTy = CDV->getElementType();
926 } else if (CV || CAZ) {
927 VectorType* VTy = dyn_cast<VectorType>(C->getType());
928 elemNum = VTy->getNumElements();
929 ElemTy = VTy->getElementType();
931 llvm_unreachable("Unknown constant vector type!");
934 Result.AggregateVal.resize(elemNum);
935 // Check if vector holds floats.
936 if(ElemTy->isFloatTy()) {
938 GenericValue floatZero;
939 floatZero.FloatVal = 0.f;
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].FloatVal = cast<ConstantFP>(
948 CV->getOperand(i))->getValueAPF().convertToFloat();
952 for (unsigned i = 0; i < elemNum; ++i)
953 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
957 // Check if vector holds doubles.
958 if (ElemTy->isDoubleTy()) {
960 GenericValue doubleZero;
961 doubleZero.DoubleVal = 0.0;
962 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
967 for (unsigned i = 0; i < elemNum; ++i)
968 if (!isa<UndefValue>(CV->getOperand(i)))
969 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
970 CV->getOperand(i))->getValueAPF().convertToDouble();
974 for (unsigned i = 0; i < elemNum; ++i)
975 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
979 // Check if vector holds integers.
980 if (ElemTy->isIntegerTy()) {
982 GenericValue intZero;
983 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
984 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
989 for (unsigned i = 0; i < elemNum; ++i)
990 if (!isa<UndefValue>(CV->getOperand(i)))
991 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
992 CV->getOperand(i))->getValue();
994 Result.AggregateVal[i].IntVal =
995 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
1000 for (unsigned i = 0; i < elemNum; ++i)
1001 Result.AggregateVal[i].IntVal = APInt(
1002 CDV->getElementType()->getPrimitiveSizeInBits(),
1003 CDV->getElementAsInteger(i));
1007 llvm_unreachable("Unknown constant pointer type!");
1012 SmallString<256> Msg;
1013 raw_svector_ostream OS(Msg);
1014 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
1015 report_fatal_error(OS.str());
1021 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
1022 /// with the integer held in IntVal.
1023 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
1024 unsigned StoreBytes) {
1025 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
1026 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
1028 if (sys::IsLittleEndianHost) {
1029 // Little-endian host - the source is ordered from LSB to MSB. Order the
1030 // destination from LSB to MSB: Do a straight copy.
1031 memcpy(Dst, Src, StoreBytes);
1033 // Big-endian host - the source is an array of 64 bit words ordered from
1034 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
1035 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
1036 while (StoreBytes > sizeof(uint64_t)) {
1037 StoreBytes -= sizeof(uint64_t);
1038 // May not be aligned so use memcpy.
1039 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
1040 Src += sizeof(uint64_t);
1043 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1047 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
1048 GenericValue *Ptr, Type *Ty) {
1049 const unsigned StoreBytes = getDataLayout().getTypeStoreSize(Ty);
1051 switch (Ty->getTypeID()) {
1053 dbgs() << "Cannot store value of type " << *Ty << "!\n";
1055 case Type::IntegerTyID:
1056 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
1058 case Type::FloatTyID:
1059 *((float*)Ptr) = Val.FloatVal;
1061 case Type::DoubleTyID:
1062 *((double*)Ptr) = Val.DoubleVal;
1064 case Type::X86_FP80TyID:
1065 memcpy(Ptr, Val.IntVal.getRawData(), 10);
1067 case Type::PointerTyID:
1068 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1069 if (StoreBytes != sizeof(PointerTy))
1070 memset(&(Ptr->PointerVal), 0, StoreBytes);
1072 *((PointerTy*)Ptr) = Val.PointerVal;
1074 case Type::VectorTyID:
1075 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1076 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1077 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1078 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1079 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1080 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1081 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1082 StoreIntToMemory(Val.AggregateVal[i].IntVal,
1083 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1089 if (sys::IsLittleEndianHost != getDataLayout().isLittleEndian())
1090 // Host and target are different endian - reverse the stored bytes.
1091 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1094 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1095 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1096 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1097 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
1098 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1099 const_cast<uint64_t *>(IntVal.getRawData()));
1101 if (sys::IsLittleEndianHost)
1102 // Little-endian host - the destination must be ordered from LSB to MSB.
1103 // The source is ordered from LSB to MSB: Do a straight copy.
1104 memcpy(Dst, Src, LoadBytes);
1106 // Big-endian - the destination is an array of 64 bit words ordered from
1107 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1108 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1110 while (LoadBytes > sizeof(uint64_t)) {
1111 LoadBytes -= sizeof(uint64_t);
1112 // May not be aligned so use memcpy.
1113 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1114 Dst += sizeof(uint64_t);
1117 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1123 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
1126 const unsigned LoadBytes = getDataLayout().getTypeStoreSize(Ty);
1128 switch (Ty->getTypeID()) {
1129 case Type::IntegerTyID:
1130 // An APInt with all words initially zero.
1131 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1132 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1134 case Type::FloatTyID:
1135 Result.FloatVal = *((float*)Ptr);
1137 case Type::DoubleTyID:
1138 Result.DoubleVal = *((double*)Ptr);
1140 case Type::PointerTyID:
1141 Result.PointerVal = *((PointerTy*)Ptr);
1143 case Type::X86_FP80TyID: {
1144 // This is endian dependent, but it will only work on x86 anyway.
1145 // FIXME: Will not trap if loading a signaling NaN.
1148 Result.IntVal = APInt(80, y);
1151 case Type::VectorTyID: {
1152 auto *VT = cast<VectorType>(Ty);
1153 Type *ElemT = VT->getElementType();
1154 const unsigned numElems = VT->getNumElements();
1155 if (ElemT->isFloatTy()) {
1156 Result.AggregateVal.resize(numElems);
1157 for (unsigned i = 0; i < numElems; ++i)
1158 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1160 if (ElemT->isDoubleTy()) {
1161 Result.AggregateVal.resize(numElems);
1162 for (unsigned i = 0; i < numElems; ++i)
1163 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1165 if (ElemT->isIntegerTy()) {
1166 GenericValue intZero;
1167 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1168 intZero.IntVal = APInt(elemBitWidth, 0);
1169 Result.AggregateVal.resize(numElems, intZero);
1170 for (unsigned i = 0; i < numElems; ++i)
1171 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1172 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1177 SmallString<256> Msg;
1178 raw_svector_ostream OS(Msg);
1179 OS << "Cannot load value of type " << *Ty << "!";
1180 report_fatal_error(OS.str());
1184 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
1185 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
1186 DEBUG(Init->dump());
1187 if (isa<UndefValue>(Init))
1190 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
1191 unsigned ElementSize =
1192 getDataLayout().getTypeAllocSize(CP->getType()->getElementType());
1193 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1194 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1198 if (isa<ConstantAggregateZero>(Init)) {
1199 memset(Addr, 0, (size_t)getDataLayout().getTypeAllocSize(Init->getType()));
1203 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
1204 unsigned ElementSize =
1205 getDataLayout().getTypeAllocSize(CPA->getType()->getElementType());
1206 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1207 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1211 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
1212 const StructLayout *SL =
1213 getDataLayout().getStructLayout(cast<StructType>(CPS->getType()));
1214 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1215 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1219 if (const ConstantDataSequential *CDS =
1220 dyn_cast<ConstantDataSequential>(Init)) {
1221 // CDS is already laid out in host memory order.
1222 StringRef Data = CDS->getRawDataValues();
1223 memcpy(Addr, Data.data(), Data.size());
1227 if (Init->getType()->isFirstClassType()) {
1228 GenericValue Val = getConstantValue(Init);
1229 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1233 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1234 llvm_unreachable("Unknown constant type to initialize memory with!");
1237 /// EmitGlobals - Emit all of the global variables to memory, storing their
1238 /// addresses into GlobalAddress. This must make sure to copy the contents of
1239 /// their initializers into the memory.
1240 void ExecutionEngine::emitGlobals() {
1241 // Loop over all of the global variables in the program, allocating the memory
1242 // to hold them. If there is more than one module, do a prepass over globals
1243 // to figure out how the different modules should link together.
1244 std::map<std::pair<std::string, Type*>,
1245 const GlobalValue*> LinkedGlobalsMap;
1247 if (Modules.size() != 1) {
1248 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1249 Module &M = *Modules[m];
1250 for (const auto &GV : M.globals()) {
1251 if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1252 GV.hasAppendingLinkage() || !GV.hasName())
1253 continue;// Ignore external globals and globals with internal linkage.
1255 const GlobalValue *&GVEntry =
1256 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
1258 // If this is the first time we've seen this global, it is the canonical
1265 // If the existing global is strong, never replace it.
1266 if (GVEntry->hasExternalLinkage())
1269 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1270 // symbol. FIXME is this right for common?
1271 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1277 std::vector<const GlobalValue*> NonCanonicalGlobals;
1278 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1279 Module &M = *Modules[m];
1280 for (const auto &GV : M.globals()) {
1281 // In the multi-module case, see what this global maps to.
1282 if (!LinkedGlobalsMap.empty()) {
1283 if (const GlobalValue *GVEntry =
1284 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
1285 // If something else is the canonical global, ignore this one.
1286 if (GVEntry != &GV) {
1287 NonCanonicalGlobals.push_back(&GV);
1293 if (!GV.isDeclaration()) {
1294 addGlobalMapping(&GV, getMemoryForGV(&GV));
1296 // External variable reference. Try to use the dynamic loader to
1297 // get a pointer to it.
1299 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1300 addGlobalMapping(&GV, SymAddr);
1302 report_fatal_error("Could not resolve external global address: "
1308 // If there are multiple modules, map the non-canonical globals to their
1309 // canonical location.
1310 if (!NonCanonicalGlobals.empty()) {
1311 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1312 const GlobalValue *GV = NonCanonicalGlobals[i];
1313 const GlobalValue *CGV =
1314 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1315 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1316 assert(Ptr && "Canonical global wasn't codegen'd!");
1317 addGlobalMapping(GV, Ptr);
1321 // Now that all of the globals are set up in memory, loop through them all
1322 // and initialize their contents.
1323 for (const auto &GV : M.globals()) {
1324 if (!GV.isDeclaration()) {
1325 if (!LinkedGlobalsMap.empty()) {
1326 if (const GlobalValue *GVEntry =
1327 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1328 if (GVEntry != &GV) // Not the canonical variable.
1331 EmitGlobalVariable(&GV);
1337 // EmitGlobalVariable - This method emits the specified global variable to the
1338 // address specified in GlobalAddresses, or allocates new memory if it's not
1339 // already in the map.
1340 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1341 void *GA = getPointerToGlobalIfAvailable(GV);
1344 // If it's not already specified, allocate memory for the global.
1345 GA = getMemoryForGV(GV);
1347 // If we failed to allocate memory for this global, return.
1350 addGlobalMapping(GV, GA);
1353 // Don't initialize if it's thread local, let the client do it.
1354 if (!GV->isThreadLocal())
1355 InitializeMemory(GV->getInitializer(), GA);
1357 Type *ElTy = GV->getValueType();
1358 size_t GVSize = (size_t)getDataLayout().getTypeAllocSize(ElTy);
1359 NumInitBytes += (unsigned)GVSize;