Path: blob/main/contrib/llvm-project/llvm/lib/ExecutionEngine/ExecutionEngine.cpp
35232 views
//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file defines the common interface used by the various execution engine9// subclasses.10//11// FIXME: This file needs to be updated to support scalable vectors12//13//===----------------------------------------------------------------------===//1415#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/MC/TargetRegistry.h"31#include "llvm/Object/Archive.h"32#include "llvm/Object/ObjectFile.h"33#include "llvm/Support/Debug.h"34#include "llvm/Support/DynamicLibrary.h"35#include "llvm/Support/ErrorHandling.h"36#include "llvm/Support/raw_ostream.h"37#include "llvm/Target/TargetMachine.h"38#include "llvm/TargetParser/Host.h"39#include <cmath>40#include <cstring>41#include <mutex>42using namespace llvm;4344#define DEBUG_TYPE "jit"4546STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");47STATISTIC(NumGlobals , "Number of global vars initialized");4849ExecutionEngine *(*ExecutionEngine::MCJITCtor)(50std::unique_ptr<Module> M, std::string *ErrorStr,51std::shared_ptr<MCJITMemoryManager> MemMgr,52std::shared_ptr<LegacyJITSymbolResolver> Resolver,53std::unique_ptr<TargetMachine> TM) = nullptr;5455ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M,56std::string *ErrorStr) =nullptr;5758void JITEventListener::anchor() {}5960void ObjectCache::anchor() {}6162void ExecutionEngine::Init(std::unique_ptr<Module> M) {63CompilingLazily = false;64GVCompilationDisabled = false;65SymbolSearchingDisabled = false;6667// IR module verification is enabled by default in debug builds, and disabled68// by default in release builds.69#ifndef NDEBUG70VerifyModules = true;71#else72VerifyModules = false;73#endif7475assert(M && "Module is null?");76Modules.push_back(std::move(M));77}7879ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)80: DL(M->getDataLayout()), LazyFunctionCreator(nullptr) {81Init(std::move(M));82}8384ExecutionEngine::ExecutionEngine(DataLayout DL, std::unique_ptr<Module> M)85: DL(std::move(DL)), LazyFunctionCreator(nullptr) {86Init(std::move(M));87}8889ExecutionEngine::~ExecutionEngine() {90clearAllGlobalMappings();91}9293namespace {94/// Helper class which uses a value handler to automatically deletes the95/// memory block when the GlobalVariable is destroyed.96class GVMemoryBlock final : public CallbackVH {97GVMemoryBlock(const GlobalVariable *GV)98: CallbackVH(const_cast<GlobalVariable*>(GV)) {}99100public:101/// Returns the address the GlobalVariable should be written into. The102/// GVMemoryBlock object prefixes that.103static char *Create(const GlobalVariable *GV, const DataLayout& TD) {104Type *ElTy = GV->getValueType();105size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);106void *RawMemory = ::operator new(107alignTo(sizeof(GVMemoryBlock), TD.getPreferredAlign(GV)) + GVSize);108new(RawMemory) GVMemoryBlock(GV);109return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);110}111112void deleted() override {113// We allocated with operator new and with some extra memory hanging off the114// end, so don't just delete this. I'm not sure if this is actually115// required.116this->~GVMemoryBlock();117::operator delete(this);118}119};120} // anonymous namespace121122char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {123return GVMemoryBlock::Create(GV, getDataLayout());124}125126void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {127llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");128}129130void131ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {132llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");133}134135void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {136llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");137}138139bool ExecutionEngine::removeModule(Module *M) {140for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {141Module *Found = I->get();142if (Found == M) {143I->release();144Modules.erase(I);145clearGlobalMappingsFromModule(M);146return true;147}148}149return false;150}151152Function *ExecutionEngine::FindFunctionNamed(StringRef FnName) {153for (const auto &M : Modules) {154Function *F = M->getFunction(FnName);155if (F && !F->isDeclaration())156return F;157}158return nullptr;159}160161GlobalVariable *ExecutionEngine::FindGlobalVariableNamed(StringRef Name, bool AllowInternal) {162for (const auto &M : Modules) {163GlobalVariable *GV = M->getGlobalVariable(Name, AllowInternal);164if (GV && !GV->isDeclaration())165return GV;166}167return nullptr;168}169170uint64_t ExecutionEngineState::RemoveMapping(StringRef Name) {171GlobalAddressMapTy::iterator I = GlobalAddressMap.find(Name);172uint64_t OldVal;173174// FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the175// GlobalAddressMap.176if (I == GlobalAddressMap.end())177OldVal = 0;178else {179GlobalAddressReverseMap.erase(I->second);180OldVal = I->second;181GlobalAddressMap.erase(I);182}183184return OldVal;185}186187std::string ExecutionEngine::getMangledName(const GlobalValue *GV) {188assert(GV->hasName() && "Global must have name.");189190std::lock_guard<sys::Mutex> locked(lock);191SmallString<128> FullName;192193const DataLayout &DL =194GV->getDataLayout().isDefault()195? getDataLayout()196: GV->getDataLayout();197198Mangler::getNameWithPrefix(FullName, GV->getName(), DL);199return std::string(FullName);200}201202void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {203std::lock_guard<sys::Mutex> locked(lock);204addGlobalMapping(getMangledName(GV), (uint64_t) Addr);205}206207void ExecutionEngine::addGlobalMapping(StringRef Name, uint64_t Addr) {208std::lock_guard<sys::Mutex> locked(lock);209210assert(!Name.empty() && "Empty GlobalMapping symbol name!");211212LLVM_DEBUG(dbgs() << "JIT: Map \'" << Name << "\' to [" << Addr << "]\n";);213uint64_t &CurVal = EEState.getGlobalAddressMap()[Name];214assert((!CurVal || !Addr) && "GlobalMapping already established!");215CurVal = Addr;216217// If we are using the reverse mapping, add it too.218if (!EEState.getGlobalAddressReverseMap().empty()) {219std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];220assert((!V.empty() || !Name.empty()) &&221"GlobalMapping already established!");222V = std::string(Name);223}224}225226void ExecutionEngine::clearAllGlobalMappings() {227std::lock_guard<sys::Mutex> locked(lock);228229EEState.getGlobalAddressMap().clear();230EEState.getGlobalAddressReverseMap().clear();231}232233void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {234std::lock_guard<sys::Mutex> locked(lock);235236for (GlobalObject &GO : M->global_objects())237EEState.RemoveMapping(getMangledName(&GO));238}239240uint64_t ExecutionEngine::updateGlobalMapping(const GlobalValue *GV,241void *Addr) {242std::lock_guard<sys::Mutex> locked(lock);243return updateGlobalMapping(getMangledName(GV), (uint64_t) Addr);244}245246uint64_t ExecutionEngine::updateGlobalMapping(StringRef Name, uint64_t Addr) {247std::lock_guard<sys::Mutex> locked(lock);248249ExecutionEngineState::GlobalAddressMapTy &Map =250EEState.getGlobalAddressMap();251252// Deleting from the mapping?253if (!Addr)254return EEState.RemoveMapping(Name);255256uint64_t &CurVal = Map[Name];257uint64_t OldVal = CurVal;258259if (CurVal && !EEState.getGlobalAddressReverseMap().empty())260EEState.getGlobalAddressReverseMap().erase(CurVal);261CurVal = Addr;262263// If we are using the reverse mapping, add it too.264if (!EEState.getGlobalAddressReverseMap().empty()) {265std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];266assert((!V.empty() || !Name.empty()) &&267"GlobalMapping already established!");268V = std::string(Name);269}270return OldVal;271}272273uint64_t ExecutionEngine::getAddressToGlobalIfAvailable(StringRef S) {274std::lock_guard<sys::Mutex> locked(lock);275uint64_t Address = 0;276ExecutionEngineState::GlobalAddressMapTy::iterator I =277EEState.getGlobalAddressMap().find(S);278if (I != EEState.getGlobalAddressMap().end())279Address = I->second;280return Address;281}282283284void *ExecutionEngine::getPointerToGlobalIfAvailable(StringRef S) {285std::lock_guard<sys::Mutex> locked(lock);286if (void* Address = (void *) getAddressToGlobalIfAvailable(S))287return Address;288return nullptr;289}290291void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {292std::lock_guard<sys::Mutex> locked(lock);293return getPointerToGlobalIfAvailable(getMangledName(GV));294}295296const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {297std::lock_guard<sys::Mutex> locked(lock);298299// If we haven't computed the reverse mapping yet, do so first.300if (EEState.getGlobalAddressReverseMap().empty()) {301for (ExecutionEngineState::GlobalAddressMapTy::iterator302I = EEState.getGlobalAddressMap().begin(),303E = EEState.getGlobalAddressMap().end(); I != E; ++I) {304StringRef Name = I->first();305uint64_t Addr = I->second;306EEState.getGlobalAddressReverseMap().insert(307std::make_pair(Addr, std::string(Name)));308}309}310311std::map<uint64_t, std::string>::iterator I =312EEState.getGlobalAddressReverseMap().find((uint64_t) Addr);313314if (I != EEState.getGlobalAddressReverseMap().end()) {315StringRef Name = I->second;316for (const auto &M : Modules)317if (GlobalValue *GV = M->getNamedValue(Name))318return GV;319}320return nullptr;321}322323namespace {324class ArgvArray {325std::unique_ptr<char[]> Array;326std::vector<std::unique_ptr<char[]>> Values;327public:328/// Turn a vector of strings into a nice argv style array of pointers to null329/// terminated strings.330void *reset(LLVMContext &C, ExecutionEngine *EE,331const std::vector<std::string> &InputArgv);332};333} // anonymous namespace334void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,335const std::vector<std::string> &InputArgv) {336Values.clear(); // Free the old contents.337Values.reserve(InputArgv.size());338unsigned PtrSize = EE->getDataLayout().getPointerSize();339Array = std::make_unique<char[]>((InputArgv.size()+1)*PtrSize);340341LLVM_DEBUG(dbgs() << "JIT: ARGV = " << (void *)Array.get() << "\n");342Type *SBytePtr = PointerType::getUnqual(C);343344for (unsigned i = 0; i != InputArgv.size(); ++i) {345unsigned Size = InputArgv[i].size()+1;346auto Dest = std::make_unique<char[]>(Size);347LLVM_DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void *)Dest.get()348<< "\n");349350std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());351Dest[Size-1] = 0;352353// Endian safe: Array[i] = (PointerTy)Dest;354EE->StoreValueToMemory(PTOGV(Dest.get()),355(GenericValue*)(&Array[i*PtrSize]), SBytePtr);356Values.push_back(std::move(Dest));357}358359// Null terminate it360EE->StoreValueToMemory(PTOGV(nullptr),361(GenericValue*)(&Array[InputArgv.size()*PtrSize]),362SBytePtr);363return Array.get();364}365366void ExecutionEngine::runStaticConstructorsDestructors(Module &module,367bool isDtors) {368StringRef Name(isDtors ? "llvm.global_dtors" : "llvm.global_ctors");369GlobalVariable *GV = module.getNamedGlobal(Name);370371// If this global has internal linkage, or if it has a use, then it must be372// an old-style (llvmgcc3) static ctor with __main linked in and in use. If373// this is the case, don't execute any of the global ctors, __main will do374// it.375if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;376377// Should be an array of '{ i32, void ()* }' structs. The first value is378// the init priority, which we ignore.379ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());380if (!InitList)381return;382for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {383ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));384if (!CS) continue;385386Constant *FP = CS->getOperand(1);387if (FP->isNullValue())388continue; // Found a sentinel value, ignore.389390// Strip off constant expression casts.391if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))392if (CE->isCast())393FP = CE->getOperand(0);394395// Execute the ctor/dtor function!396if (Function *F = dyn_cast<Function>(FP))397runFunction(F, std::nullopt);398399// FIXME: It is marginally lame that we just do nothing here if we see an400// entry we don't recognize. It might not be unreasonable for the verifier401// to not even allow this and just assert here.402}403}404405void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {406// Execute global ctors/dtors for each module in the program.407for (std::unique_ptr<Module> &M : Modules)408runStaticConstructorsDestructors(*M, isDtors);409}410411#ifndef NDEBUG412/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.413static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {414unsigned PtrSize = EE->getDataLayout().getPointerSize();415for (unsigned i = 0; i < PtrSize; ++i)416if (*(i + (uint8_t*)Loc))417return false;418return true;419}420#endif421422int ExecutionEngine::runFunctionAsMain(Function *Fn,423const std::vector<std::string> &argv,424const char * const * envp) {425std::vector<GenericValue> GVArgs;426GenericValue GVArgc;427GVArgc.IntVal = APInt(32, argv.size());428429// Check main() type430unsigned NumArgs = Fn->getFunctionType()->getNumParams();431FunctionType *FTy = Fn->getFunctionType();432Type *PPInt8Ty = PointerType::get(Fn->getContext(), 0);433434// Check the argument types.435if (NumArgs > 3)436report_fatal_error("Invalid number of arguments of main() supplied");437if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)438report_fatal_error("Invalid type for third argument of main() supplied");439if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)440report_fatal_error("Invalid type for second argument of main() supplied");441if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))442report_fatal_error("Invalid type for first argument of main() supplied");443if (!FTy->getReturnType()->isIntegerTy() &&444!FTy->getReturnType()->isVoidTy())445report_fatal_error("Invalid return type of main() supplied");446447ArgvArray CArgv;448ArgvArray CEnv;449if (NumArgs) {450GVArgs.push_back(GVArgc); // Arg #0 = argc.451if (NumArgs > 1) {452// Arg #1 = argv.453GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));454assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&455"argv[0] was null after CreateArgv");456if (NumArgs > 2) {457std::vector<std::string> EnvVars;458for (unsigned i = 0; envp[i]; ++i)459EnvVars.emplace_back(envp[i]);460// Arg #2 = envp.461GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));462}463}464}465466return runFunction(Fn, GVArgs).IntVal.getZExtValue();467}468469EngineBuilder::EngineBuilder() : EngineBuilder(nullptr) {}470471EngineBuilder::EngineBuilder(std::unique_ptr<Module> M)472: M(std::move(M)), WhichEngine(EngineKind::Either), ErrorStr(nullptr),473OptLevel(CodeGenOptLevel::Default), MemMgr(nullptr), Resolver(nullptr) {474// IR module verification is enabled by default in debug builds, and disabled475// by default in release builds.476#ifndef NDEBUG477VerifyModules = true;478#else479VerifyModules = false;480#endif481}482483EngineBuilder::~EngineBuilder() = default;484485EngineBuilder &EngineBuilder::setMCJITMemoryManager(486std::unique_ptr<RTDyldMemoryManager> mcjmm) {487auto SharedMM = std::shared_ptr<RTDyldMemoryManager>(std::move(mcjmm));488MemMgr = SharedMM;489Resolver = SharedMM;490return *this;491}492493EngineBuilder&494EngineBuilder::setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM) {495MemMgr = std::shared_ptr<MCJITMemoryManager>(std::move(MM));496return *this;497}498499EngineBuilder &500EngineBuilder::setSymbolResolver(std::unique_ptr<LegacyJITSymbolResolver> SR) {501Resolver = std::shared_ptr<LegacyJITSymbolResolver>(std::move(SR));502return *this;503}504505ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {506std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.507508// Make sure we can resolve symbols in the program as well. The zero arg509// to the function tells DynamicLibrary to load the program, not a library.510if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))511return nullptr;512513// If the user specified a memory manager but didn't specify which engine to514// create, we assume they only want the JIT, and we fail if they only want515// the interpreter.516if (MemMgr) {517if (WhichEngine & EngineKind::JIT)518WhichEngine = EngineKind::JIT;519else {520if (ErrorStr)521*ErrorStr = "Cannot create an interpreter with a memory manager.";522return nullptr;523}524}525526// Unless the interpreter was explicitly selected or the JIT is not linked,527// try making a JIT.528if ((WhichEngine & EngineKind::JIT) && TheTM) {529if (!TM->getTarget().hasJIT()) {530errs() << "WARNING: This target JIT is not designed for the host"531<< " you are running. If bad things happen, please choose"532<< " a different -march switch.\n";533}534535ExecutionEngine *EE = nullptr;536if (ExecutionEngine::MCJITCtor)537EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MemMgr),538std::move(Resolver), std::move(TheTM));539540if (EE) {541EE->setVerifyModules(VerifyModules);542return EE;543}544}545546// If we can't make a JIT and we didn't request one specifically, try making547// an interpreter instead.548if (WhichEngine & EngineKind::Interpreter) {549if (ExecutionEngine::InterpCtor)550return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);551if (ErrorStr)552*ErrorStr = "Interpreter has not been linked in.";553return nullptr;554}555556if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {557if (ErrorStr)558*ErrorStr = "JIT has not been linked in.";559}560561return nullptr;562}563564void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {565if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))566return getPointerToFunction(F);567568std::lock_guard<sys::Mutex> locked(lock);569if (void* P = getPointerToGlobalIfAvailable(GV))570return P;571572// Global variable might have been added since interpreter started.573if (GlobalVariable *GVar =574const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))575emitGlobalVariable(GVar);576else577llvm_unreachable("Global hasn't had an address allocated yet!");578579return getPointerToGlobalIfAvailable(GV);580}581582/// Converts a Constant* into a GenericValue, including handling of583/// ConstantExpr values.584GenericValue ExecutionEngine::getConstantValue(const Constant *C) {585// If its undefined, return the garbage.586if (isa<UndefValue>(C)) {587GenericValue Result;588switch (C->getType()->getTypeID()) {589default:590break;591case Type::IntegerTyID:592case Type::X86_FP80TyID:593case Type::FP128TyID:594case Type::PPC_FP128TyID:595// Although the value is undefined, we still have to construct an APInt596// with the correct bit width.597Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);598break;599case Type::StructTyID: {600// if the whole struct is 'undef' just reserve memory for the value.601if(StructType *STy = dyn_cast<StructType>(C->getType())) {602unsigned int elemNum = STy->getNumElements();603Result.AggregateVal.resize(elemNum);604for (unsigned int i = 0; i < elemNum; ++i) {605Type *ElemTy = STy->getElementType(i);606if (ElemTy->isIntegerTy())607Result.AggregateVal[i].IntVal =608APInt(ElemTy->getPrimitiveSizeInBits(), 0);609else if (ElemTy->isAggregateType()) {610const Constant *ElemUndef = UndefValue::get(ElemTy);611Result.AggregateVal[i] = getConstantValue(ElemUndef);612}613}614}615}616break;617case Type::ScalableVectorTyID:618report_fatal_error(619"Scalable vector support not yet implemented in ExecutionEngine");620case Type::ArrayTyID: {621auto *ArrTy = cast<ArrayType>(C->getType());622Type *ElemTy = ArrTy->getElementType();623unsigned int elemNum = ArrTy->getNumElements();624Result.AggregateVal.resize(elemNum);625if (ElemTy->isIntegerTy())626for (unsigned int i = 0; i < elemNum; ++i)627Result.AggregateVal[i].IntVal =628APInt(ElemTy->getPrimitiveSizeInBits(), 0);629break;630}631case Type::FixedVectorTyID: {632// if the whole vector is 'undef' just reserve memory for the value.633auto *VTy = cast<FixedVectorType>(C->getType());634Type *ElemTy = VTy->getElementType();635unsigned int elemNum = VTy->getNumElements();636Result.AggregateVal.resize(elemNum);637if (ElemTy->isIntegerTy())638for (unsigned int i = 0; i < elemNum; ++i)639Result.AggregateVal[i].IntVal =640APInt(ElemTy->getPrimitiveSizeInBits(), 0);641break;642}643}644return Result;645}646647// Otherwise, if the value is a ConstantExpr...648if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {649Constant *Op0 = CE->getOperand(0);650switch (CE->getOpcode()) {651case Instruction::GetElementPtr: {652// Compute the index653GenericValue Result = getConstantValue(Op0);654APInt Offset(DL.getPointerSizeInBits(), 0);655cast<GEPOperator>(CE)->accumulateConstantOffset(DL, Offset);656657char* tmp = (char*) Result.PointerVal;658Result = PTOGV(tmp + Offset.getSExtValue());659return Result;660}661case Instruction::Trunc: {662GenericValue GV = getConstantValue(Op0);663uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();664GV.IntVal = GV.IntVal.trunc(BitWidth);665return GV;666}667case Instruction::ZExt: {668GenericValue GV = getConstantValue(Op0);669uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();670GV.IntVal = GV.IntVal.zext(BitWidth);671return GV;672}673case Instruction::SExt: {674GenericValue GV = getConstantValue(Op0);675uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();676GV.IntVal = GV.IntVal.sext(BitWidth);677return GV;678}679case Instruction::FPTrunc: {680// FIXME long double681GenericValue GV = getConstantValue(Op0);682GV.FloatVal = float(GV.DoubleVal);683return GV;684}685case Instruction::FPExt:{686// FIXME long double687GenericValue GV = getConstantValue(Op0);688GV.DoubleVal = double(GV.FloatVal);689return GV;690}691case Instruction::UIToFP: {692GenericValue GV = getConstantValue(Op0);693if (CE->getType()->isFloatTy())694GV.FloatVal = float(GV.IntVal.roundToDouble());695else if (CE->getType()->isDoubleTy())696GV.DoubleVal = GV.IntVal.roundToDouble();697else if (CE->getType()->isX86_FP80Ty()) {698APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended());699(void)apf.convertFromAPInt(GV.IntVal,700false,701APFloat::rmNearestTiesToEven);702GV.IntVal = apf.bitcastToAPInt();703}704return GV;705}706case Instruction::SIToFP: {707GenericValue GV = getConstantValue(Op0);708if (CE->getType()->isFloatTy())709GV.FloatVal = float(GV.IntVal.signedRoundToDouble());710else if (CE->getType()->isDoubleTy())711GV.DoubleVal = GV.IntVal.signedRoundToDouble();712else if (CE->getType()->isX86_FP80Ty()) {713APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended());714(void)apf.convertFromAPInt(GV.IntVal,715true,716APFloat::rmNearestTiesToEven);717GV.IntVal = apf.bitcastToAPInt();718}719return GV;720}721case Instruction::FPToUI: // double->APInt conversion handles sign722case Instruction::FPToSI: {723GenericValue GV = getConstantValue(Op0);724uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();725if (Op0->getType()->isFloatTy())726GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);727else if (Op0->getType()->isDoubleTy())728GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);729else if (Op0->getType()->isX86_FP80Ty()) {730APFloat apf = APFloat(APFloat::x87DoubleExtended(), GV.IntVal);731uint64_t v;732bool ignored;733(void)apf.convertToInteger(MutableArrayRef(v), BitWidth,734CE->getOpcode()==Instruction::FPToSI,735APFloat::rmTowardZero, &ignored);736GV.IntVal = v; // endian?737}738return GV;739}740case Instruction::PtrToInt: {741GenericValue GV = getConstantValue(Op0);742uint32_t PtrWidth = DL.getTypeSizeInBits(Op0->getType());743assert(PtrWidth <= 64 && "Bad pointer width");744GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));745uint32_t IntWidth = DL.getTypeSizeInBits(CE->getType());746GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);747return GV;748}749case Instruction::IntToPtr: {750GenericValue GV = getConstantValue(Op0);751uint32_t PtrWidth = DL.getTypeSizeInBits(CE->getType());752GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);753assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");754GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));755return GV;756}757case Instruction::BitCast: {758GenericValue GV = getConstantValue(Op0);759Type* DestTy = CE->getType();760switch (Op0->getType()->getTypeID()) {761default: llvm_unreachable("Invalid bitcast operand");762case Type::IntegerTyID:763assert(DestTy->isFloatingPointTy() && "invalid bitcast");764if (DestTy->isFloatTy())765GV.FloatVal = GV.IntVal.bitsToFloat();766else if (DestTy->isDoubleTy())767GV.DoubleVal = GV.IntVal.bitsToDouble();768break;769case Type::FloatTyID:770assert(DestTy->isIntegerTy(32) && "Invalid bitcast");771GV.IntVal = APInt::floatToBits(GV.FloatVal);772break;773case Type::DoubleTyID:774assert(DestTy->isIntegerTy(64) && "Invalid bitcast");775GV.IntVal = APInt::doubleToBits(GV.DoubleVal);776break;777case Type::PointerTyID:778assert(DestTy->isPointerTy() && "Invalid bitcast");779break; // getConstantValue(Op0) above already converted it780}781return GV;782}783case Instruction::Add:784case Instruction::FAdd:785case Instruction::Sub:786case Instruction::FSub:787case Instruction::Mul:788case Instruction::FMul:789case Instruction::UDiv:790case Instruction::SDiv:791case Instruction::URem:792case Instruction::SRem:793case Instruction::And:794case Instruction::Or:795case Instruction::Xor: {796GenericValue LHS = getConstantValue(Op0);797GenericValue RHS = getConstantValue(CE->getOperand(1));798GenericValue GV;799switch (CE->getOperand(0)->getType()->getTypeID()) {800default: llvm_unreachable("Bad add type!");801case Type::IntegerTyID:802switch (CE->getOpcode()) {803default: llvm_unreachable("Invalid integer opcode");804case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;805case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;806case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;807case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;808case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;809case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;810case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;811case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;812case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;813case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;814}815break;816case Type::FloatTyID:817switch (CE->getOpcode()) {818default: llvm_unreachable("Invalid float opcode");819case Instruction::FAdd:820GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;821case Instruction::FSub:822GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;823case Instruction::FMul:824GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;825case Instruction::FDiv:826GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;827case Instruction::FRem:828GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;829}830break;831case Type::DoubleTyID:832switch (CE->getOpcode()) {833default: llvm_unreachable("Invalid double opcode");834case Instruction::FAdd:835GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;836case Instruction::FSub:837GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;838case Instruction::FMul:839GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;840case Instruction::FDiv:841GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;842case Instruction::FRem:843GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;844}845break;846case Type::X86_FP80TyID:847case Type::PPC_FP128TyID:848case Type::FP128TyID: {849const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();850APFloat apfLHS = APFloat(Sem, LHS.IntVal);851switch (CE->getOpcode()) {852default: llvm_unreachable("Invalid long double opcode");853case Instruction::FAdd:854apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);855GV.IntVal = apfLHS.bitcastToAPInt();856break;857case Instruction::FSub:858apfLHS.subtract(APFloat(Sem, RHS.IntVal),859APFloat::rmNearestTiesToEven);860GV.IntVal = apfLHS.bitcastToAPInt();861break;862case Instruction::FMul:863apfLHS.multiply(APFloat(Sem, RHS.IntVal),864APFloat::rmNearestTiesToEven);865GV.IntVal = apfLHS.bitcastToAPInt();866break;867case Instruction::FDiv:868apfLHS.divide(APFloat(Sem, RHS.IntVal),869APFloat::rmNearestTiesToEven);870GV.IntVal = apfLHS.bitcastToAPInt();871break;872case Instruction::FRem:873apfLHS.mod(APFloat(Sem, RHS.IntVal));874GV.IntVal = apfLHS.bitcastToAPInt();875break;876}877}878break;879}880return GV;881}882default:883break;884}885886SmallString<256> Msg;887raw_svector_ostream OS(Msg);888OS << "ConstantExpr not handled: " << *CE;889report_fatal_error(OS.str());890}891892if (auto *TETy = dyn_cast<TargetExtType>(C->getType())) {893assert(TETy->hasProperty(TargetExtType::HasZeroInit) && C->isNullValue() &&894"TargetExtType only supports null constant value");895C = Constant::getNullValue(TETy->getLayoutType());896}897898// Otherwise, we have a simple constant.899GenericValue Result;900switch (C->getType()->getTypeID()) {901case Type::FloatTyID:902Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();903break;904case Type::DoubleTyID:905Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();906break;907case Type::X86_FP80TyID:908case Type::FP128TyID:909case Type::PPC_FP128TyID:910Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();911break;912case Type::IntegerTyID:913Result.IntVal = cast<ConstantInt>(C)->getValue();914break;915case Type::PointerTyID:916while (auto *A = dyn_cast<GlobalAlias>(C)) {917C = A->getAliasee();918}919if (isa<ConstantPointerNull>(C))920Result.PointerVal = nullptr;921else if (const Function *F = dyn_cast<Function>(C))922Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));923else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))924Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));925else926llvm_unreachable("Unknown constant pointer type!");927break;928case Type::ScalableVectorTyID:929report_fatal_error(930"Scalable vector support not yet implemented in ExecutionEngine");931case Type::FixedVectorTyID: {932unsigned elemNum;933Type* ElemTy;934const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);935const ConstantVector *CV = dyn_cast<ConstantVector>(C);936const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);937938if (CDV) {939elemNum = CDV->getNumElements();940ElemTy = CDV->getElementType();941} else if (CV || CAZ) {942auto *VTy = cast<FixedVectorType>(C->getType());943elemNum = VTy->getNumElements();944ElemTy = VTy->getElementType();945} else {946llvm_unreachable("Unknown constant vector type!");947}948949Result.AggregateVal.resize(elemNum);950// Check if vector holds floats.951if(ElemTy->isFloatTy()) {952if (CAZ) {953GenericValue floatZero;954floatZero.FloatVal = 0.f;955std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),956floatZero);957break;958}959if(CV) {960for (unsigned i = 0; i < elemNum; ++i)961if (!isa<UndefValue>(CV->getOperand(i)))962Result.AggregateVal[i].FloatVal = cast<ConstantFP>(963CV->getOperand(i))->getValueAPF().convertToFloat();964break;965}966if(CDV)967for (unsigned i = 0; i < elemNum; ++i)968Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);969970break;971}972// Check if vector holds doubles.973if (ElemTy->isDoubleTy()) {974if (CAZ) {975GenericValue doubleZero;976doubleZero.DoubleVal = 0.0;977std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),978doubleZero);979break;980}981if(CV) {982for (unsigned i = 0; i < elemNum; ++i)983if (!isa<UndefValue>(CV->getOperand(i)))984Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(985CV->getOperand(i))->getValueAPF().convertToDouble();986break;987}988if(CDV)989for (unsigned i = 0; i < elemNum; ++i)990Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);991992break;993}994// Check if vector holds integers.995if (ElemTy->isIntegerTy()) {996if (CAZ) {997GenericValue intZero;998intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);999std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),1000intZero);1001break;1002}1003if(CV) {1004for (unsigned i = 0; i < elemNum; ++i)1005if (!isa<UndefValue>(CV->getOperand(i)))1006Result.AggregateVal[i].IntVal = cast<ConstantInt>(1007CV->getOperand(i))->getValue();1008else {1009Result.AggregateVal[i].IntVal =1010APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);1011}1012break;1013}1014if(CDV)1015for (unsigned i = 0; i < elemNum; ++i)1016Result.AggregateVal[i].IntVal = APInt(1017CDV->getElementType()->getPrimitiveSizeInBits(),1018CDV->getElementAsInteger(i));10191020break;1021}1022llvm_unreachable("Unknown constant pointer type!");1023} break;10241025default:1026SmallString<256> Msg;1027raw_svector_ostream OS(Msg);1028OS << "ERROR: Constant unimplemented for type: " << *C->getType();1029report_fatal_error(OS.str());1030}10311032return Result;1033}10341035void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,1036GenericValue *Ptr, Type *Ty) {1037// It is safe to treat TargetExtType as its layout type since the underlying1038// bits are only copied and are not inspected.1039if (auto *TETy = dyn_cast<TargetExtType>(Ty))1040Ty = TETy->getLayoutType();10411042const unsigned StoreBytes = getDataLayout().getTypeStoreSize(Ty);10431044switch (Ty->getTypeID()) {1045default:1046dbgs() << "Cannot store value of type " << *Ty << "!\n";1047break;1048case Type::IntegerTyID:1049StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);1050break;1051case Type::FloatTyID:1052*((float*)Ptr) = Val.FloatVal;1053break;1054case Type::DoubleTyID:1055*((double*)Ptr) = Val.DoubleVal;1056break;1057case Type::X86_FP80TyID:1058memcpy(Ptr, Val.IntVal.getRawData(), 10);1059break;1060case Type::PointerTyID:1061// Ensure 64 bit target pointers are fully initialized on 32 bit hosts.1062if (StoreBytes != sizeof(PointerTy))1063memset(&(Ptr->PointerVal), 0, StoreBytes);10641065*((PointerTy*)Ptr) = Val.PointerVal;1066break;1067case Type::FixedVectorTyID:1068case Type::ScalableVectorTyID:1069for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {1070if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())1071*(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;1072if (cast<VectorType>(Ty)->getElementType()->isFloatTy())1073*(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;1074if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {1075unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;1076StoreIntToMemory(Val.AggregateVal[i].IntVal,1077(uint8_t*)Ptr + numOfBytes*i, numOfBytes);1078}1079}1080break;1081}10821083if (sys::IsLittleEndianHost != getDataLayout().isLittleEndian())1084// Host and target are different endian - reverse the stored bytes.1085std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);1086}10871088/// FIXME: document1089///1090void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,1091GenericValue *Ptr,1092Type *Ty) {1093if (auto *TETy = dyn_cast<TargetExtType>(Ty))1094Ty = TETy->getLayoutType();10951096const unsigned LoadBytes = getDataLayout().getTypeStoreSize(Ty);10971098switch (Ty->getTypeID()) {1099case Type::IntegerTyID:1100// An APInt with all words initially zero.1101Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);1102LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);1103break;1104case Type::FloatTyID:1105Result.FloatVal = *((float*)Ptr);1106break;1107case Type::DoubleTyID:1108Result.DoubleVal = *((double*)Ptr);1109break;1110case Type::PointerTyID:1111Result.PointerVal = *((PointerTy*)Ptr);1112break;1113case Type::X86_FP80TyID: {1114// This is endian dependent, but it will only work on x86 anyway.1115// FIXME: Will not trap if loading a signaling NaN.1116uint64_t y[2];1117memcpy(y, Ptr, 10);1118Result.IntVal = APInt(80, y);1119break;1120}1121case Type::ScalableVectorTyID:1122report_fatal_error(1123"Scalable vector support not yet implemented in ExecutionEngine");1124case Type::FixedVectorTyID: {1125auto *VT = cast<FixedVectorType>(Ty);1126Type *ElemT = VT->getElementType();1127const unsigned numElems = VT->getNumElements();1128if (ElemT->isFloatTy()) {1129Result.AggregateVal.resize(numElems);1130for (unsigned i = 0; i < numElems; ++i)1131Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);1132}1133if (ElemT->isDoubleTy()) {1134Result.AggregateVal.resize(numElems);1135for (unsigned i = 0; i < numElems; ++i)1136Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);1137}1138if (ElemT->isIntegerTy()) {1139GenericValue intZero;1140const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();1141intZero.IntVal = APInt(elemBitWidth, 0);1142Result.AggregateVal.resize(numElems, intZero);1143for (unsigned i = 0; i < numElems; ++i)1144LoadIntFromMemory(Result.AggregateVal[i].IntVal,1145(uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);1146}1147break;1148}1149default:1150SmallString<256> Msg;1151raw_svector_ostream OS(Msg);1152OS << "Cannot load value of type " << *Ty << "!";1153report_fatal_error(OS.str());1154}1155}11561157void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {1158LLVM_DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");1159LLVM_DEBUG(Init->dump());1160if (isa<UndefValue>(Init))1161return;11621163if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {1164unsigned ElementSize =1165getDataLayout().getTypeAllocSize(CP->getType()->getElementType());1166for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)1167InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);1168return;1169}11701171if (isa<ConstantAggregateZero>(Init)) {1172memset(Addr, 0, (size_t)getDataLayout().getTypeAllocSize(Init->getType()));1173return;1174}11751176if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {1177unsigned ElementSize =1178getDataLayout().getTypeAllocSize(CPA->getType()->getElementType());1179for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)1180InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);1181return;1182}11831184if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {1185const StructLayout *SL =1186getDataLayout().getStructLayout(cast<StructType>(CPS->getType()));1187for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)1188InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));1189return;1190}11911192if (const ConstantDataSequential *CDS =1193dyn_cast<ConstantDataSequential>(Init)) {1194// CDS is already laid out in host memory order.1195StringRef Data = CDS->getRawDataValues();1196memcpy(Addr, Data.data(), Data.size());1197return;1198}11991200if (Init->getType()->isFirstClassType()) {1201GenericValue Val = getConstantValue(Init);1202StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());1203return;1204}12051206LLVM_DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");1207llvm_unreachable("Unknown constant type to initialize memory with!");1208}12091210/// EmitGlobals - Emit all of the global variables to memory, storing their1211/// addresses into GlobalAddress. This must make sure to copy the contents of1212/// their initializers into the memory.1213void ExecutionEngine::emitGlobals() {1214// Loop over all of the global variables in the program, allocating the memory1215// to hold them. If there is more than one module, do a prepass over globals1216// to figure out how the different modules should link together.1217std::map<std::pair<std::string, Type*>,1218const GlobalValue*> LinkedGlobalsMap;12191220if (Modules.size() != 1) {1221for (const auto &M : Modules) {1222for (const auto &GV : M->globals()) {1223if (GV.hasLocalLinkage() || GV.isDeclaration() ||1224GV.hasAppendingLinkage() || !GV.hasName())1225continue;// Ignore external globals and globals with internal linkage.12261227const GlobalValue *&GVEntry = LinkedGlobalsMap[std::make_pair(1228std::string(GV.getName()), GV.getType())];12291230// If this is the first time we've seen this global, it is the canonical1231// version.1232if (!GVEntry) {1233GVEntry = &GV;1234continue;1235}12361237// If the existing global is strong, never replace it.1238if (GVEntry->hasExternalLinkage())1239continue;12401241// Otherwise, we know it's linkonce/weak, replace it if this is a strong1242// symbol. FIXME is this right for common?1243if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())1244GVEntry = &GV;1245}1246}1247}12481249std::vector<const GlobalValue*> NonCanonicalGlobals;1250for (const auto &M : Modules) {1251for (const auto &GV : M->globals()) {1252// In the multi-module case, see what this global maps to.1253if (!LinkedGlobalsMap.empty()) {1254if (const GlobalValue *GVEntry = LinkedGlobalsMap[std::make_pair(1255std::string(GV.getName()), GV.getType())]) {1256// If something else is the canonical global, ignore this one.1257if (GVEntry != &GV) {1258NonCanonicalGlobals.push_back(&GV);1259continue;1260}1261}1262}12631264if (!GV.isDeclaration()) {1265addGlobalMapping(&GV, getMemoryForGV(&GV));1266} else {1267// External variable reference. Try to use the dynamic loader to1268// get a pointer to it.1269if (void *SymAddr = sys::DynamicLibrary::SearchForAddressOfSymbol(1270std::string(GV.getName())))1271addGlobalMapping(&GV, SymAddr);1272else {1273report_fatal_error("Could not resolve external global address: "1274+GV.getName());1275}1276}1277}12781279// If there are multiple modules, map the non-canonical globals to their1280// canonical location.1281if (!NonCanonicalGlobals.empty()) {1282for (const GlobalValue *GV : NonCanonicalGlobals) {1283const GlobalValue *CGV = LinkedGlobalsMap[std::make_pair(1284std::string(GV->getName()), GV->getType())];1285void *Ptr = getPointerToGlobalIfAvailable(CGV);1286assert(Ptr && "Canonical global wasn't codegen'd!");1287addGlobalMapping(GV, Ptr);1288}1289}12901291// Now that all of the globals are set up in memory, loop through them all1292// and initialize their contents.1293for (const auto &GV : M->globals()) {1294if (!GV.isDeclaration()) {1295if (!LinkedGlobalsMap.empty()) {1296if (const GlobalValue *GVEntry = LinkedGlobalsMap[std::make_pair(1297std::string(GV.getName()), GV.getType())])1298if (GVEntry != &GV) // Not the canonical variable.1299continue;1300}1301emitGlobalVariable(&GV);1302}1303}1304}1305}13061307// EmitGlobalVariable - This method emits the specified global variable to the1308// address specified in GlobalAddresses, or allocates new memory if it's not1309// already in the map.1310void ExecutionEngine::emitGlobalVariable(const GlobalVariable *GV) {1311void *GA = getPointerToGlobalIfAvailable(GV);13121313if (!GA) {1314// If it's not already specified, allocate memory for the global.1315GA = getMemoryForGV(GV);13161317// If we failed to allocate memory for this global, return.1318if (!GA) return;13191320addGlobalMapping(GV, GA);1321}13221323// Don't initialize if it's thread local, let the client do it.1324if (!GV->isThreadLocal())1325InitializeMemory(GV->getInitializer(), GA);13261327Type *ElTy = GV->getValueType();1328size_t GVSize = (size_t)getDataLayout().getTypeAllocSize(ElTy);1329NumInitBytes += (unsigned)GVSize;1330++NumGlobals;1331}133213331334