ExecutionEngine.cpp 48 KB

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