ExecutionEngine.cpp 40 KB

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