1 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the common interface used by the various execution engine
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "jit"
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/ExecutionEngine.h"
23 #include "llvm/ExecutionEngine/GenericValue.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/MutexGuard.h"
26 #include "llvm/System/DynamicLibrary.h"
27 #include "llvm/System/Host.h"
28 #include "llvm/Target/TargetData.h"
32 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
33 STATISTIC(NumGlobals , "Number of global vars initialized");
35 ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
36 ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
38 ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) {
39 LazyCompilationDisabled = false;
41 assert(P && "ModuleProvider is null?");
44 ExecutionEngine::~ExecutionEngine() {
45 clearAllGlobalMappings();
46 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
50 /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
51 /// Release module from ModuleProvider.
52 Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P,
53 std::string *ErrInfo) {
54 for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
55 E = Modules.end(); I != E; ++I) {
56 ModuleProvider *MP = *I;
59 return MP->releaseModule(ErrInfo);
65 /// FindFunctionNamed - Search all of the active modules to find the one that
66 /// defines FnName. This is very slow operation and shouldn't be used for
68 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
69 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
70 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
77 /// addGlobalMapping - Tell the execution engine that the specified global is
78 /// at the specified location. This is used internally as functions are JIT'd
79 /// and as global variables are laid out in memory. It can and should also be
80 /// used by clients of the EE that want to have an LLVM global overlay
81 /// existing data in memory.
82 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
83 MutexGuard locked(lock);
85 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
86 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
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!");
97 /// clearAllGlobalMappings - Clear all global mappings and start over again
98 /// use in dynamic compilation scenarios when you want to move globals
99 void ExecutionEngine::clearAllGlobalMappings() {
100 MutexGuard locked(lock);
102 state.getGlobalAddressMap(locked).clear();
103 state.getGlobalAddressReverseMap(locked).clear();
106 /// updateGlobalMapping - Replace an existing mapping for GV with a new
107 /// address. This updates both maps as required. If "Addr" is null, the
108 /// entry for the global is removed from the mappings.
109 void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
110 MutexGuard locked(lock);
112 // Deleting from the mapping?
114 state.getGlobalAddressMap(locked).erase(GV);
115 if (!state.getGlobalAddressReverseMap(locked).empty())
116 state.getGlobalAddressReverseMap(locked).erase(Addr);
120 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
121 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
122 state.getGlobalAddressReverseMap(locked).erase(CurVal);
125 // If we are using the reverse mapping, add it too
126 if (!state.getGlobalAddressReverseMap(locked).empty()) {
127 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
128 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
133 /// getPointerToGlobalIfAvailable - This returns the address of the specified
134 /// global value if it is has already been codegen'd, otherwise it returns null.
136 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
137 MutexGuard locked(lock);
139 std::map<const GlobalValue*, void*>::iterator I =
140 state.getGlobalAddressMap(locked).find(GV);
141 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
144 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
145 /// at the specified address.
147 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
148 MutexGuard locked(lock);
150 // If we haven't computed the reverse mapping yet, do so first.
151 if (state.getGlobalAddressReverseMap(locked).empty()) {
152 for (std::map<const GlobalValue*, void *>::iterator
153 I = state.getGlobalAddressMap(locked).begin(),
154 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
155 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
159 std::map<void *, const GlobalValue*>::iterator I =
160 state.getGlobalAddressReverseMap(locked).find(Addr);
161 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
164 // CreateArgv - Turn a vector of strings into a nice argv style array of
165 // pointers to null terminated strings.
167 static void *CreateArgv(ExecutionEngine *EE,
168 const std::vector<std::string> &InputArgv) {
169 unsigned PtrSize = EE->getTargetData()->getPointerSize();
170 char *Result = new char[(InputArgv.size()+1)*PtrSize];
172 DOUT << "ARGV = " << (void*)Result << "\n";
173 const Type *SBytePtr = PointerType::getUnqual(Type::Int8Ty);
175 for (unsigned i = 0; i != InputArgv.size(); ++i) {
176 unsigned Size = InputArgv[i].size()+1;
177 char *Dest = new char[Size];
178 DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
180 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
183 // Endian safe: Result[i] = (PointerTy)Dest;
184 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
189 EE->StoreValueToMemory(PTOGV(0),
190 (GenericValue*)(Result+InputArgv.size()*PtrSize),
196 /// runStaticConstructorsDestructors - This method is used to execute all of
197 /// the static constructors or destructors for a program, depending on the
198 /// value of isDtors.
199 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
200 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
202 // Execute global ctors/dtors for each module in the program.
203 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
204 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
206 // If this global has internal linkage, or if it has a use, then it must be
207 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
208 // this is the case, don't execute any of the global ctors, __main will do
210 if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
212 // Should be an array of '{ int, void ()* }' structs. The first value is
213 // the init priority, which we ignore.
214 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
215 if (!InitList) continue;
216 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
217 if (ConstantStruct *CS =
218 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
219 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
221 Constant *FP = CS->getOperand(1);
222 if (FP->isNullValue())
223 break; // Found a null terminator, exit.
225 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
227 FP = CE->getOperand(0);
228 if (Function *F = dyn_cast<Function>(FP)) {
229 // Execute the ctor/dtor function!
230 runFunction(F, std::vector<GenericValue>());
236 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
237 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
238 unsigned PtrSize = EE->getTargetData()->getPointerSize();
239 for (unsigned i = 0; i < PtrSize; ++i)
240 if (*(i + (uint8_t*)Loc))
245 /// runFunctionAsMain - This is a helper function which wraps runFunction to
246 /// handle the common task of starting up main with the specified argc, argv,
247 /// and envp parameters.
248 int ExecutionEngine::runFunctionAsMain(Function *Fn,
249 const std::vector<std::string> &argv,
250 const char * const * envp) {
251 std::vector<GenericValue> GVArgs;
253 GVArgc.IntVal = APInt(32, argv.size());
256 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
257 const FunctionType *FTy = Fn->getFunctionType();
258 const Type* PPInt8Ty =
259 PointerType::getUnqual(PointerType::getUnqual(Type::Int8Ty));
262 if (FTy->getParamType(2) != PPInt8Ty) {
263 cerr << "Invalid type for third argument of main() supplied\n";
268 if (FTy->getParamType(1) != PPInt8Ty) {
269 cerr << "Invalid type for second argument of main() supplied\n";
274 if (FTy->getParamType(0) != Type::Int32Ty) {
275 cerr << "Invalid type for first argument of main() supplied\n";
280 if (FTy->getReturnType() != Type::Int32Ty &&
281 FTy->getReturnType() != Type::VoidTy) {
282 cerr << "Invalid return type of main() supplied\n";
287 cerr << "Invalid number of arguments of main() supplied\n";
292 GVArgs.push_back(GVArgc); // Arg #0 = argc.
294 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
295 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
296 "argv[0] was null after CreateArgv");
298 std::vector<std::string> EnvVars;
299 for (unsigned i = 0; envp[i]; ++i)
300 EnvVars.push_back(envp[i]);
301 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
305 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
308 /// If possible, create a JIT, unless the caller specifically requests an
309 /// Interpreter or there's an error. If even an Interpreter cannot be created,
310 /// NULL is returned.
312 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
313 bool ForceInterpreter,
314 std::string *ErrorStr) {
315 ExecutionEngine *EE = 0;
317 // Unless the interpreter was explicitly selected, try making a JIT.
318 if (!ForceInterpreter && JITCtor)
319 EE = JITCtor(MP, ErrorStr);
321 // If we can't make a JIT, make an interpreter instead.
322 if (EE == 0 && InterpCtor)
323 EE = InterpCtor(MP, ErrorStr);
326 // Make sure we can resolve symbols in the program as well. The zero arg
327 // to the function tells DynamicLibrary to load the program, not a library.
328 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr)) {
337 ExecutionEngine *ExecutionEngine::create(Module *M) {
338 return create(new ExistingModuleProvider(M));
341 /// getPointerToGlobal - This returns the address of the specified global
342 /// value. This may involve code generation if it's a function.
344 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
345 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
346 return getPointerToFunction(F);
348 MutexGuard locked(lock);
349 void *p = state.getGlobalAddressMap(locked)[GV];
353 // Global variable might have been added since interpreter started.
354 if (GlobalVariable *GVar =
355 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
356 EmitGlobalVariable(GVar);
358 assert(0 && "Global hasn't had an address allocated yet!");
359 return state.getGlobalAddressMap(locked)[GV];
362 /// This function converts a Constant* into a GenericValue. The interesting
363 /// part is if C is a ConstantExpr.
364 /// @brief Get a GenericValue for a Constant*
365 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
366 // If its undefined, return the garbage.
367 if (isa<UndefValue>(C))
368 return GenericValue();
370 // If the value is a ConstantExpr
371 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
372 Constant *Op0 = CE->getOperand(0);
373 switch (CE->getOpcode()) {
374 case Instruction::GetElementPtr: {
376 GenericValue Result = getConstantValue(Op0);
377 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
379 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
381 char* tmp = (char*) Result.PointerVal;
382 Result = PTOGV(tmp + Offset);
385 case Instruction::Trunc: {
386 GenericValue GV = getConstantValue(Op0);
387 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
388 GV.IntVal = GV.IntVal.trunc(BitWidth);
391 case Instruction::ZExt: {
392 GenericValue GV = getConstantValue(Op0);
393 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
394 GV.IntVal = GV.IntVal.zext(BitWidth);
397 case Instruction::SExt: {
398 GenericValue GV = getConstantValue(Op0);
399 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
400 GV.IntVal = GV.IntVal.sext(BitWidth);
403 case Instruction::FPTrunc: {
405 GenericValue GV = getConstantValue(Op0);
406 GV.FloatVal = float(GV.DoubleVal);
409 case Instruction::FPExt:{
411 GenericValue GV = getConstantValue(Op0);
412 GV.DoubleVal = double(GV.FloatVal);
415 case Instruction::UIToFP: {
416 GenericValue GV = getConstantValue(Op0);
417 if (CE->getType() == Type::FloatTy)
418 GV.FloatVal = float(GV.IntVal.roundToDouble());
419 else if (CE->getType() == Type::DoubleTy)
420 GV.DoubleVal = GV.IntVal.roundToDouble();
421 else if (CE->getType() == Type::X86_FP80Ty) {
422 const uint64_t zero[] = {0, 0};
423 APFloat apf = APFloat(APInt(80, 2, zero));
424 (void)apf.convertFromZeroExtendedInteger(GV.IntVal.getRawData(),
425 GV.IntVal.getBitWidth(), false,
426 APFloat::rmNearestTiesToEven);
427 GV.IntVal = apf.convertToAPInt();
431 case Instruction::SIToFP: {
432 GenericValue GV = getConstantValue(Op0);
433 if (CE->getType() == Type::FloatTy)
434 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
435 else if (CE->getType() == Type::DoubleTy)
436 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
437 else if (CE->getType() == Type::X86_FP80Ty) {
438 const uint64_t zero[] = { 0, 0};
439 APFloat apf = APFloat(APInt(80, 2, zero));
440 (void)apf.convertFromZeroExtendedInteger(GV.IntVal.getRawData(),
441 GV.IntVal.getBitWidth(), true,
442 APFloat::rmNearestTiesToEven);
443 GV.IntVal = apf.convertToAPInt();
447 case Instruction::FPToUI: // double->APInt conversion handles sign
448 case Instruction::FPToSI: {
449 GenericValue GV = getConstantValue(Op0);
450 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
451 if (Op0->getType() == Type::FloatTy)
452 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
453 else if (Op0->getType() == Type::DoubleTy)
454 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
455 else if (Op0->getType() == Type::X86_FP80Ty) {
456 APFloat apf = APFloat(GV.IntVal);
458 (void)apf.convertToInteger(&v, BitWidth,
459 CE->getOpcode()==Instruction::FPToSI,
460 APFloat::rmTowardZero);
461 GV.IntVal = v; // endian?
465 case Instruction::PtrToInt: {
466 GenericValue GV = getConstantValue(Op0);
467 uint32_t PtrWidth = TD->getPointerSizeInBits();
468 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
471 case Instruction::IntToPtr: {
472 GenericValue GV = getConstantValue(Op0);
473 uint32_t PtrWidth = TD->getPointerSizeInBits();
474 if (PtrWidth != GV.IntVal.getBitWidth())
475 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
476 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
477 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
480 case Instruction::BitCast: {
481 GenericValue GV = getConstantValue(Op0);
482 const Type* DestTy = CE->getType();
483 switch (Op0->getType()->getTypeID()) {
484 default: assert(0 && "Invalid bitcast operand");
485 case Type::IntegerTyID:
486 assert(DestTy->isFloatingPoint() && "invalid bitcast");
487 if (DestTy == Type::FloatTy)
488 GV.FloatVal = GV.IntVal.bitsToFloat();
489 else if (DestTy == Type::DoubleTy)
490 GV.DoubleVal = GV.IntVal.bitsToDouble();
492 case Type::FloatTyID:
493 assert(DestTy == Type::Int32Ty && "Invalid bitcast");
494 GV.IntVal.floatToBits(GV.FloatVal);
496 case Type::DoubleTyID:
497 assert(DestTy == Type::Int64Ty && "Invalid bitcast");
498 GV.IntVal.doubleToBits(GV.DoubleVal);
500 case Type::PointerTyID:
501 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
502 break; // getConstantValue(Op0) above already converted it
506 case Instruction::Add:
507 case Instruction::Sub:
508 case Instruction::Mul:
509 case Instruction::UDiv:
510 case Instruction::SDiv:
511 case Instruction::URem:
512 case Instruction::SRem:
513 case Instruction::And:
514 case Instruction::Or:
515 case Instruction::Xor: {
516 GenericValue LHS = getConstantValue(Op0);
517 GenericValue RHS = getConstantValue(CE->getOperand(1));
519 switch (CE->getOperand(0)->getType()->getTypeID()) {
520 default: assert(0 && "Bad add type!"); abort();
521 case Type::IntegerTyID:
522 switch (CE->getOpcode()) {
523 default: assert(0 && "Invalid integer opcode");
524 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
525 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
526 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
527 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
528 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
529 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
530 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
531 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
532 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
533 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
536 case Type::FloatTyID:
537 switch (CE->getOpcode()) {
538 default: assert(0 && "Invalid float opcode"); abort();
539 case Instruction::Add:
540 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
541 case Instruction::Sub:
542 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
543 case Instruction::Mul:
544 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
545 case Instruction::FDiv:
546 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
547 case Instruction::FRem:
548 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
551 case Type::DoubleTyID:
552 switch (CE->getOpcode()) {
553 default: assert(0 && "Invalid double opcode"); abort();
554 case Instruction::Add:
555 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
556 case Instruction::Sub:
557 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
558 case Instruction::Mul:
559 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
560 case Instruction::FDiv:
561 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
562 case Instruction::FRem:
563 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
566 case Type::X86_FP80TyID:
567 case Type::PPC_FP128TyID:
568 case Type::FP128TyID: {
569 APFloat apfLHS = APFloat(LHS.IntVal);
570 switch (CE->getOpcode()) {
571 default: assert(0 && "Invalid long double opcode"); abort();
572 case Instruction::Add:
573 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
574 GV.IntVal = apfLHS.convertToAPInt();
576 case Instruction::Sub:
577 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
578 GV.IntVal = apfLHS.convertToAPInt();
580 case Instruction::Mul:
581 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
582 GV.IntVal = apfLHS.convertToAPInt();
584 case Instruction::FDiv:
585 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
586 GV.IntVal = apfLHS.convertToAPInt();
588 case Instruction::FRem:
589 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
590 GV.IntVal = apfLHS.convertToAPInt();
601 cerr << "ConstantExpr not handled: " << *CE << "\n";
606 switch (C->getType()->getTypeID()) {
607 case Type::FloatTyID:
608 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
610 case Type::DoubleTyID:
611 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
613 case Type::X86_FP80TyID:
614 case Type::FP128TyID:
615 case Type::PPC_FP128TyID:
616 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt();
618 case Type::IntegerTyID:
619 Result.IntVal = cast<ConstantInt>(C)->getValue();
621 case Type::PointerTyID:
622 if (isa<ConstantPointerNull>(C))
623 Result.PointerVal = 0;
624 else if (const Function *F = dyn_cast<Function>(C))
625 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
626 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
627 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
629 assert(0 && "Unknown constant pointer type!");
632 cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
638 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
639 /// with the integer held in IntVal.
640 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
641 unsigned StoreBytes) {
642 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
643 uint8_t *Src = (uint8_t *)IntVal.getRawData();
645 if (sys::littleEndianHost())
646 // Little-endian host - the source is ordered from LSB to MSB. Order the
647 // destination from LSB to MSB: Do a straight copy.
648 memcpy(Dst, Src, StoreBytes);
650 // Big-endian host - the source is an array of 64 bit words ordered from
651 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
652 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
653 while (StoreBytes > sizeof(uint64_t)) {
654 StoreBytes -= sizeof(uint64_t);
655 // May not be aligned so use memcpy.
656 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
657 Src += sizeof(uint64_t);
660 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
664 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
665 /// is the address of the memory at which to store Val, cast to GenericValue *.
666 /// It is not a pointer to a GenericValue containing the address at which to
668 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
670 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
672 switch (Ty->getTypeID()) {
673 case Type::IntegerTyID:
674 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
676 case Type::FloatTyID:
677 *((float*)Ptr) = Val.FloatVal;
679 case Type::DoubleTyID:
680 *((double*)Ptr) = Val.DoubleVal;
682 case Type::X86_FP80TyID: {
683 uint16_t *Dest = (uint16_t*)Ptr;
684 const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
685 // This is endian dependent, but it will only work on x86 anyway.
693 case Type::PointerTyID:
694 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
695 if (StoreBytes != sizeof(PointerTy))
696 memset(Ptr, 0, StoreBytes);
698 *((PointerTy*)Ptr) = Val.PointerVal;
701 cerr << "Cannot store value of type " << *Ty << "!\n";
704 if (sys::littleEndianHost() != getTargetData()->isLittleEndian())
705 // Host and target are different endian - reverse the stored bytes.
706 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
709 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
710 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
711 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
712 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
713 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
715 if (sys::littleEndianHost())
716 // Little-endian host - the destination must be ordered from LSB to MSB.
717 // The source is ordered from LSB to MSB: Do a straight copy.
718 memcpy(Dst, Src, LoadBytes);
720 // Big-endian - the destination is an array of 64 bit words ordered from
721 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
722 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
724 while (LoadBytes > sizeof(uint64_t)) {
725 LoadBytes -= sizeof(uint64_t);
726 // May not be aligned so use memcpy.
727 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
728 Dst += sizeof(uint64_t);
731 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
737 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
740 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
742 if (sys::littleEndianHost() != getTargetData()->isLittleEndian()) {
743 // Host and target are different endian - reverse copy the stored
744 // bytes into a buffer, and load from that.
745 uint8_t *Src = (uint8_t*)Ptr;
746 uint8_t *Buf = (uint8_t*)alloca(LoadBytes);
747 std::reverse_copy(Src, Src + LoadBytes, Buf);
748 Ptr = (GenericValue*)Buf;
751 switch (Ty->getTypeID()) {
752 case Type::IntegerTyID:
753 // An APInt with all words initially zero.
754 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
755 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
757 case Type::FloatTyID:
758 Result.FloatVal = *((float*)Ptr);
760 case Type::DoubleTyID:
761 Result.DoubleVal = *((double*)Ptr);
763 case Type::PointerTyID:
764 Result.PointerVal = *((PointerTy*)Ptr);
766 case Type::X86_FP80TyID: {
767 // This is endian dependent, but it will only work on x86 anyway.
768 // FIXME: Will not trap if loading a signaling NaN.
769 uint16_t *p = (uint16_t*)Ptr;
779 Result.IntVal = APInt(80, 2, y);
783 cerr << "Cannot load value of type " << *Ty << "!\n";
788 // InitializeMemory - Recursive function to apply a Constant value into the
789 // specified memory location...
791 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
792 if (isa<UndefValue>(Init)) {
794 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
795 unsigned ElementSize =
796 getTargetData()->getABITypeSize(CP->getType()->getElementType());
797 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
798 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
800 } else if (Init->getType()->isFirstClassType()) {
801 GenericValue Val = getConstantValue(Init);
802 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
804 } else if (isa<ConstantAggregateZero>(Init)) {
805 memset(Addr, 0, (size_t)getTargetData()->getABITypeSize(Init->getType()));
809 switch (Init->getType()->getTypeID()) {
810 case Type::ArrayTyID: {
811 const ConstantArray *CPA = cast<ConstantArray>(Init);
812 unsigned ElementSize =
813 getTargetData()->getABITypeSize(CPA->getType()->getElementType());
814 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
815 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
819 case Type::StructTyID: {
820 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
821 const StructLayout *SL =
822 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
823 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
824 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
829 cerr << "Bad Type: " << *Init->getType() << "\n";
830 assert(0 && "Unknown constant type to initialize memory with!");
834 /// EmitGlobals - Emit all of the global variables to memory, storing their
835 /// addresses into GlobalAddress. This must make sure to copy the contents of
836 /// their initializers into the memory.
838 void ExecutionEngine::emitGlobals() {
839 const TargetData *TD = getTargetData();
841 // Loop over all of the global variables in the program, allocating the memory
842 // to hold them. If there is more than one module, do a prepass over globals
843 // to figure out how the different modules should link together.
845 std::map<std::pair<std::string, const Type*>,
846 const GlobalValue*> LinkedGlobalsMap;
848 if (Modules.size() != 1) {
849 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
850 Module &M = *Modules[m]->getModule();
851 for (Module::const_global_iterator I = M.global_begin(),
852 E = M.global_end(); I != E; ++I) {
853 const GlobalValue *GV = I;
854 if (GV->hasInternalLinkage() || GV->isDeclaration() ||
855 GV->hasAppendingLinkage() || !GV->hasName())
856 continue;// Ignore external globals and globals with internal linkage.
858 const GlobalValue *&GVEntry =
859 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
861 // If this is the first time we've seen this global, it is the canonical
868 // If the existing global is strong, never replace it.
869 if (GVEntry->hasExternalLinkage() ||
870 GVEntry->hasDLLImportLinkage() ||
871 GVEntry->hasDLLExportLinkage())
874 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
876 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
882 std::vector<const GlobalValue*> NonCanonicalGlobals;
883 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
884 Module &M = *Modules[m]->getModule();
885 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
887 // In the multi-module case, see what this global maps to.
888 if (!LinkedGlobalsMap.empty()) {
889 if (const GlobalValue *GVEntry =
890 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
891 // If something else is the canonical global, ignore this one.
892 if (GVEntry != &*I) {
893 NonCanonicalGlobals.push_back(I);
899 if (!I->isDeclaration()) {
900 // Get the type of the global.
901 const Type *Ty = I->getType()->getElementType();
903 // Allocate some memory for it!
904 unsigned Size = TD->getABITypeSize(Ty);
905 addGlobalMapping(I, new char[Size]);
907 // External variable reference. Try to use the dynamic loader to
908 // get a pointer to it.
910 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
911 addGlobalMapping(I, SymAddr);
913 cerr << "Could not resolve external global address: "
914 << I->getName() << "\n";
920 // If there are multiple modules, map the non-canonical globals to their
921 // canonical location.
922 if (!NonCanonicalGlobals.empty()) {
923 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
924 const GlobalValue *GV = NonCanonicalGlobals[i];
925 const GlobalValue *CGV =
926 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
927 void *Ptr = getPointerToGlobalIfAvailable(CGV);
928 assert(Ptr && "Canonical global wasn't codegen'd!");
929 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
933 // Now that all of the globals are set up in memory, loop through them all
934 // and initialize their contents.
935 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
937 if (!I->isDeclaration()) {
938 if (!LinkedGlobalsMap.empty()) {
939 if (const GlobalValue *GVEntry =
940 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
941 if (GVEntry != &*I) // Not the canonical variable.
944 EmitGlobalVariable(I);
950 // EmitGlobalVariable - This method emits the specified global variable to the
951 // address specified in GlobalAddresses, or allocates new memory if it's not
952 // already in the map.
953 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
954 void *GA = getPointerToGlobalIfAvailable(GV);
955 DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
957 const Type *ElTy = GV->getType()->getElementType();
958 size_t GVSize = (size_t)getTargetData()->getABITypeSize(ElTy);
960 // If it's not already specified, allocate memory for the global.
961 GA = new char[GVSize];
962 addGlobalMapping(GV, GA);
965 InitializeMemory(GV->getInitializer(), GA);
966 NumInitBytes += (unsigned)GVSize;