ExecutionEngine.cpp 39 KB

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