ExecutionEngine.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  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. #define DEBUG_TYPE "jit"
  15. #include "llvm/Constants.h"
  16. #include "llvm/DerivedTypes.h"
  17. #include "llvm/Module.h"
  18. #include "llvm/ModuleProvider.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/Config/alloca.h"
  21. #include "llvm/ExecutionEngine/ExecutionEngine.h"
  22. #include "llvm/ExecutionEngine/GenericValue.h"
  23. #include "llvm/Support/Debug.h"
  24. #include "llvm/Support/ErrorHandling.h"
  25. #include "llvm/Support/MutexGuard.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include "llvm/System/DynamicLibrary.h"
  28. #include "llvm/System/Host.h"
  29. #include "llvm/Target/TargetData.h"
  30. #include <cmath>
  31. #include <cstring>
  32. using namespace llvm;
  33. STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
  34. STATISTIC(NumGlobals , "Number of global vars initialized");
  35. ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
  36. ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
  37. ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
  38. ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) {
  39. LazyCompilationDisabled = false;
  40. GVCompilationDisabled = false;
  41. SymbolSearchingDisabled = false;
  42. DlsymStubsEnabled = false;
  43. Modules.push_back(P);
  44. assert(P && "ModuleProvider is null?");
  45. }
  46. ExecutionEngine::~ExecutionEngine() {
  47. clearAllGlobalMappings();
  48. for (unsigned i = 0, e = Modules.size(); i != e; ++i)
  49. delete Modules[i];
  50. }
  51. char* ExecutionEngine::getMemoryForGV(const GlobalVariable* GV) {
  52. const Type *ElTy = GV->getType()->getElementType();
  53. size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
  54. return new char[GVSize];
  55. }
  56. /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
  57. /// Relases the Module from the ModuleProvider, materializing it in the
  58. /// process, and returns the materialized Module.
  59. Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P,
  60. std::string *ErrInfo) {
  61. for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
  62. E = Modules.end(); I != E; ++I) {
  63. ModuleProvider *MP = *I;
  64. if (MP == P) {
  65. Modules.erase(I);
  66. clearGlobalMappingsFromModule(MP->getModule());
  67. return MP->releaseModule(ErrInfo);
  68. }
  69. }
  70. return NULL;
  71. }
  72. /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
  73. /// and deletes the ModuleProvider and owned Module. Avoids materializing
  74. /// the underlying module.
  75. void ExecutionEngine::deleteModuleProvider(ModuleProvider *P,
  76. std::string *ErrInfo) {
  77. for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
  78. E = Modules.end(); I != E; ++I) {
  79. ModuleProvider *MP = *I;
  80. if (MP == P) {
  81. Modules.erase(I);
  82. clearGlobalMappingsFromModule(MP->getModule());
  83. delete MP;
  84. return;
  85. }
  86. }
  87. }
  88. /// FindFunctionNamed - Search all of the active modules to find the one that
  89. /// defines FnName. This is very slow operation and shouldn't be used for
  90. /// general code.
  91. Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
  92. for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
  93. if (Function *F = Modules[i]->getModule()->getFunction(FnName))
  94. return F;
  95. }
  96. return 0;
  97. }
  98. /// addGlobalMapping - Tell the execution engine that the specified global is
  99. /// at the specified location. This is used internally as functions are JIT'd
  100. /// and as global variables are laid out in memory. It can and should also be
  101. /// used by clients of the EE that want to have an LLVM global overlay
  102. /// existing data in memory.
  103. void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
  104. MutexGuard locked(lock);
  105. DOUT << "JIT: Map \'" << GV->getNameStart() << "\' to [" << Addr << "]\n";
  106. void *&CurVal = state.getGlobalAddressMap(locked)[GV];
  107. assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
  108. CurVal = Addr;
  109. // If we are using the reverse mapping, add it too
  110. if (!state.getGlobalAddressReverseMap(locked).empty()) {
  111. const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
  112. assert((V == 0 || GV == 0) && "GlobalMapping already established!");
  113. V = GV;
  114. }
  115. }
  116. /// clearAllGlobalMappings - Clear all global mappings and start over again
  117. /// use in dynamic compilation scenarios when you want to move globals
  118. void ExecutionEngine::clearAllGlobalMappings() {
  119. MutexGuard locked(lock);
  120. state.getGlobalAddressMap(locked).clear();
  121. state.getGlobalAddressReverseMap(locked).clear();
  122. }
  123. /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
  124. /// particular module, because it has been removed from the JIT.
  125. void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
  126. MutexGuard locked(lock);
  127. for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
  128. state.getGlobalAddressMap(locked).erase(FI);
  129. state.getGlobalAddressReverseMap(locked).erase(FI);
  130. }
  131. for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
  132. GI != GE; ++GI) {
  133. state.getGlobalAddressMap(locked).erase(GI);
  134. state.getGlobalAddressReverseMap(locked).erase(GI);
  135. }
  136. }
  137. /// updateGlobalMapping - Replace an existing mapping for GV with a new
  138. /// address. This updates both maps as required. If "Addr" is null, the
  139. /// entry for the global is removed from the mappings.
  140. void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
  141. MutexGuard locked(lock);
  142. std::map<const GlobalValue*, void *> &Map = state.getGlobalAddressMap(locked);
  143. // Deleting from the mapping?
  144. if (Addr == 0) {
  145. std::map<const GlobalValue*, void *>::iterator I = Map.find(GV);
  146. void *OldVal;
  147. if (I == Map.end())
  148. OldVal = 0;
  149. else {
  150. OldVal = I->second;
  151. Map.erase(I);
  152. }
  153. if (!state.getGlobalAddressReverseMap(locked).empty())
  154. state.getGlobalAddressReverseMap(locked).erase(Addr);
  155. return OldVal;
  156. }
  157. void *&CurVal = Map[GV];
  158. void *OldVal = CurVal;
  159. if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
  160. state.getGlobalAddressReverseMap(locked).erase(CurVal);
  161. CurVal = Addr;
  162. // If we are using the reverse mapping, add it too
  163. if (!state.getGlobalAddressReverseMap(locked).empty()) {
  164. const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
  165. assert((V == 0 || GV == 0) && "GlobalMapping already established!");
  166. V = GV;
  167. }
  168. return OldVal;
  169. }
  170. /// getPointerToGlobalIfAvailable - This returns the address of the specified
  171. /// global value if it is has already been codegen'd, otherwise it returns null.
  172. ///
  173. void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
  174. MutexGuard locked(lock);
  175. std::map<const GlobalValue*, void*>::iterator I =
  176. state.getGlobalAddressMap(locked).find(GV);
  177. return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
  178. }
  179. /// getGlobalValueAtAddress - Return the LLVM global value object that starts
  180. /// at the specified address.
  181. ///
  182. const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
  183. MutexGuard locked(lock);
  184. // If we haven't computed the reverse mapping yet, do so first.
  185. if (state.getGlobalAddressReverseMap(locked).empty()) {
  186. for (std::map<const GlobalValue*, void *>::iterator
  187. I = state.getGlobalAddressMap(locked).begin(),
  188. E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
  189. state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
  190. I->first));
  191. }
  192. std::map<void *, const GlobalValue*>::iterator I =
  193. state.getGlobalAddressReverseMap(locked).find(Addr);
  194. return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
  195. }
  196. // CreateArgv - Turn a vector of strings into a nice argv style array of
  197. // pointers to null terminated strings.
  198. //
  199. static void *CreateArgv(ExecutionEngine *EE,
  200. const std::vector<std::string> &InputArgv) {
  201. unsigned PtrSize = EE->getTargetData()->getPointerSize();
  202. char *Result = new char[(InputArgv.size()+1)*PtrSize];
  203. DOUT << "JIT: ARGV = " << (void*)Result << "\n";
  204. const Type *SBytePtr = PointerType::getUnqual(Type::Int8Ty);
  205. for (unsigned i = 0; i != InputArgv.size(); ++i) {
  206. unsigned Size = InputArgv[i].size()+1;
  207. char *Dest = new char[Size];
  208. DOUT << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n";
  209. std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
  210. Dest[Size-1] = 0;
  211. // Endian safe: Result[i] = (PointerTy)Dest;
  212. EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
  213. SBytePtr);
  214. }
  215. // Null terminate it
  216. EE->StoreValueToMemory(PTOGV(0),
  217. (GenericValue*)(Result+InputArgv.size()*PtrSize),
  218. SBytePtr);
  219. return Result;
  220. }
  221. /// runStaticConstructorsDestructors - This method is used to execute all of
  222. /// the static constructors or destructors for a module, depending on the
  223. /// value of isDtors.
  224. void ExecutionEngine::runStaticConstructorsDestructors(Module *module, bool isDtors) {
  225. const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
  226. // Execute global ctors/dtors for each module in the program.
  227. GlobalVariable *GV = module->getNamedGlobal(Name);
  228. // If this global has internal linkage, or if it has a use, then it must be
  229. // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
  230. // this is the case, don't execute any of the global ctors, __main will do
  231. // it.
  232. if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
  233. // Should be an array of '{ int, void ()* }' structs. The first value is
  234. // the init priority, which we ignore.
  235. ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
  236. if (!InitList) return;
  237. for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
  238. if (ConstantStruct *CS =
  239. dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
  240. if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
  241. Constant *FP = CS->getOperand(1);
  242. if (FP->isNullValue())
  243. break; // Found a null terminator, exit.
  244. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
  245. if (CE->isCast())
  246. FP = CE->getOperand(0);
  247. if (Function *F = dyn_cast<Function>(FP)) {
  248. // Execute the ctor/dtor function!
  249. runFunction(F, std::vector<GenericValue>());
  250. }
  251. }
  252. }
  253. /// runStaticConstructorsDestructors - This method is used to execute all of
  254. /// the static constructors or destructors for a program, depending on the
  255. /// value of isDtors.
  256. void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
  257. // Execute global ctors/dtors for each module in the program.
  258. for (unsigned m = 0, e = Modules.size(); m != e; ++m)
  259. runStaticConstructorsDestructors(Modules[m]->getModule(), isDtors);
  260. }
  261. #ifndef NDEBUG
  262. /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
  263. static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
  264. unsigned PtrSize = EE->getTargetData()->getPointerSize();
  265. for (unsigned i = 0; i < PtrSize; ++i)
  266. if (*(i + (uint8_t*)Loc))
  267. return false;
  268. return true;
  269. }
  270. #endif
  271. /// runFunctionAsMain - This is a helper function which wraps runFunction to
  272. /// handle the common task of starting up main with the specified argc, argv,
  273. /// and envp parameters.
  274. int ExecutionEngine::runFunctionAsMain(Function *Fn,
  275. const std::vector<std::string> &argv,
  276. const char * const * envp) {
  277. std::vector<GenericValue> GVArgs;
  278. GenericValue GVArgc;
  279. GVArgc.IntVal = APInt(32, argv.size());
  280. // Check main() type
  281. unsigned NumArgs = Fn->getFunctionType()->getNumParams();
  282. const FunctionType *FTy = Fn->getFunctionType();
  283. const Type* PPInt8Ty =
  284. PointerType::getUnqual(PointerType::getUnqual(Type::Int8Ty));
  285. switch (NumArgs) {
  286. case 3:
  287. if (FTy->getParamType(2) != PPInt8Ty) {
  288. llvm_report_error("Invalid type for third argument of main() supplied");
  289. }
  290. // FALLS THROUGH
  291. case 2:
  292. if (FTy->getParamType(1) != PPInt8Ty) {
  293. llvm_report_error("Invalid type for second argument of main() supplied");
  294. }
  295. // FALLS THROUGH
  296. case 1:
  297. if (FTy->getParamType(0) != Type::Int32Ty) {
  298. llvm_report_error("Invalid type for first argument of main() supplied");
  299. }
  300. // FALLS THROUGH
  301. case 0:
  302. if (!isa<IntegerType>(FTy->getReturnType()) &&
  303. FTy->getReturnType() != Type::VoidTy) {
  304. llvm_report_error("Invalid return type of main() supplied");
  305. }
  306. break;
  307. default:
  308. llvm_report_error("Invalid number of arguments of main() supplied");
  309. }
  310. if (NumArgs) {
  311. GVArgs.push_back(GVArgc); // Arg #0 = argc.
  312. if (NumArgs > 1) {
  313. GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
  314. assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
  315. "argv[0] was null after CreateArgv");
  316. if (NumArgs > 2) {
  317. std::vector<std::string> EnvVars;
  318. for (unsigned i = 0; envp[i]; ++i)
  319. EnvVars.push_back(envp[i]);
  320. GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
  321. }
  322. }
  323. }
  324. return runFunction(Fn, GVArgs).IntVal.getZExtValue();
  325. }
  326. /// If possible, create a JIT, unless the caller specifically requests an
  327. /// Interpreter or there's an error. If even an Interpreter cannot be created,
  328. /// NULL is returned.
  329. ///
  330. ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
  331. bool ForceInterpreter,
  332. std::string *ErrorStr,
  333. CodeGenOpt::Level OptLevel,
  334. bool GVsWithCode) {
  335. ExecutionEngine *EE = 0;
  336. // Make sure we can resolve symbols in the program as well. The zero arg
  337. // to the function tells DynamicLibrary to load the program, not a library.
  338. if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
  339. return 0;
  340. // Unless the interpreter was explicitly selected, try making a JIT.
  341. if (!ForceInterpreter && JITCtor)
  342. EE = JITCtor(MP, ErrorStr, OptLevel, GVsWithCode);
  343. // If we can't make a JIT, make an interpreter instead.
  344. if (EE == 0 && InterpCtor)
  345. EE = InterpCtor(MP, ErrorStr, OptLevel, GVsWithCode);
  346. return EE;
  347. }
  348. ExecutionEngine *ExecutionEngine::create(Module *M) {
  349. return create(new ExistingModuleProvider(M));
  350. }
  351. /// getPointerToGlobal - This returns the address of the specified global
  352. /// value. This may involve code generation if it's a function.
  353. ///
  354. void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
  355. if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
  356. return getPointerToFunction(F);
  357. MutexGuard locked(lock);
  358. void *p = state.getGlobalAddressMap(locked)[GV];
  359. if (p)
  360. return p;
  361. // Global variable might have been added since interpreter started.
  362. if (GlobalVariable *GVar =
  363. const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
  364. EmitGlobalVariable(GVar);
  365. else
  366. LLVM_UNREACHABLE("Global hasn't had an address allocated yet!");
  367. return state.getGlobalAddressMap(locked)[GV];
  368. }
  369. /// This function converts a Constant* into a GenericValue. The interesting
  370. /// part is if C is a ConstantExpr.
  371. /// @brief Get a GenericValue for a Constant*
  372. GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
  373. // If its undefined, return the garbage.
  374. if (isa<UndefValue>(C))
  375. return GenericValue();
  376. // If the value is a ConstantExpr
  377. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  378. Constant *Op0 = CE->getOperand(0);
  379. switch (CE->getOpcode()) {
  380. case Instruction::GetElementPtr: {
  381. // Compute the index
  382. GenericValue Result = getConstantValue(Op0);
  383. SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
  384. uint64_t Offset =
  385. TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
  386. char* tmp = (char*) Result.PointerVal;
  387. Result = PTOGV(tmp + Offset);
  388. return Result;
  389. }
  390. case Instruction::Trunc: {
  391. GenericValue GV = getConstantValue(Op0);
  392. uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
  393. GV.IntVal = GV.IntVal.trunc(BitWidth);
  394. return GV;
  395. }
  396. case Instruction::ZExt: {
  397. GenericValue GV = getConstantValue(Op0);
  398. uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
  399. GV.IntVal = GV.IntVal.zext(BitWidth);
  400. return GV;
  401. }
  402. case Instruction::SExt: {
  403. GenericValue GV = getConstantValue(Op0);
  404. uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
  405. GV.IntVal = GV.IntVal.sext(BitWidth);
  406. return GV;
  407. }
  408. case Instruction::FPTrunc: {
  409. // FIXME long double
  410. GenericValue GV = getConstantValue(Op0);
  411. GV.FloatVal = float(GV.DoubleVal);
  412. return GV;
  413. }
  414. case Instruction::FPExt:{
  415. // FIXME long double
  416. GenericValue GV = getConstantValue(Op0);
  417. GV.DoubleVal = double(GV.FloatVal);
  418. return GV;
  419. }
  420. case Instruction::UIToFP: {
  421. GenericValue GV = getConstantValue(Op0);
  422. if (CE->getType() == Type::FloatTy)
  423. GV.FloatVal = float(GV.IntVal.roundToDouble());
  424. else if (CE->getType() == Type::DoubleTy)
  425. GV.DoubleVal = GV.IntVal.roundToDouble();
  426. else if (CE->getType() == Type::X86_FP80Ty) {
  427. const uint64_t zero[] = {0, 0};
  428. APFloat apf = APFloat(APInt(80, 2, zero));
  429. (void)apf.convertFromAPInt(GV.IntVal,
  430. false,
  431. APFloat::rmNearestTiesToEven);
  432. GV.IntVal = apf.bitcastToAPInt();
  433. }
  434. return GV;
  435. }
  436. case Instruction::SIToFP: {
  437. GenericValue GV = getConstantValue(Op0);
  438. if (CE->getType() == Type::FloatTy)
  439. GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
  440. else if (CE->getType() == Type::DoubleTy)
  441. GV.DoubleVal = GV.IntVal.signedRoundToDouble();
  442. else if (CE->getType() == Type::X86_FP80Ty) {
  443. const uint64_t zero[] = { 0, 0};
  444. APFloat apf = APFloat(APInt(80, 2, zero));
  445. (void)apf.convertFromAPInt(GV.IntVal,
  446. true,
  447. APFloat::rmNearestTiesToEven);
  448. GV.IntVal = apf.bitcastToAPInt();
  449. }
  450. return GV;
  451. }
  452. case Instruction::FPToUI: // double->APInt conversion handles sign
  453. case Instruction::FPToSI: {
  454. GenericValue GV = getConstantValue(Op0);
  455. uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
  456. if (Op0->getType() == Type::FloatTy)
  457. GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
  458. else if (Op0->getType() == Type::DoubleTy)
  459. GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
  460. else if (Op0->getType() == Type::X86_FP80Ty) {
  461. APFloat apf = APFloat(GV.IntVal);
  462. uint64_t v;
  463. bool ignored;
  464. (void)apf.convertToInteger(&v, BitWidth,
  465. CE->getOpcode()==Instruction::FPToSI,
  466. APFloat::rmTowardZero, &ignored);
  467. GV.IntVal = v; // endian?
  468. }
  469. return GV;
  470. }
  471. case Instruction::PtrToInt: {
  472. GenericValue GV = getConstantValue(Op0);
  473. uint32_t PtrWidth = TD->getPointerSizeInBits();
  474. GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
  475. return GV;
  476. }
  477. case Instruction::IntToPtr: {
  478. GenericValue GV = getConstantValue(Op0);
  479. uint32_t PtrWidth = TD->getPointerSizeInBits();
  480. if (PtrWidth != GV.IntVal.getBitWidth())
  481. GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
  482. assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
  483. GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
  484. return GV;
  485. }
  486. case Instruction::BitCast: {
  487. GenericValue GV = getConstantValue(Op0);
  488. const Type* DestTy = CE->getType();
  489. switch (Op0->getType()->getTypeID()) {
  490. default: LLVM_UNREACHABLE("Invalid bitcast operand");
  491. case Type::IntegerTyID:
  492. assert(DestTy->isFloatingPoint() && "invalid bitcast");
  493. if (DestTy == Type::FloatTy)
  494. GV.FloatVal = GV.IntVal.bitsToFloat();
  495. else if (DestTy == Type::DoubleTy)
  496. GV.DoubleVal = GV.IntVal.bitsToDouble();
  497. break;
  498. case Type::FloatTyID:
  499. assert(DestTy == Type::Int32Ty && "Invalid bitcast");
  500. GV.IntVal.floatToBits(GV.FloatVal);
  501. break;
  502. case Type::DoubleTyID:
  503. assert(DestTy == Type::Int64Ty && "Invalid bitcast");
  504. GV.IntVal.doubleToBits(GV.DoubleVal);
  505. break;
  506. case Type::PointerTyID:
  507. assert(isa<PointerType>(DestTy) && "Invalid bitcast");
  508. break; // getConstantValue(Op0) above already converted it
  509. }
  510. return GV;
  511. }
  512. case Instruction::Add:
  513. case Instruction::FAdd:
  514. case Instruction::Sub:
  515. case Instruction::FSub:
  516. case Instruction::Mul:
  517. case Instruction::FMul:
  518. case Instruction::UDiv:
  519. case Instruction::SDiv:
  520. case Instruction::URem:
  521. case Instruction::SRem:
  522. case Instruction::And:
  523. case Instruction::Or:
  524. case Instruction::Xor: {
  525. GenericValue LHS = getConstantValue(Op0);
  526. GenericValue RHS = getConstantValue(CE->getOperand(1));
  527. GenericValue GV;
  528. switch (CE->getOperand(0)->getType()->getTypeID()) {
  529. default: LLVM_UNREACHABLE("Bad add type!");
  530. case Type::IntegerTyID:
  531. switch (CE->getOpcode()) {
  532. default: LLVM_UNREACHABLE("Invalid integer opcode");
  533. case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
  534. case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
  535. case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
  536. case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
  537. case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
  538. case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
  539. case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
  540. case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
  541. case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
  542. case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
  543. }
  544. break;
  545. case Type::FloatTyID:
  546. switch (CE->getOpcode()) {
  547. default: LLVM_UNREACHABLE("Invalid float opcode");
  548. case Instruction::FAdd:
  549. GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
  550. case Instruction::FSub:
  551. GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
  552. case Instruction::FMul:
  553. GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
  554. case Instruction::FDiv:
  555. GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
  556. case Instruction::FRem:
  557. GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
  558. }
  559. break;
  560. case Type::DoubleTyID:
  561. switch (CE->getOpcode()) {
  562. default: LLVM_UNREACHABLE("Invalid double opcode");
  563. case Instruction::FAdd:
  564. GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
  565. case Instruction::FSub:
  566. GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
  567. case Instruction::FMul:
  568. GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
  569. case Instruction::FDiv:
  570. GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
  571. case Instruction::FRem:
  572. GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
  573. }
  574. break;
  575. case Type::X86_FP80TyID:
  576. case Type::PPC_FP128TyID:
  577. case Type::FP128TyID: {
  578. APFloat apfLHS = APFloat(LHS.IntVal);
  579. switch (CE->getOpcode()) {
  580. default: LLVM_UNREACHABLE("Invalid long double opcode");llvm_unreachable();
  581. case Instruction::FAdd:
  582. apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
  583. GV.IntVal = apfLHS.bitcastToAPInt();
  584. break;
  585. case Instruction::FSub:
  586. apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
  587. GV.IntVal = apfLHS.bitcastToAPInt();
  588. break;
  589. case Instruction::FMul:
  590. apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
  591. GV.IntVal = apfLHS.bitcastToAPInt();
  592. break;
  593. case Instruction::FDiv:
  594. apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
  595. GV.IntVal = apfLHS.bitcastToAPInt();
  596. break;
  597. case Instruction::FRem:
  598. apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
  599. GV.IntVal = apfLHS.bitcastToAPInt();
  600. break;
  601. }
  602. }
  603. break;
  604. }
  605. return GV;
  606. }
  607. default:
  608. break;
  609. }
  610. std::string msg;
  611. raw_string_ostream Msg(msg);
  612. Msg << "ConstantExpr not handled: " << *CE;
  613. llvm_report_error(Msg.str());
  614. }
  615. GenericValue Result;
  616. switch (C->getType()->getTypeID()) {
  617. case Type::FloatTyID:
  618. Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
  619. break;
  620. case Type::DoubleTyID:
  621. Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
  622. break;
  623. case Type::X86_FP80TyID:
  624. case Type::FP128TyID:
  625. case Type::PPC_FP128TyID:
  626. Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
  627. break;
  628. case Type::IntegerTyID:
  629. Result.IntVal = cast<ConstantInt>(C)->getValue();
  630. break;
  631. case Type::PointerTyID:
  632. if (isa<ConstantPointerNull>(C))
  633. Result.PointerVal = 0;
  634. else if (const Function *F = dyn_cast<Function>(C))
  635. Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
  636. else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
  637. Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
  638. else
  639. LLVM_UNREACHABLE("Unknown constant pointer type!");
  640. break;
  641. default:
  642. std::string msg;
  643. raw_string_ostream Msg(msg);
  644. Msg << "ERROR: Constant unimplemented for type: " << *C->getType();
  645. llvm_report_error(Msg.str());
  646. }
  647. return Result;
  648. }
  649. /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
  650. /// with the integer held in IntVal.
  651. static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
  652. unsigned StoreBytes) {
  653. assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
  654. uint8_t *Src = (uint8_t *)IntVal.getRawData();
  655. if (sys::isLittleEndianHost())
  656. // Little-endian host - the source is ordered from LSB to MSB. Order the
  657. // destination from LSB to MSB: Do a straight copy.
  658. memcpy(Dst, Src, StoreBytes);
  659. else {
  660. // Big-endian host - the source is an array of 64 bit words ordered from
  661. // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
  662. // from MSB to LSB: Reverse the word order, but not the bytes in a word.
  663. while (StoreBytes > sizeof(uint64_t)) {
  664. StoreBytes -= sizeof(uint64_t);
  665. // May not be aligned so use memcpy.
  666. memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
  667. Src += sizeof(uint64_t);
  668. }
  669. memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
  670. }
  671. }
  672. /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
  673. /// is the address of the memory at which to store Val, cast to GenericValue *.
  674. /// It is not a pointer to a GenericValue containing the address at which to
  675. /// store Val.
  676. void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
  677. GenericValue *Ptr, const Type *Ty) {
  678. const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
  679. switch (Ty->getTypeID()) {
  680. case Type::IntegerTyID:
  681. StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
  682. break;
  683. case Type::FloatTyID:
  684. *((float*)Ptr) = Val.FloatVal;
  685. break;
  686. case Type::DoubleTyID:
  687. *((double*)Ptr) = Val.DoubleVal;
  688. break;
  689. case Type::X86_FP80TyID:
  690. memcpy(Ptr, Val.IntVal.getRawData(), 10);
  691. break;
  692. case Type::PointerTyID:
  693. // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
  694. if (StoreBytes != sizeof(PointerTy))
  695. memset(Ptr, 0, StoreBytes);
  696. *((PointerTy*)Ptr) = Val.PointerVal;
  697. break;
  698. default:
  699. cerr << "Cannot store value of type " << *Ty << "!\n";
  700. }
  701. if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
  702. // Host and target are different endian - reverse the stored bytes.
  703. std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
  704. }
  705. /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
  706. /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
  707. static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
  708. assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
  709. uint8_t *Dst = (uint8_t *)IntVal.getRawData();
  710. if (sys::isLittleEndianHost())
  711. // Little-endian host - the destination must be ordered from LSB to MSB.
  712. // The source is ordered from LSB to MSB: Do a straight copy.
  713. memcpy(Dst, Src, LoadBytes);
  714. else {
  715. // Big-endian - the destination is an array of 64 bit words ordered from
  716. // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
  717. // ordered from MSB to LSB: Reverse the word order, but not the bytes in
  718. // a word.
  719. while (LoadBytes > sizeof(uint64_t)) {
  720. LoadBytes -= sizeof(uint64_t);
  721. // May not be aligned so use memcpy.
  722. memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
  723. Dst += sizeof(uint64_t);
  724. }
  725. memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
  726. }
  727. }
  728. /// FIXME: document
  729. ///
  730. void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
  731. GenericValue *Ptr,
  732. const Type *Ty) {
  733. const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
  734. if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian()) {
  735. // Host and target are different endian - reverse copy the stored
  736. // bytes into a buffer, and load from that.
  737. uint8_t *Src = (uint8_t*)Ptr;
  738. uint8_t *Buf = (uint8_t*)alloca(LoadBytes);
  739. std::reverse_copy(Src, Src + LoadBytes, Buf);
  740. Ptr = (GenericValue*)Buf;
  741. }
  742. switch (Ty->getTypeID()) {
  743. case Type::IntegerTyID:
  744. // An APInt with all words initially zero.
  745. Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
  746. LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
  747. break;
  748. case Type::FloatTyID:
  749. Result.FloatVal = *((float*)Ptr);
  750. break;
  751. case Type::DoubleTyID:
  752. Result.DoubleVal = *((double*)Ptr);
  753. break;
  754. case Type::PointerTyID:
  755. Result.PointerVal = *((PointerTy*)Ptr);
  756. break;
  757. case Type::X86_FP80TyID: {
  758. // This is endian dependent, but it will only work on x86 anyway.
  759. // FIXME: Will not trap if loading a signaling NaN.
  760. uint64_t y[2];
  761. memcpy(y, Ptr, 10);
  762. Result.IntVal = APInt(80, 2, y);
  763. break;
  764. }
  765. default:
  766. std::string msg;
  767. raw_string_ostream Msg(msg);
  768. Msg << "Cannot load value of type " << *Ty << "!";
  769. llvm_report_error(Msg.str());
  770. }
  771. }
  772. // InitializeMemory - Recursive function to apply a Constant value into the
  773. // specified memory location...
  774. //
  775. void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
  776. DOUT << "JIT: Initializing " << Addr << " ";
  777. DEBUG(Init->dump());
  778. if (isa<UndefValue>(Init)) {
  779. return;
  780. } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
  781. unsigned ElementSize =
  782. getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
  783. for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
  784. InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
  785. return;
  786. } else if (isa<ConstantAggregateZero>(Init)) {
  787. memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
  788. return;
  789. } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
  790. unsigned ElementSize =
  791. getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
  792. for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
  793. InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
  794. return;
  795. } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
  796. const StructLayout *SL =
  797. getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
  798. for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
  799. InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
  800. return;
  801. } else if (Init->getType()->isFirstClassType()) {
  802. GenericValue Val = getConstantValue(Init);
  803. StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
  804. return;
  805. }
  806. cerr << "Bad Type: " << *Init->getType() << "\n";
  807. LLVM_UNREACHABLE("Unknown constant type to initialize memory with!");
  808. }
  809. /// EmitGlobals - Emit all of the global variables to memory, storing their
  810. /// addresses into GlobalAddress. This must make sure to copy the contents of
  811. /// their initializers into the memory.
  812. ///
  813. void ExecutionEngine::emitGlobals() {
  814. // Loop over all of the global variables in the program, allocating the memory
  815. // to hold them. If there is more than one module, do a prepass over globals
  816. // to figure out how the different modules should link together.
  817. //
  818. std::map<std::pair<std::string, const Type*>,
  819. const GlobalValue*> LinkedGlobalsMap;
  820. if (Modules.size() != 1) {
  821. for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
  822. Module &M = *Modules[m]->getModule();
  823. for (Module::const_global_iterator I = M.global_begin(),
  824. E = M.global_end(); I != E; ++I) {
  825. const GlobalValue *GV = I;
  826. if (GV->hasLocalLinkage() || GV->isDeclaration() ||
  827. GV->hasAppendingLinkage() || !GV->hasName())
  828. continue;// Ignore external globals and globals with internal linkage.
  829. const GlobalValue *&GVEntry =
  830. LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
  831. // If this is the first time we've seen this global, it is the canonical
  832. // version.
  833. if (!GVEntry) {
  834. GVEntry = GV;
  835. continue;
  836. }
  837. // If the existing global is strong, never replace it.
  838. if (GVEntry->hasExternalLinkage() ||
  839. GVEntry->hasDLLImportLinkage() ||
  840. GVEntry->hasDLLExportLinkage())
  841. continue;
  842. // Otherwise, we know it's linkonce/weak, replace it if this is a strong
  843. // symbol. FIXME is this right for common?
  844. if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
  845. GVEntry = GV;
  846. }
  847. }
  848. }
  849. std::vector<const GlobalValue*> NonCanonicalGlobals;
  850. for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
  851. Module &M = *Modules[m]->getModule();
  852. for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
  853. I != E; ++I) {
  854. // In the multi-module case, see what this global maps to.
  855. if (!LinkedGlobalsMap.empty()) {
  856. if (const GlobalValue *GVEntry =
  857. LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
  858. // If something else is the canonical global, ignore this one.
  859. if (GVEntry != &*I) {
  860. NonCanonicalGlobals.push_back(I);
  861. continue;
  862. }
  863. }
  864. }
  865. if (!I->isDeclaration()) {
  866. addGlobalMapping(I, getMemoryForGV(I));
  867. } else {
  868. // External variable reference. Try to use the dynamic loader to
  869. // get a pointer to it.
  870. if (void *SymAddr =
  871. sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
  872. addGlobalMapping(I, SymAddr);
  873. else {
  874. llvm_report_error("Could not resolve external global address: "
  875. +I->getName());
  876. }
  877. }
  878. }
  879. // If there are multiple modules, map the non-canonical globals to their
  880. // canonical location.
  881. if (!NonCanonicalGlobals.empty()) {
  882. for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
  883. const GlobalValue *GV = NonCanonicalGlobals[i];
  884. const GlobalValue *CGV =
  885. LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
  886. void *Ptr = getPointerToGlobalIfAvailable(CGV);
  887. assert(Ptr && "Canonical global wasn't codegen'd!");
  888. addGlobalMapping(GV, Ptr);
  889. }
  890. }
  891. // Now that all of the globals are set up in memory, loop through them all
  892. // and initialize their contents.
  893. for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
  894. I != E; ++I) {
  895. if (!I->isDeclaration()) {
  896. if (!LinkedGlobalsMap.empty()) {
  897. if (const GlobalValue *GVEntry =
  898. LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
  899. if (GVEntry != &*I) // Not the canonical variable.
  900. continue;
  901. }
  902. EmitGlobalVariable(I);
  903. }
  904. }
  905. }
  906. }
  907. // EmitGlobalVariable - This method emits the specified global variable to the
  908. // address specified in GlobalAddresses, or allocates new memory if it's not
  909. // already in the map.
  910. void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
  911. void *GA = getPointerToGlobalIfAvailable(GV);
  912. if (GA == 0) {
  913. // If it's not already specified, allocate memory for the global.
  914. GA = getMemoryForGV(GV);
  915. addGlobalMapping(GV, GA);
  916. }
  917. // Don't initialize if it's thread local, let the client do it.
  918. if (!GV->isThreadLocal())
  919. InitializeMemory(GV->getInitializer(), GA);
  920. const Type *ElTy = GV->getType()->getElementType();
  921. size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
  922. NumInitBytes += (unsigned)GVSize;
  923. ++NumGlobals;
  924. }