ExecutionEngine.cpp 37 KB

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