PageRenderTime 57ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/project/llvm/lib/ExecutionEngine/ExecutionEngine.cpp

https://gitlab.com/torshie/modern-tool
C++ | 1355 lines | 1090 code | 139 blank | 126 comment | 241 complexity | 156a336a59fc074af0681d40ee6e5dd5 MD5 | raw file
Possible License(s): BSD-3-Clause, 0BSD, BSD-2-Clause, GPL-2.0, GPL-3.0, LGPL-2.0, Apache-2.0
  1. //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the common interface used by the various execution engine
  11. // subclasses.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/ExecutionEngine/ExecutionEngine.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SmallString.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/ExecutionEngine/GenericValue.h"
  19. #include "llvm/ExecutionEngine/JITEventListener.h"
  20. #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
  21. #include "llvm/IR/Constants.h"
  22. #include "llvm/IR/DataLayout.h"
  23. #include "llvm/IR/DerivedTypes.h"
  24. #include "llvm/IR/Mangler.h"
  25. #include "llvm/IR/Module.h"
  26. #include "llvm/IR/Operator.h"
  27. #include "llvm/IR/ValueHandle.h"
  28. #include "llvm/Object/Archive.h"
  29. #include "llvm/Object/ObjectFile.h"
  30. #include "llvm/Support/Debug.h"
  31. #include "llvm/Support/DynamicLibrary.h"
  32. #include "llvm/Support/ErrorHandling.h"
  33. #include "llvm/Support/Host.h"
  34. #include "llvm/Support/MutexGuard.h"
  35. #include "llvm/Support/TargetRegistry.h"
  36. #include "llvm/Support/raw_ostream.h"
  37. #include "llvm/Target/TargetMachine.h"
  38. #include <cmath>
  39. #include <cstring>
  40. using namespace llvm;
  41. #define DEBUG_TYPE "jit"
  42. STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
  43. STATISTIC(NumGlobals , "Number of global vars initialized");
  44. ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
  45. std::unique_ptr<Module> M, std::string *ErrorStr,
  46. std::shared_ptr<MCJITMemoryManager> MemMgr,
  47. std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver,
  48. std::unique_ptr<TargetMachine> TM) = nullptr;
  49. ExecutionEngine *(*ExecutionEngine::OrcMCJITReplacementCtor)(
  50. std::string *ErrorStr, std::shared_ptr<MCJITMemoryManager> MemMgr,
  51. std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver,
  52. std::unique_ptr<TargetMachine> TM) = nullptr;
  53. ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M,
  54. std::string *ErrorStr) =nullptr;
  55. void JITEventListener::anchor() {}
  56. ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)
  57. : LazyFunctionCreator(nullptr) {
  58. CompilingLazily = false;
  59. GVCompilationDisabled = false;
  60. SymbolSearchingDisabled = false;
  61. // IR module verification is enabled by default in debug builds, and disabled
  62. // by default in release builds.
  63. #ifndef NDEBUG
  64. VerifyModules = true;
  65. #else
  66. VerifyModules = false;
  67. #endif
  68. assert(M && "Module is null?");
  69. Modules.push_back(std::move(M));
  70. }
  71. ExecutionEngine::~ExecutionEngine() {
  72. clearAllGlobalMappings();
  73. }
  74. namespace {
  75. /// \brief Helper class which uses a value handler to automatically deletes the
  76. /// memory block when the GlobalVariable is destroyed.
  77. class GVMemoryBlock : public CallbackVH {
  78. GVMemoryBlock(const GlobalVariable *GV)
  79. : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
  80. public:
  81. /// \brief Returns the address the GlobalVariable should be written into. The
  82. /// GVMemoryBlock object prefixes that.
  83. static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
  84. Type *ElTy = GV->getType()->getElementType();
  85. size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
  86. void *RawMemory = ::operator new(
  87. RoundUpToAlignment(sizeof(GVMemoryBlock),
  88. TD.getPreferredAlignment(GV))
  89. + GVSize);
  90. new(RawMemory) GVMemoryBlock(GV);
  91. return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
  92. }
  93. void deleted() override {
  94. // We allocated with operator new and with some extra memory hanging off the
  95. // end, so don't just delete this. I'm not sure if this is actually
  96. // required.
  97. this->~GVMemoryBlock();
  98. ::operator delete(this);
  99. }
  100. };
  101. } // anonymous namespace
  102. char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
  103. return GVMemoryBlock::Create(GV, *getDataLayout());
  104. }
  105. void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
  106. llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
  107. }
  108. void
  109. ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
  110. llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
  111. }
  112. void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
  113. llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
  114. }
  115. bool ExecutionEngine::removeModule(Module *M) {
  116. for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
  117. Module *Found = I->get();
  118. if (Found == M) {
  119. I->release();
  120. Modules.erase(I);
  121. clearGlobalMappingsFromModule(M);
  122. return true;
  123. }
  124. }
  125. return false;
  126. }
  127. Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
  128. for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
  129. Function *F = Modules[i]->getFunction(FnName);
  130. if (F && !F->isDeclaration())
  131. return F;
  132. }
  133. return nullptr;
  134. }
  135. GlobalVariable *ExecutionEngine::FindGlobalVariableNamed(const char *Name, bool AllowInternal) {
  136. for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
  137. GlobalVariable *GV = Modules[i]->getGlobalVariable(Name,AllowInternal);
  138. if (GV && !GV->isDeclaration())
  139. return GV;
  140. }
  141. return nullptr;
  142. }
  143. uint64_t ExecutionEngineState::RemoveMapping(StringRef Name) {
  144. GlobalAddressMapTy::iterator I = GlobalAddressMap.find(Name);
  145. uint64_t OldVal;
  146. // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
  147. // GlobalAddressMap.
  148. if (I == GlobalAddressMap.end())
  149. OldVal = 0;
  150. else {
  151. GlobalAddressReverseMap.erase(I->second);
  152. OldVal = I->second;
  153. GlobalAddressMap.erase(I);
  154. }
  155. return OldVal;
  156. }
  157. std::string ExecutionEngine::getMangledName(const GlobalValue *GV) {
  158. assert(GV->hasName() && "Global must have name.");
  159. MutexGuard locked(lock);
  160. SmallString<128> FullName;
  161. const DataLayout &DL =
  162. GV->getParent()->getDataLayout().isDefault()
  163. ? *getDataLayout()
  164. : GV->getParent()->getDataLayout();
  165. Mangler::getNameWithPrefix(FullName, GV->getName(), DL);
  166. return FullName.str();
  167. }
  168. void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
  169. MutexGuard locked(lock);
  170. addGlobalMapping(getMangledName(GV), (uint64_t) Addr);
  171. }
  172. void ExecutionEngine::addGlobalMapping(StringRef Name, uint64_t Addr) {
  173. MutexGuard locked(lock);
  174. assert(!Name.empty() && "Empty GlobalMapping symbol name!");
  175. DEBUG(dbgs() << "JIT: Map \'" << Name << "\' to [" << Addr << "]\n";);
  176. uint64_t &CurVal = EEState.getGlobalAddressMap()[Name];
  177. assert((!CurVal || !Addr) && "GlobalMapping already established!");
  178. CurVal = Addr;
  179. // If we are using the reverse mapping, add it too.
  180. if (!EEState.getGlobalAddressReverseMap().empty()) {
  181. std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
  182. assert((!V.empty() || !Name.empty()) &&
  183. "GlobalMapping already established!");
  184. V = Name;
  185. }
  186. }
  187. void ExecutionEngine::clearAllGlobalMappings() {
  188. MutexGuard locked(lock);
  189. EEState.getGlobalAddressMap().clear();
  190. EEState.getGlobalAddressReverseMap().clear();
  191. }
  192. void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
  193. MutexGuard locked(lock);
  194. for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
  195. EEState.RemoveMapping(getMangledName(FI));
  196. for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
  197. GI != GE; ++GI)
  198. EEState.RemoveMapping(getMangledName(GI));
  199. }
  200. uint64_t ExecutionEngine::updateGlobalMapping(const GlobalValue *GV,
  201. void *Addr) {
  202. MutexGuard locked(lock);
  203. return updateGlobalMapping(getMangledName(GV), (uint64_t) Addr);
  204. }
  205. uint64_t ExecutionEngine::updateGlobalMapping(StringRef Name, uint64_t Addr) {
  206. MutexGuard locked(lock);
  207. ExecutionEngineState::GlobalAddressMapTy &Map =
  208. EEState.getGlobalAddressMap();
  209. // Deleting from the mapping?
  210. if (!Addr)
  211. return EEState.RemoveMapping(Name);
  212. uint64_t &CurVal = Map[Name];
  213. uint64_t OldVal = CurVal;
  214. if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
  215. EEState.getGlobalAddressReverseMap().erase(CurVal);
  216. CurVal = Addr;
  217. // If we are using the reverse mapping, add it too.
  218. if (!EEState.getGlobalAddressReverseMap().empty()) {
  219. std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
  220. assert((!V.empty() || !Name.empty()) &&
  221. "GlobalMapping already established!");
  222. V = Name;
  223. }
  224. return OldVal;
  225. }
  226. uint64_t ExecutionEngine::getAddressToGlobalIfAvailable(StringRef S) {
  227. MutexGuard locked(lock);
  228. uint64_t Address = 0;
  229. ExecutionEngineState::GlobalAddressMapTy::iterator I =
  230. EEState.getGlobalAddressMap().find(S);
  231. if (I != EEState.getGlobalAddressMap().end())
  232. Address = I->second;
  233. return Address;
  234. }
  235. void *ExecutionEngine::getPointerToGlobalIfAvailable(StringRef S) {
  236. MutexGuard locked(lock);
  237. if (void* Address = (void *) getAddressToGlobalIfAvailable(S))
  238. return Address;
  239. return nullptr;
  240. }
  241. void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
  242. MutexGuard locked(lock);
  243. return getPointerToGlobalIfAvailable(getMangledName(GV));
  244. }
  245. const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
  246. MutexGuard locked(lock);
  247. // If we haven't computed the reverse mapping yet, do so first.
  248. if (EEState.getGlobalAddressReverseMap().empty()) {
  249. for (ExecutionEngineState::GlobalAddressMapTy::iterator
  250. I = EEState.getGlobalAddressMap().begin(),
  251. E = EEState.getGlobalAddressMap().end(); I != E; ++I) {
  252. StringRef Name = I->first();
  253. uint64_t Addr = I->second;
  254. EEState.getGlobalAddressReverseMap().insert(std::make_pair(
  255. Addr, Name));
  256. }
  257. }
  258. std::map<uint64_t, std::string>::iterator I =
  259. EEState.getGlobalAddressReverseMap().find((uint64_t) Addr);
  260. if (I != EEState.getGlobalAddressReverseMap().end()) {
  261. StringRef Name = I->second;
  262. for (unsigned i = 0, e = Modules.size(); i != e; ++i)
  263. if (GlobalValue *GV = Modules[i]->getNamedValue(Name))
  264. return GV;
  265. }
  266. return nullptr;
  267. }
  268. namespace {
  269. class ArgvArray {
  270. std::unique_ptr<char[]> Array;
  271. std::vector<std::unique_ptr<char[]>> Values;
  272. public:
  273. /// Turn a vector of strings into a nice argv style array of pointers to null
  274. /// terminated strings.
  275. void *reset(LLVMContext &C, ExecutionEngine *EE,
  276. const std::vector<std::string> &InputArgv);
  277. };
  278. } // anonymous namespace
  279. void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
  280. const std::vector<std::string> &InputArgv) {
  281. Values.clear(); // Free the old contents.
  282. Values.reserve(InputArgv.size());
  283. unsigned PtrSize = EE->getDataLayout()->getPointerSize();
  284. Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
  285. DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array.get() << "\n");
  286. Type *SBytePtr = Type::getInt8PtrTy(C);
  287. for (unsigned i = 0; i != InputArgv.size(); ++i) {
  288. unsigned Size = InputArgv[i].size()+1;
  289. auto Dest = make_unique<char[]>(Size);
  290. DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest.get() << "\n");
  291. std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
  292. Dest[Size-1] = 0;
  293. // Endian safe: Array[i] = (PointerTy)Dest;
  294. EE->StoreValueToMemory(PTOGV(Dest.get()),
  295. (GenericValue*)(&Array[i*PtrSize]), SBytePtr);
  296. Values.push_back(std::move(Dest));
  297. }
  298. // Null terminate it
  299. EE->StoreValueToMemory(PTOGV(nullptr),
  300. (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
  301. SBytePtr);
  302. return Array.get();
  303. }
  304. void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
  305. bool isDtors) {
  306. const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
  307. GlobalVariable *GV = module.getNamedGlobal(Name);
  308. // If this global has internal linkage, or if it has a use, then it must be
  309. // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
  310. // this is the case, don't execute any of the global ctors, __main will do
  311. // it.
  312. if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
  313. // Should be an array of '{ i32, void ()* }' structs. The first value is
  314. // the init priority, which we ignore.
  315. ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
  316. if (!InitList)
  317. return;
  318. for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
  319. ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
  320. if (!CS) continue;
  321. Constant *FP = CS->getOperand(1);
  322. if (FP->isNullValue())
  323. continue; // Found a sentinal value, ignore.
  324. // Strip off constant expression casts.
  325. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
  326. if (CE->isCast())
  327. FP = CE->getOperand(0);
  328. // Execute the ctor/dtor function!
  329. if (Function *F = dyn_cast<Function>(FP))
  330. runFunction(F, None);
  331. // FIXME: It is marginally lame that we just do nothing here if we see an
  332. // entry we don't recognize. It might not be unreasonable for the verifier
  333. // to not even allow this and just assert here.
  334. }
  335. }
  336. void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
  337. // Execute global ctors/dtors for each module in the program.
  338. for (std::unique_ptr<Module> &M : Modules)
  339. runStaticConstructorsDestructors(*M, isDtors);
  340. }
  341. #ifndef NDEBUG
  342. /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
  343. static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
  344. unsigned PtrSize = EE->getDataLayout()->getPointerSize();
  345. for (unsigned i = 0; i < PtrSize; ++i)
  346. if (*(i + (uint8_t*)Loc))
  347. return false;
  348. return true;
  349. }
  350. #endif
  351. int ExecutionEngine::runFunctionAsMain(Function *Fn,
  352. const std::vector<std::string> &argv,
  353. const char * const * envp) {
  354. std::vector<GenericValue> GVArgs;
  355. GenericValue GVArgc;
  356. GVArgc.IntVal = APInt(32, argv.size());
  357. // Check main() type
  358. unsigned NumArgs = Fn->getFunctionType()->getNumParams();
  359. FunctionType *FTy = Fn->getFunctionType();
  360. Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
  361. // Check the argument types.
  362. if (NumArgs > 3)
  363. report_fatal_error("Invalid number of arguments of main() supplied");
  364. if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
  365. report_fatal_error("Invalid type for third argument of main() supplied");
  366. if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
  367. report_fatal_error("Invalid type for second argument of main() supplied");
  368. if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
  369. report_fatal_error("Invalid type for first argument of main() supplied");
  370. if (!FTy->getReturnType()->isIntegerTy() &&
  371. !FTy->getReturnType()->isVoidTy())
  372. report_fatal_error("Invalid return type of main() supplied");
  373. ArgvArray CArgv;
  374. ArgvArray CEnv;
  375. if (NumArgs) {
  376. GVArgs.push_back(GVArgc); // Arg #0 = argc.
  377. if (NumArgs > 1) {
  378. // Arg #1 = argv.
  379. GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
  380. assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
  381. "argv[0] was null after CreateArgv");
  382. if (NumArgs > 2) {
  383. std::vector<std::string> EnvVars;
  384. for (unsigned i = 0; envp[i]; ++i)
  385. EnvVars.emplace_back(envp[i]);
  386. // Arg #2 = envp.
  387. GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
  388. }
  389. }
  390. }
  391. return runFunction(Fn, GVArgs).IntVal.getZExtValue();
  392. }
  393. EngineBuilder::EngineBuilder() : EngineBuilder(nullptr) {}
  394. EngineBuilder::EngineBuilder(std::unique_ptr<Module> M)
  395. : M(std::move(M)), WhichEngine(EngineKind::Either), ErrorStr(nullptr),
  396. OptLevel(CodeGenOpt::Default), MemMgr(nullptr), Resolver(nullptr),
  397. RelocModel(Reloc::Default), CMModel(CodeModel::JITDefault),
  398. UseOrcMCJITReplacement(false) {
  399. // IR module verification is enabled by default in debug builds, and disabled
  400. // by default in release builds.
  401. #ifndef NDEBUG
  402. VerifyModules = true;
  403. #else
  404. VerifyModules = false;
  405. #endif
  406. }
  407. EngineBuilder::~EngineBuilder() = default;
  408. EngineBuilder &EngineBuilder::setMCJITMemoryManager(
  409. std::unique_ptr<RTDyldMemoryManager> mcjmm) {
  410. auto SharedMM = std::shared_ptr<RTDyldMemoryManager>(std::move(mcjmm));
  411. MemMgr = SharedMM;
  412. Resolver = SharedMM;
  413. return *this;
  414. }
  415. EngineBuilder&
  416. EngineBuilder::setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM) {
  417. MemMgr = std::shared_ptr<MCJITMemoryManager>(std::move(MM));
  418. return *this;
  419. }
  420. EngineBuilder&
  421. EngineBuilder::setSymbolResolver(std::unique_ptr<RuntimeDyld::SymbolResolver> SR) {
  422. Resolver = std::shared_ptr<RuntimeDyld::SymbolResolver>(std::move(SR));
  423. return *this;
  424. }
  425. ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
  426. std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
  427. // Make sure we can resolve symbols in the program as well. The zero arg
  428. // to the function tells DynamicLibrary to load the program, not a library.
  429. if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
  430. return nullptr;
  431. // If the user specified a memory manager but didn't specify which engine to
  432. // create, we assume they only want the JIT, and we fail if they only want
  433. // the interpreter.
  434. if (MemMgr) {
  435. if (WhichEngine & EngineKind::JIT)
  436. WhichEngine = EngineKind::JIT;
  437. else {
  438. if (ErrorStr)
  439. *ErrorStr = "Cannot create an interpreter with a memory manager.";
  440. return nullptr;
  441. }
  442. }
  443. // Unless the interpreter was explicitly selected or the JIT is not linked,
  444. // try making a JIT.
  445. if ((WhichEngine & EngineKind::JIT) && TheTM) {
  446. Triple TT(M->getTargetTriple());
  447. if (!TM->getTarget().hasJIT()) {
  448. errs() << "WARNING: This target JIT is not designed for the host"
  449. << " you are running. If bad things happen, please choose"
  450. << " a different -march switch.\n";
  451. }
  452. ExecutionEngine *EE = nullptr;
  453. if (ExecutionEngine::OrcMCJITReplacementCtor && UseOrcMCJITReplacement) {
  454. EE = ExecutionEngine::OrcMCJITReplacementCtor(ErrorStr, std::move(MemMgr),
  455. std::move(Resolver),
  456. std::move(TheTM));
  457. EE->addModule(std::move(M));
  458. } else if (ExecutionEngine::MCJITCtor)
  459. EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MemMgr),
  460. std::move(Resolver), std::move(TheTM));
  461. if (EE) {
  462. EE->setVerifyModules(VerifyModules);
  463. return EE;
  464. }
  465. }
  466. // If we can't make a JIT and we didn't request one specifically, try making
  467. // an interpreter instead.
  468. if (WhichEngine & EngineKind::Interpreter) {
  469. if (ExecutionEngine::InterpCtor)
  470. return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
  471. if (ErrorStr)
  472. *ErrorStr = "Interpreter has not been linked in.";
  473. return nullptr;
  474. }
  475. if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
  476. if (ErrorStr)
  477. *ErrorStr = "JIT has not been linked in.";
  478. }
  479. return nullptr;
  480. }
  481. void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
  482. if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
  483. return getPointerToFunction(F);
  484. MutexGuard locked(lock);
  485. if (void* P = getPointerToGlobalIfAvailable(GV))
  486. return P;
  487. // Global variable might have been added since interpreter started.
  488. if (GlobalVariable *GVar =
  489. const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
  490. EmitGlobalVariable(GVar);
  491. else
  492. llvm_unreachable("Global hasn't had an address allocated yet!");
  493. return getPointerToGlobalIfAvailable(GV);
  494. }
  495. /// \brief Converts a Constant* into a GenericValue, including handling of
  496. /// ConstantExpr values.
  497. GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
  498. // If its undefined, return the garbage.
  499. if (isa<UndefValue>(C)) {
  500. GenericValue Result;
  501. switch (C->getType()->getTypeID()) {
  502. default:
  503. break;
  504. case Type::IntegerTyID:
  505. case Type::X86_FP80TyID:
  506. case Type::FP128TyID:
  507. case Type::PPC_FP128TyID:
  508. // Although the value is undefined, we still have to construct an APInt
  509. // with the correct bit width.
  510. Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
  511. break;
  512. case Type::StructTyID: {
  513. // if the whole struct is 'undef' just reserve memory for the value.
  514. if(StructType *STy = dyn_cast<StructType>(C->getType())) {
  515. unsigned int elemNum = STy->getNumElements();
  516. Result.AggregateVal.resize(elemNum);
  517. for (unsigned int i = 0; i < elemNum; ++i) {
  518. Type *ElemTy = STy->getElementType(i);
  519. if (ElemTy->isIntegerTy())
  520. Result.AggregateVal[i].IntVal =
  521. APInt(ElemTy->getPrimitiveSizeInBits(), 0);
  522. else if (ElemTy->isAggregateType()) {
  523. const Constant *ElemUndef = UndefValue::get(ElemTy);
  524. Result.AggregateVal[i] = getConstantValue(ElemUndef);
  525. }
  526. }
  527. }
  528. }
  529. break;
  530. case Type::VectorTyID:
  531. // if the whole vector is 'undef' just reserve memory for the value.
  532. const VectorType* VTy = dyn_cast<VectorType>(C->getType());
  533. const Type *ElemTy = VTy->getElementType();
  534. unsigned int elemNum = VTy->getNumElements();
  535. Result.AggregateVal.resize(elemNum);
  536. if (ElemTy->isIntegerTy())
  537. for (unsigned int i = 0; i < elemNum; ++i)
  538. Result.AggregateVal[i].IntVal =
  539. APInt(ElemTy->getPrimitiveSizeInBits(), 0);
  540. break;
  541. }
  542. return Result;
  543. }
  544. // Otherwise, if the value is a ConstantExpr...
  545. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  546. Constant *Op0 = CE->getOperand(0);
  547. switch (CE->getOpcode()) {
  548. case Instruction::GetElementPtr: {
  549. // Compute the index
  550. GenericValue Result = getConstantValue(Op0);
  551. APInt Offset(DL->getPointerSizeInBits(), 0);
  552. cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset);
  553. char* tmp = (char*) Result.PointerVal;
  554. Result = PTOGV(tmp + Offset.getSExtValue());
  555. return Result;
  556. }
  557. case Instruction::Trunc: {
  558. GenericValue GV = getConstantValue(Op0);
  559. uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
  560. GV.IntVal = GV.IntVal.trunc(BitWidth);
  561. return GV;
  562. }
  563. case Instruction::ZExt: {
  564. GenericValue GV = getConstantValue(Op0);
  565. uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
  566. GV.IntVal = GV.IntVal.zext(BitWidth);
  567. return GV;
  568. }
  569. case Instruction::SExt: {
  570. GenericValue GV = getConstantValue(Op0);
  571. uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
  572. GV.IntVal = GV.IntVal.sext(BitWidth);
  573. return GV;
  574. }
  575. case Instruction::FPTrunc: {
  576. // FIXME long double
  577. GenericValue GV = getConstantValue(Op0);
  578. GV.FloatVal = float(GV.DoubleVal);
  579. return GV;
  580. }
  581. case Instruction::FPExt:{
  582. // FIXME long double
  583. GenericValue GV = getConstantValue(Op0);
  584. GV.DoubleVal = double(GV.FloatVal);
  585. return GV;
  586. }
  587. case Instruction::UIToFP: {
  588. GenericValue GV = getConstantValue(Op0);
  589. if (CE->getType()->isFloatTy())
  590. GV.FloatVal = float(GV.IntVal.roundToDouble());
  591. else if (CE->getType()->isDoubleTy())
  592. GV.DoubleVal = GV.IntVal.roundToDouble();
  593. else if (CE->getType()->isX86_FP80Ty()) {
  594. APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
  595. (void)apf.convertFromAPInt(GV.IntVal,
  596. false,
  597. APFloat::rmNearestTiesToEven);
  598. GV.IntVal = apf.bitcastToAPInt();
  599. }
  600. return GV;
  601. }
  602. case Instruction::SIToFP: {
  603. GenericValue GV = getConstantValue(Op0);
  604. if (CE->getType()->isFloatTy())
  605. GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
  606. else if (CE->getType()->isDoubleTy())
  607. GV.DoubleVal = GV.IntVal.signedRoundToDouble();
  608. else if (CE->getType()->isX86_FP80Ty()) {
  609. APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
  610. (void)apf.convertFromAPInt(GV.IntVal,
  611. true,
  612. APFloat::rmNearestTiesToEven);
  613. GV.IntVal = apf.bitcastToAPInt();
  614. }
  615. return GV;
  616. }
  617. case Instruction::FPToUI: // double->APInt conversion handles sign
  618. case Instruction::FPToSI: {
  619. GenericValue GV = getConstantValue(Op0);
  620. uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
  621. if (Op0->getType()->isFloatTy())
  622. GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
  623. else if (Op0->getType()->isDoubleTy())
  624. GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
  625. else if (Op0->getType()->isX86_FP80Ty()) {
  626. APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
  627. uint64_t v;
  628. bool ignored;
  629. (void)apf.convertToInteger(&v, BitWidth,
  630. CE->getOpcode()==Instruction::FPToSI,
  631. APFloat::rmTowardZero, &ignored);
  632. GV.IntVal = v; // endian?
  633. }
  634. return GV;
  635. }
  636. case Instruction::PtrToInt: {
  637. GenericValue GV = getConstantValue(Op0);
  638. uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType());
  639. assert(PtrWidth <= 64 && "Bad pointer width");
  640. GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
  641. uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType());
  642. GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
  643. return GV;
  644. }
  645. case Instruction::IntToPtr: {
  646. GenericValue GV = getConstantValue(Op0);
  647. uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType());
  648. GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
  649. assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
  650. GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
  651. return GV;
  652. }
  653. case Instruction::BitCast: {
  654. GenericValue GV = getConstantValue(Op0);
  655. Type* DestTy = CE->getType();
  656. switch (Op0->getType()->getTypeID()) {
  657. default: llvm_unreachable("Invalid bitcast operand");
  658. case Type::IntegerTyID:
  659. assert(DestTy->isFloatingPointTy() && "invalid bitcast");
  660. if (DestTy->isFloatTy())
  661. GV.FloatVal = GV.IntVal.bitsToFloat();
  662. else if (DestTy->isDoubleTy())
  663. GV.DoubleVal = GV.IntVal.bitsToDouble();
  664. break;
  665. case Type::FloatTyID:
  666. assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
  667. GV.IntVal = APInt::floatToBits(GV.FloatVal);
  668. break;
  669. case Type::DoubleTyID:
  670. assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
  671. GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
  672. break;
  673. case Type::PointerTyID:
  674. assert(DestTy->isPointerTy() && "Invalid bitcast");
  675. break; // getConstantValue(Op0) above already converted it
  676. }
  677. return GV;
  678. }
  679. case Instruction::Add:
  680. case Instruction::FAdd:
  681. case Instruction::Sub:
  682. case Instruction::FSub:
  683. case Instruction::Mul:
  684. case Instruction::FMul:
  685. case Instruction::UDiv:
  686. case Instruction::SDiv:
  687. case Instruction::URem:
  688. case Instruction::SRem:
  689. case Instruction::And:
  690. case Instruction::Or:
  691. case Instruction::Xor: {
  692. GenericValue LHS = getConstantValue(Op0);
  693. GenericValue RHS = getConstantValue(CE->getOperand(1));
  694. GenericValue GV;
  695. switch (CE->getOperand(0)->getType()->getTypeID()) {
  696. default: llvm_unreachable("Bad add type!");
  697. case Type::IntegerTyID:
  698. switch (CE->getOpcode()) {
  699. default: llvm_unreachable("Invalid integer opcode");
  700. case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
  701. case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
  702. case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
  703. case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
  704. case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
  705. case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
  706. case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
  707. case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
  708. case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
  709. case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
  710. }
  711. break;
  712. case Type::FloatTyID:
  713. switch (CE->getOpcode()) {
  714. default: llvm_unreachable("Invalid float opcode");
  715. case Instruction::FAdd:
  716. GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
  717. case Instruction::FSub:
  718. GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
  719. case Instruction::FMul:
  720. GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
  721. case Instruction::FDiv:
  722. GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
  723. case Instruction::FRem:
  724. GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
  725. }
  726. break;
  727. case Type::DoubleTyID:
  728. switch (CE->getOpcode()) {
  729. default: llvm_unreachable("Invalid double opcode");
  730. case Instruction::FAdd:
  731. GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
  732. case Instruction::FSub:
  733. GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
  734. case Instruction::FMul:
  735. GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
  736. case Instruction::FDiv:
  737. GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
  738. case Instruction::FRem:
  739. GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
  740. }
  741. break;
  742. case Type::X86_FP80TyID:
  743. case Type::PPC_FP128TyID:
  744. case Type::FP128TyID: {
  745. const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
  746. APFloat apfLHS = APFloat(Sem, LHS.IntVal);
  747. switch (CE->getOpcode()) {
  748. default: llvm_unreachable("Invalid long double opcode");
  749. case Instruction::FAdd:
  750. apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
  751. GV.IntVal = apfLHS.bitcastToAPInt();
  752. break;
  753. case Instruction::FSub:
  754. apfLHS.subtract(APFloat(Sem, RHS.IntVal),
  755. APFloat::rmNearestTiesToEven);
  756. GV.IntVal = apfLHS.bitcastToAPInt();
  757. break;
  758. case Instruction::FMul:
  759. apfLHS.multiply(APFloat(Sem, RHS.IntVal),
  760. APFloat::rmNearestTiesToEven);
  761. GV.IntVal = apfLHS.bitcastToAPInt();
  762. break;
  763. case Instruction::FDiv:
  764. apfLHS.divide(APFloat(Sem, RHS.IntVal),
  765. APFloat::rmNearestTiesToEven);
  766. GV.IntVal = apfLHS.bitcastToAPInt();
  767. break;
  768. case Instruction::FRem:
  769. apfLHS.mod(APFloat(Sem, RHS.IntVal),
  770. APFloat::rmNearestTiesToEven);
  771. GV.IntVal = apfLHS.bitcastToAPInt();
  772. break;
  773. }
  774. }
  775. break;
  776. }
  777. return GV;
  778. }
  779. default:
  780. break;
  781. }
  782. SmallString<256> Msg;
  783. raw_svector_ostream OS(Msg);
  784. OS << "ConstantExpr not handled: " << *CE;
  785. report_fatal_error(OS.str());
  786. }
  787. // Otherwise, we have a simple constant.
  788. GenericValue Result;
  789. switch (C->getType()->getTypeID()) {
  790. case Type::FloatTyID:
  791. Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
  792. break;
  793. case Type::DoubleTyID:
  794. Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
  795. break;
  796. case Type::X86_FP80TyID:
  797. case Type::FP128TyID:
  798. case Type::PPC_FP128TyID:
  799. Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
  800. break;
  801. case Type::IntegerTyID:
  802. Result.IntVal = cast<ConstantInt>(C)->getValue();
  803. break;
  804. case Type::PointerTyID:
  805. if (isa<ConstantPointerNull>(C))
  806. Result.PointerVal = nullptr;
  807. else if (const Function *F = dyn_cast<Function>(C))
  808. Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
  809. else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
  810. Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
  811. else
  812. llvm_unreachable("Unknown constant pointer type!");
  813. break;
  814. case Type::VectorTyID: {
  815. unsigned elemNum;
  816. Type* ElemTy;
  817. const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
  818. const ConstantVector *CV = dyn_cast<ConstantVector>(C);
  819. const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
  820. if (CDV) {
  821. elemNum = CDV->getNumElements();
  822. ElemTy = CDV->getElementType();
  823. } else if (CV || CAZ) {
  824. VectorType* VTy = dyn_cast<VectorType>(C->getType());
  825. elemNum = VTy->getNumElements();
  826. ElemTy = VTy->getElementType();
  827. } else {
  828. llvm_unreachable("Unknown constant vector type!");
  829. }
  830. Result.AggregateVal.resize(elemNum);
  831. // Check if vector holds floats.
  832. if(ElemTy->isFloatTy()) {
  833. if (CAZ) {
  834. GenericValue floatZero;
  835. floatZero.FloatVal = 0.f;
  836. std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
  837. floatZero);
  838. break;
  839. }
  840. if(CV) {
  841. for (unsigned i = 0; i < elemNum; ++i)
  842. if (!isa<UndefValue>(CV->getOperand(i)))
  843. Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
  844. CV->getOperand(i))->getValueAPF().convertToFloat();
  845. break;
  846. }
  847. if(CDV)
  848. for (unsigned i = 0; i < elemNum; ++i)
  849. Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
  850. break;
  851. }
  852. // Check if vector holds doubles.
  853. if (ElemTy->isDoubleTy()) {
  854. if (CAZ) {
  855. GenericValue doubleZero;
  856. doubleZero.DoubleVal = 0.0;
  857. std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
  858. doubleZero);
  859. break;
  860. }
  861. if(CV) {
  862. for (unsigned i = 0; i < elemNum; ++i)
  863. if (!isa<UndefValue>(CV->getOperand(i)))
  864. Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
  865. CV->getOperand(i))->getValueAPF().convertToDouble();
  866. break;
  867. }
  868. if(CDV)
  869. for (unsigned i = 0; i < elemNum; ++i)
  870. Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
  871. break;
  872. }
  873. // Check if vector holds integers.
  874. if (ElemTy->isIntegerTy()) {
  875. if (CAZ) {
  876. GenericValue intZero;
  877. intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
  878. std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
  879. intZero);
  880. break;
  881. }
  882. if(CV) {
  883. for (unsigned i = 0; i < elemNum; ++i)
  884. if (!isa<UndefValue>(CV->getOperand(i)))
  885. Result.AggregateVal[i].IntVal = cast<ConstantInt>(
  886. CV->getOperand(i))->getValue();
  887. else {
  888. Result.AggregateVal[i].IntVal =
  889. APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
  890. }
  891. break;
  892. }
  893. if(CDV)
  894. for (unsigned i = 0; i < elemNum; ++i)
  895. Result.AggregateVal[i].IntVal = APInt(
  896. CDV->getElementType()->getPrimitiveSizeInBits(),
  897. CDV->getElementAsInteger(i));
  898. break;
  899. }
  900. llvm_unreachable("Unknown constant pointer type!");
  901. }
  902. break;
  903. default:
  904. SmallString<256> Msg;
  905. raw_svector_ostream OS(Msg);
  906. OS << "ERROR: Constant unimplemented for type: " << *C->getType();
  907. report_fatal_error(OS.str());
  908. }
  909. return Result;
  910. }
  911. /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
  912. /// with the integer held in IntVal.
  913. static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
  914. unsigned StoreBytes) {
  915. assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
  916. const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
  917. if (sys::IsLittleEndianHost) {
  918. // Little-endian host - the source is ordered from LSB to MSB. Order the
  919. // destination from LSB to MSB: Do a straight copy.
  920. memcpy(Dst, Src, StoreBytes);
  921. } else {
  922. // Big-endian host - the source is an array of 64 bit words ordered from
  923. // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
  924. // from MSB to LSB: Reverse the word order, but not the bytes in a word.
  925. while (StoreBytes > sizeof(uint64_t)) {
  926. StoreBytes -= sizeof(uint64_t);
  927. // May not be aligned so use memcpy.
  928. memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
  929. Src += sizeof(uint64_t);
  930. }
  931. memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
  932. }
  933. }
  934. void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
  935. GenericValue *Ptr, Type *Ty) {
  936. const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
  937. switch (Ty->getTypeID()) {
  938. default:
  939. dbgs() << "Cannot store value of type " << *Ty << "!\n";
  940. break;
  941. case Type::IntegerTyID:
  942. StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
  943. break;
  944. case Type::FloatTyID:
  945. *((float*)Ptr) = Val.FloatVal;
  946. break;
  947. case Type::DoubleTyID:
  948. *((double*)Ptr) = Val.DoubleVal;
  949. break;
  950. case Type::X86_FP80TyID:
  951. memcpy(Ptr, Val.IntVal.getRawData(), 10);
  952. break;
  953. case Type::PointerTyID:
  954. // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
  955. if (StoreBytes != sizeof(PointerTy))
  956. memset(&(Ptr->PointerVal), 0, StoreBytes);
  957. *((PointerTy*)Ptr) = Val.PointerVal;
  958. break;
  959. case Type::VectorTyID:
  960. for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
  961. if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
  962. *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
  963. if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
  964. *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
  965. if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
  966. unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
  967. StoreIntToMemory(Val.AggregateVal[i].IntVal,
  968. (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
  969. }
  970. }
  971. break;
  972. }
  973. if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
  974. // Host and target are different endian - reverse the stored bytes.
  975. std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
  976. }
  977. /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
  978. /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
  979. static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
  980. assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
  981. uint8_t *Dst = reinterpret_cast<uint8_t *>(
  982. const_cast<uint64_t *>(IntVal.getRawData()));
  983. if (sys::IsLittleEndianHost)
  984. // Little-endian host - the destination must be ordered from LSB to MSB.
  985. // The source is ordered from LSB to MSB: Do a straight copy.
  986. memcpy(Dst, Src, LoadBytes);
  987. else {
  988. // Big-endian - the destination is an array of 64 bit words ordered from
  989. // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
  990. // ordered from MSB to LSB: Reverse the word order, but not the bytes in
  991. // a word.
  992. while (LoadBytes > sizeof(uint64_t)) {
  993. LoadBytes -= sizeof(uint64_t);
  994. // May not be aligned so use memcpy.
  995. memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
  996. Dst += sizeof(uint64_t);
  997. }
  998. memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
  999. }
  1000. }
  1001. /// FIXME: document
  1002. ///
  1003. void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
  1004. GenericValue *Ptr,
  1005. Type *Ty) {
  1006. const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
  1007. switch (Ty->getTypeID()) {
  1008. case Type::IntegerTyID:
  1009. // An APInt with all words initially zero.
  1010. Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
  1011. LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
  1012. break;
  1013. case Type::FloatTyID:
  1014. Result.FloatVal = *((float*)Ptr);
  1015. break;
  1016. case Type::DoubleTyID:
  1017. Result.DoubleVal = *((double*)Ptr);
  1018. break;
  1019. case Type::PointerTyID:
  1020. Result.PointerVal = *((PointerTy*)Ptr);
  1021. break;
  1022. case Type::X86_FP80TyID: {
  1023. // This is endian dependent, but it will only work on x86 anyway.
  1024. // FIXME: Will not trap if loading a signaling NaN.
  1025. uint64_t y[2];
  1026. memcpy(y, Ptr, 10);
  1027. Result.IntVal = APInt(80, y);
  1028. break;
  1029. }
  1030. case Type::VectorTyID: {
  1031. const VectorType *VT = cast<VectorType>(Ty);
  1032. const Type *ElemT = VT->getElementType();
  1033. const unsigned numElems = VT->getNumElements();
  1034. if (ElemT->isFloatTy()) {
  1035. Result.AggregateVal.resize(numElems);
  1036. for (unsigned i = 0; i < numElems; ++i)
  1037. Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
  1038. }
  1039. if (ElemT->isDoubleTy()) {
  1040. Result.AggregateVal.resize(numElems);
  1041. for (unsigned i = 0; i < numElems; ++i)
  1042. Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
  1043. }
  1044. if (ElemT->isIntegerTy()) {
  1045. GenericValue intZero;
  1046. const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
  1047. intZero.IntVal = APInt(elemBitWidth, 0);
  1048. Result.AggregateVal.resize(numElems, intZero);
  1049. for (unsigned i = 0; i < numElems; ++i)
  1050. LoadIntFromMemory(Result.AggregateVal[i].IntVal,
  1051. (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
  1052. }
  1053. break;
  1054. }
  1055. default:
  1056. SmallString<256> Msg;
  1057. raw_svector_ostream OS(Msg);
  1058. OS << "Cannot load value of type " << *Ty << "!";
  1059. report_fatal_error(OS.str());
  1060. }
  1061. }
  1062. void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
  1063. DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
  1064. DEBUG(Init->dump());
  1065. if (isa<UndefValue>(Init))
  1066. return;
  1067. if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
  1068. unsigned ElementSize =
  1069. getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
  1070. for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
  1071. InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
  1072. return;
  1073. }
  1074. if (isa<ConstantAggregateZero>(Init)) {
  1075. memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
  1076. return;
  1077. }
  1078. if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
  1079. unsigned ElementSize =
  1080. getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
  1081. for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
  1082. InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
  1083. return;
  1084. }
  1085. if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
  1086. const StructLayout *SL =
  1087. getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
  1088. for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
  1089. InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
  1090. return;
  1091. }
  1092. if (const ConstantDataSequential *CDS =
  1093. dyn_cast<ConstantDataSequential>(Init)) {
  1094. // CDS is already laid out in host memory order.
  1095. StringRef Data = CDS->getRawDataValues();
  1096. memcpy(Addr, Data.data(), Data.size());
  1097. return;
  1098. }
  1099. if (Init->getType()->isFirstClassType()) {
  1100. GenericValue Val = getConstantValue(Init);
  1101. StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
  1102. return;
  1103. }
  1104. DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
  1105. llvm_unreachable("Unknown constant type to initialize memory with!");
  1106. }
  1107. /// EmitGlobals - Emit all of the global variables to memory, storing their
  1108. /// addresses into GlobalAddress. This must make sure to copy the contents of
  1109. /// their initializers into the memory.
  1110. void ExecutionEngine::emitGlobals() {
  1111. // Loop over all of the global variables in the program, allocating the memory
  1112. // to hold them. If there is more than one module, do a prepass over globals
  1113. // to figure out how the different modules should link together.
  1114. std::map<std::pair<std::string, Type*>,
  1115. const GlobalValue*> LinkedGlobalsMap;
  1116. if (Modules.size() != 1) {
  1117. for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
  1118. Module &M = *Modules[m];
  1119. for (const auto &GV : M.globals()) {
  1120. if (GV.hasLocalLinkage() || GV.isDeclaration() ||
  1121. GV.hasAppendingLinkage() || !GV.hasName())
  1122. continue;// Ignore external globals and globals with internal linkage.
  1123. const GlobalValue *&GVEntry =
  1124. LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
  1125. // If this is the first time we've seen this global, it is the canonical
  1126. // version.
  1127. if (!GVEntry) {
  1128. GVEntry = &GV;
  1129. continue;
  1130. }
  1131. // If the existing global is strong, never replace it.
  1132. if (GVEntry->hasExternalLinkage())
  1133. continue;
  1134. // Otherwise, we know it's linkonce/weak, replace it if this is a strong
  1135. // symbol. FIXME is this right for common?
  1136. if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
  1137. GVEntry = &GV;
  1138. }
  1139. }
  1140. }
  1141. std::vector<const GlobalValue*> NonCanonicalGlobals;
  1142. for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
  1143. Module &M = *Modules[m];
  1144. for (const auto &GV : M.globals()) {
  1145. // In the multi-module case, see what this global maps to.
  1146. if (!LinkedGlobalsMap.empty()) {
  1147. if (const GlobalValue *GVEntry =
  1148. LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
  1149. // If something else is the canonical global, ignore this one.
  1150. if (GVEntry != &GV) {
  1151. NonCanonicalGlobals.push_back(&GV);
  1152. continue;
  1153. }
  1154. }
  1155. }
  1156. if (!GV.isDeclaration()) {
  1157. addGlobalMapping(&GV, getMemoryForGV(&GV));
  1158. } else {
  1159. // External variable reference. Try to use the dynamic loader to
  1160. // get a pointer to it.
  1161. if (void *SymAddr =
  1162. sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
  1163. addGlobalMapping(&GV, SymAddr);
  1164. else {
  1165. report_fatal_error("Could not resolve external global address: "
  1166. +GV.getName());
  1167. }
  1168. }
  1169. }
  1170. // If there are multiple modules, map the non-canonical globals to their
  1171. // canonical location.
  1172. if (!NonCanonicalGlobals.empty()) {
  1173. for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
  1174. const GlobalValue *GV = NonCanonicalGlobals[i];
  1175. const GlobalValue *CGV =
  1176. LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
  1177. void *Ptr = getPointerToGlobalIfAvailable(CGV);
  1178. assert(Ptr && "Canonical global wasn't codegen'd!");
  1179. addGlobalMapping(GV, Ptr);
  1180. }
  1181. }
  1182. // Now that all of the globals are set up in memory, loop through them all
  1183. // and initialize their contents.
  1184. for (const auto &GV : M.globals()) {
  1185. if (!GV.isDeclaration()) {
  1186. if (!LinkedGlobalsMap.empty()) {
  1187. if (const GlobalValue *GVEntry =
  1188. LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
  1189. if (GVEntry != &GV) // Not the canonical variable.
  1190. continue;
  1191. }
  1192. EmitGlobalVariable(&GV);
  1193. }
  1194. }
  1195. }
  1196. }
  1197. // EmitGlobalVariable - This method emits the specified global variable to the
  1198. // address specified in GlobalAddresses, or allocates new memory if it's not
  1199. // already in the map.
  1200. void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
  1201. void *GA = getPointerToGlobalIfAvailable(GV);
  1202. if (!GA) {
  1203. // If it's not already specified, allocate memory for the global.
  1204. GA = getMemoryForGV(GV);
  1205. // If we failed to allocate memory for this global, return.
  1206. if (!GA) return;
  1207. addGlobalMapping(GV, GA);
  1208. }
  1209. // Don't initialize if it's thread local, let the client do it.
  1210. if (!GV->isThreadLocal())
  1211. InitializeMemory(GV->getInitializer(), GA);
  1212. Type *ElTy = GV->getType()->getElementType();
  1213. size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
  1214. NumInitBytes += (unsigned)GVSize;
  1215. ++NumGlobals;
  1216. }