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"
33 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
34 STATISTIC(NumGlobals , "Number of global vars initialized");
36 ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
37 ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
38 ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
41 ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) {
42 LazyCompilationDisabled = false;
43 SymbolSearchingDisabled = false;
45 assert(P && "ModuleProvider is null?");
48 ExecutionEngine::~ExecutionEngine() {
49 clearAllGlobalMappings();
50 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
54 /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
55 /// Release module from ModuleProvider.
56 Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P,
57 std::string *ErrInfo) {
58 for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
59 E = Modules.end(); I != E; ++I) {
60 ModuleProvider *MP = *I;
63 clearGlobalMappingsFromModule(MP->getModule());
64 return MP->releaseModule(ErrInfo);
70 /// FindFunctionNamed - Search all of the active modules to find the one that
71 /// defines FnName. This is very slow operation and shouldn't be used for
73 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
74 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
75 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
82 /// addGlobalMapping - Tell the execution engine that the specified global is
83 /// at the specified location. This is used internally as functions are JIT'd
84 /// and as global variables are laid out in memory. It can and should also be
85 /// used by clients of the EE that want to have an LLVM global overlay
86 /// existing data in memory.
87 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
88 MutexGuard locked(lock);
90 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
91 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
94 // If we are using the reverse mapping, add it too
95 if (!state.getGlobalAddressReverseMap(locked).empty()) {
96 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
97 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
102 /// clearAllGlobalMappings - Clear all global mappings and start over again
103 /// use in dynamic compilation scenarios when you want to move globals
104 void ExecutionEngine::clearAllGlobalMappings() {
105 MutexGuard locked(lock);
107 state.getGlobalAddressMap(locked).clear();
108 state.getGlobalAddressReverseMap(locked).clear();
111 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
112 /// particular module, because it has been removed from the JIT.
113 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
114 MutexGuard locked(lock);
116 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
117 state.getGlobalAddressMap(locked).erase(FI);
118 state.getGlobalAddressReverseMap(locked).erase(FI);
120 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
122 state.getGlobalAddressMap(locked).erase(GI);
123 state.getGlobalAddressReverseMap(locked).erase(GI);
127 /// updateGlobalMapping - Replace an existing mapping for GV with a new
128 /// address. This updates both maps as required. If "Addr" is null, the
129 /// entry for the global is removed from the mappings.
130 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
131 MutexGuard locked(lock);
133 std::map<const GlobalValue*, void *> &Map = state.getGlobalAddressMap(locked);
135 // Deleting from the mapping?
137 std::map<const GlobalValue*, void *>::iterator I = Map.find(GV);
146 if (!state.getGlobalAddressReverseMap(locked).empty())
147 state.getGlobalAddressReverseMap(locked).erase(Addr);
151 void *&CurVal = Map[GV];
152 void *OldVal = CurVal;
154 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
155 state.getGlobalAddressReverseMap(locked).erase(CurVal);
158 // If we are using the reverse mapping, add it too
159 if (!state.getGlobalAddressReverseMap(locked).empty()) {
160 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
161 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
167 /// getPointerToGlobalIfAvailable - This returns the address of the specified
168 /// global value if it is has already been codegen'd, otherwise it returns null.
170 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
171 MutexGuard locked(lock);
173 std::map<const GlobalValue*, void*>::iterator I =
174 state.getGlobalAddressMap(locked).find(GV);
175 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
178 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
179 /// at the specified address.
181 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
182 MutexGuard locked(lock);
184 // If we haven't computed the reverse mapping yet, do so first.
185 if (state.getGlobalAddressReverseMap(locked).empty()) {
186 for (std::map<const GlobalValue*, void *>::iterator
187 I = state.getGlobalAddressMap(locked).begin(),
188 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
189 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
193 std::map<void *, const GlobalValue*>::iterator I =
194 state.getGlobalAddressReverseMap(locked).find(Addr);
195 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
198 // CreateArgv - Turn a vector of strings into a nice argv style array of
199 // pointers to null terminated strings.
201 static void *CreateArgv(ExecutionEngine *EE,
202 const std::vector<std::string> &InputArgv) {
203 unsigned PtrSize = EE->getTargetData()->getPointerSize();
204 char *Result = new char[(InputArgv.size()+1)*PtrSize];
206 DOUT << "ARGV = " << (void*)Result << "\n";
207 const Type *SBytePtr = PointerType::getUnqual(Type::Int8Ty);
209 for (unsigned i = 0; i != InputArgv.size(); ++i) {
210 unsigned Size = InputArgv[i].size()+1;
211 char *Dest = new char[Size];
212 DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
214 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
217 // Endian safe: Result[i] = (PointerTy)Dest;
218 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
223 EE->StoreValueToMemory(PTOGV(0),
224 (GenericValue*)(Result+InputArgv.size()*PtrSize),
230 /// runStaticConstructorsDestructors - This method is used to execute all of
231 /// the static constructors or destructors for a program, depending on the
232 /// value of isDtors.
233 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
234 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
236 // Execute global ctors/dtors for each module in the program.
237 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
238 GlobalVariable *GV = Modules[m]->getModule()->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
244 if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
246 // Should be an array of '{ int, void ()* }' structs. The first value is
247 // the init priority, which we ignore.
248 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
249 if (!InitList) continue;
250 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
251 if (ConstantStruct *CS =
252 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
253 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
255 Constant *FP = CS->getOperand(1);
256 if (FP->isNullValue())
257 break; // Found a null terminator, exit.
259 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
261 FP = CE->getOperand(0);
262 if (Function *F = dyn_cast<Function>(FP)) {
263 // Execute the ctor/dtor function!
264 runFunction(F, std::vector<GenericValue>());
270 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
271 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
272 unsigned PtrSize = EE->getTargetData()->getPointerSize();
273 for (unsigned i = 0; i < PtrSize; ++i)
274 if (*(i + (uint8_t*)Loc))
279 /// runFunctionAsMain - This is a helper function which wraps runFunction to
280 /// handle the common task of starting up main with the specified argc, argv,
281 /// and envp parameters.
282 int ExecutionEngine::runFunctionAsMain(Function *Fn,
283 const std::vector<std::string> &argv,
284 const char * const * envp) {
285 std::vector<GenericValue> GVArgs;
287 GVArgc.IntVal = APInt(32, argv.size());
290 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
291 const FunctionType *FTy = Fn->getFunctionType();
292 const Type* PPInt8Ty =
293 PointerType::getUnqual(PointerType::getUnqual(Type::Int8Ty));
296 if (FTy->getParamType(2) != PPInt8Ty) {
297 cerr << "Invalid type for third argument of main() supplied\n";
302 if (FTy->getParamType(1) != PPInt8Ty) {
303 cerr << "Invalid type for second argument of main() supplied\n";
308 if (FTy->getParamType(0) != Type::Int32Ty) {
309 cerr << "Invalid type for first argument of main() supplied\n";
314 if (FTy->getReturnType() != Type::Int32Ty &&
315 FTy->getReturnType() != Type::VoidTy) {
316 cerr << "Invalid return type of main() supplied\n";
321 cerr << "Invalid number of arguments of main() supplied\n";
326 GVArgs.push_back(GVArgc); // Arg #0 = argc.
328 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
329 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
330 "argv[0] was null after CreateArgv");
332 std::vector<std::string> EnvVars;
333 for (unsigned i = 0; envp[i]; ++i)
334 EnvVars.push_back(envp[i]);
335 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
339 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
342 /// If possible, create a JIT, unless the caller specifically requests an
343 /// Interpreter or there's an error. If even an Interpreter cannot be created,
344 /// NULL is returned.
346 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
347 bool ForceInterpreter,
348 std::string *ErrorStr) {
349 ExecutionEngine *EE = 0;
351 // Make sure we can resolve symbols in the program as well. The zero arg
352 // to the function tells DynamicLibrary to load the program, not a library.
353 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
356 // Unless the interpreter was explicitly selected, try making a JIT.
357 if (!ForceInterpreter && JITCtor)
358 EE = JITCtor(MP, ErrorStr);
360 // If we can't make a JIT, make an interpreter instead.
361 if (EE == 0 && InterpCtor)
362 EE = InterpCtor(MP, ErrorStr);
367 ExecutionEngine *ExecutionEngine::create(Module *M) {
368 return create(new ExistingModuleProvider(M));
371 /// getPointerToGlobal - This returns the address of the specified global
372 /// value. This may involve code generation if it's a function.
374 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
375 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
376 return getPointerToFunction(F);
378 MutexGuard locked(lock);
379 void *p = state.getGlobalAddressMap(locked)[GV];
383 // Global variable might have been added since interpreter started.
384 if (GlobalVariable *GVar =
385 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
386 EmitGlobalVariable(GVar);
388 assert(0 && "Global hasn't had an address allocated yet!");
389 return state.getGlobalAddressMap(locked)[GV];
392 /// This function converts a Constant* into a GenericValue. The interesting
393 /// part is if C is a ConstantExpr.
394 /// @brief Get a GenericValue for a Constant*
395 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
396 // If its undefined, return the garbage.
397 if (isa<UndefValue>(C))
398 return GenericValue();
400 // If the value is a ConstantExpr
401 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
402 Constant *Op0 = CE->getOperand(0);
403 switch (CE->getOpcode()) {
404 case Instruction::GetElementPtr: {
406 GenericValue Result = getConstantValue(Op0);
407 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
409 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
411 char* tmp = (char*) Result.PointerVal;
412 Result = PTOGV(tmp + Offset);
415 case Instruction::Trunc: {
416 GenericValue GV = getConstantValue(Op0);
417 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
418 GV.IntVal = GV.IntVal.trunc(BitWidth);
421 case Instruction::ZExt: {
422 GenericValue GV = getConstantValue(Op0);
423 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
424 GV.IntVal = GV.IntVal.zext(BitWidth);
427 case Instruction::SExt: {
428 GenericValue GV = getConstantValue(Op0);
429 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
430 GV.IntVal = GV.IntVal.sext(BitWidth);
433 case Instruction::FPTrunc: {
435 GenericValue GV = getConstantValue(Op0);
436 GV.FloatVal = float(GV.DoubleVal);
439 case Instruction::FPExt:{
441 GenericValue GV = getConstantValue(Op0);
442 GV.DoubleVal = double(GV.FloatVal);
445 case Instruction::UIToFP: {
446 GenericValue GV = getConstantValue(Op0);
447 if (CE->getType() == Type::FloatTy)
448 GV.FloatVal = float(GV.IntVal.roundToDouble());
449 else if (CE->getType() == Type::DoubleTy)
450 GV.DoubleVal = GV.IntVal.roundToDouble();
451 else if (CE->getType() == Type::X86_FP80Ty) {
452 const uint64_t zero[] = {0, 0};
453 APFloat apf = APFloat(APInt(80, 2, zero));
454 (void)apf.convertFromAPInt(GV.IntVal,
456 APFloat::rmNearestTiesToEven);
457 GV.IntVal = apf.convertToAPInt();
461 case Instruction::SIToFP: {
462 GenericValue GV = getConstantValue(Op0);
463 if (CE->getType() == Type::FloatTy)
464 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
465 else if (CE->getType() == Type::DoubleTy)
466 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
467 else if (CE->getType() == Type::X86_FP80Ty) {
468 const uint64_t zero[] = { 0, 0};
469 APFloat apf = APFloat(APInt(80, 2, zero));
470 (void)apf.convertFromAPInt(GV.IntVal,
472 APFloat::rmNearestTiesToEven);
473 GV.IntVal = apf.convertToAPInt();
477 case Instruction::FPToUI: // double->APInt conversion handles sign
478 case Instruction::FPToSI: {
479 GenericValue GV = getConstantValue(Op0);
480 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
481 if (Op0->getType() == Type::FloatTy)
482 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
483 else if (Op0->getType() == Type::DoubleTy)
484 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
485 else if (Op0->getType() == Type::X86_FP80Ty) {
486 APFloat apf = APFloat(GV.IntVal);
488 (void)apf.convertToInteger(&v, BitWidth,
489 CE->getOpcode()==Instruction::FPToSI,
490 APFloat::rmTowardZero);
491 GV.IntVal = v; // endian?
495 case Instruction::PtrToInt: {
496 GenericValue GV = getConstantValue(Op0);
497 uint32_t PtrWidth = TD->getPointerSizeInBits();
498 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
501 case Instruction::IntToPtr: {
502 GenericValue GV = getConstantValue(Op0);
503 uint32_t PtrWidth = TD->getPointerSizeInBits();
504 if (PtrWidth != GV.IntVal.getBitWidth())
505 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
506 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
507 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
510 case Instruction::BitCast: {
511 GenericValue GV = getConstantValue(Op0);
512 const Type* DestTy = CE->getType();
513 switch (Op0->getType()->getTypeID()) {
514 default: assert(0 && "Invalid bitcast operand");
515 case Type::IntegerTyID:
516 assert(DestTy->isFloatingPoint() && "invalid bitcast");
517 if (DestTy == Type::FloatTy)
518 GV.FloatVal = GV.IntVal.bitsToFloat();
519 else if (DestTy == Type::DoubleTy)
520 GV.DoubleVal = GV.IntVal.bitsToDouble();
522 case Type::FloatTyID:
523 assert(DestTy == Type::Int32Ty && "Invalid bitcast");
524 GV.IntVal.floatToBits(GV.FloatVal);
526 case Type::DoubleTyID:
527 assert(DestTy == Type::Int64Ty && "Invalid bitcast");
528 GV.IntVal.doubleToBits(GV.DoubleVal);
530 case Type::PointerTyID:
531 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
532 break; // getConstantValue(Op0) above already converted it
536 case Instruction::Add:
537 case Instruction::Sub:
538 case Instruction::Mul:
539 case Instruction::UDiv:
540 case Instruction::SDiv:
541 case Instruction::URem:
542 case Instruction::SRem:
543 case Instruction::And:
544 case Instruction::Or:
545 case Instruction::Xor: {
546 GenericValue LHS = getConstantValue(Op0);
547 GenericValue RHS = getConstantValue(CE->getOperand(1));
549 switch (CE->getOperand(0)->getType()->getTypeID()) {
550 default: assert(0 && "Bad add type!"); abort();
551 case Type::IntegerTyID:
552 switch (CE->getOpcode()) {
553 default: assert(0 && "Invalid integer opcode");
554 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
555 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
556 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
557 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
558 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
559 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
560 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
561 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
562 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
563 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
566 case Type::FloatTyID:
567 switch (CE->getOpcode()) {
568 default: assert(0 && "Invalid float opcode"); abort();
569 case Instruction::Add:
570 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
571 case Instruction::Sub:
572 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
573 case Instruction::Mul:
574 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
575 case Instruction::FDiv:
576 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
577 case Instruction::FRem:
578 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
581 case Type::DoubleTyID:
582 switch (CE->getOpcode()) {
583 default: assert(0 && "Invalid double opcode"); abort();
584 case Instruction::Add:
585 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
586 case Instruction::Sub:
587 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
588 case Instruction::Mul:
589 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
590 case Instruction::FDiv:
591 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
592 case Instruction::FRem:
593 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
596 case Type::X86_FP80TyID:
597 case Type::PPC_FP128TyID:
598 case Type::FP128TyID: {
599 APFloat apfLHS = APFloat(LHS.IntVal);
600 switch (CE->getOpcode()) {
601 default: assert(0 && "Invalid long double opcode"); abort();
602 case Instruction::Add:
603 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
604 GV.IntVal = apfLHS.convertToAPInt();
606 case Instruction::Sub:
607 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
608 GV.IntVal = apfLHS.convertToAPInt();
610 case Instruction::Mul:
611 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
612 GV.IntVal = apfLHS.convertToAPInt();
614 case Instruction::FDiv:
615 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
616 GV.IntVal = apfLHS.convertToAPInt();
618 case Instruction::FRem:
619 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
620 GV.IntVal = apfLHS.convertToAPInt();
631 cerr << "ConstantExpr not handled: " << *CE << "\n";
636 switch (C->getType()->getTypeID()) {
637 case Type::FloatTyID:
638 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
640 case Type::DoubleTyID:
641 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
643 case Type::X86_FP80TyID:
644 case Type::FP128TyID:
645 case Type::PPC_FP128TyID:
646 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt();
648 case Type::IntegerTyID:
649 Result.IntVal = cast<ConstantInt>(C)->getValue();
651 case Type::PointerTyID:
652 if (isa<ConstantPointerNull>(C))
653 Result.PointerVal = 0;
654 else if (const Function *F = dyn_cast<Function>(C))
655 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
656 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
657 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
659 assert(0 && "Unknown constant pointer type!");
662 cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
668 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
669 /// with the integer held in IntVal.
670 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
671 unsigned StoreBytes) {
672 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
673 uint8_t *Src = (uint8_t *)IntVal.getRawData();
675 if (sys::littleEndianHost())
676 // Little-endian host - the source is ordered from LSB to MSB. Order the
677 // destination from LSB to MSB: Do a straight copy.
678 memcpy(Dst, Src, StoreBytes);
680 // Big-endian host - the source is an array of 64 bit words ordered from
681 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
682 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
683 while (StoreBytes > sizeof(uint64_t)) {
684 StoreBytes -= sizeof(uint64_t);
685 // May not be aligned so use memcpy.
686 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
687 Src += sizeof(uint64_t);
690 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
694 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
695 /// is the address of the memory at which to store Val, cast to GenericValue *.
696 /// It is not a pointer to a GenericValue containing the address at which to
698 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
700 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
702 switch (Ty->getTypeID()) {
703 case Type::IntegerTyID:
704 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
706 case Type::FloatTyID:
707 *((float*)Ptr) = Val.FloatVal;
709 case Type::DoubleTyID:
710 *((double*)Ptr) = Val.DoubleVal;
712 case Type::X86_FP80TyID: {
713 uint16_t *Dest = (uint16_t*)Ptr;
714 const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
715 // This is endian dependent, but it will only work on x86 anyway.
723 case Type::PointerTyID:
724 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
725 if (StoreBytes != sizeof(PointerTy))
726 memset(Ptr, 0, StoreBytes);
728 *((PointerTy*)Ptr) = Val.PointerVal;
731 cerr << "Cannot store value of type " << *Ty << "!\n";
734 if (sys::littleEndianHost() != getTargetData()->isLittleEndian())
735 // Host and target are different endian - reverse the stored bytes.
736 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
739 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
740 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
741 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
742 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
743 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
745 if (sys::littleEndianHost())
746 // Little-endian host - the destination must be ordered from LSB to MSB.
747 // The source is ordered from LSB to MSB: Do a straight copy.
748 memcpy(Dst, Src, LoadBytes);
750 // Big-endian - the destination is an array of 64 bit words ordered from
751 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
752 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
754 while (LoadBytes > sizeof(uint64_t)) {
755 LoadBytes -= sizeof(uint64_t);
756 // May not be aligned so use memcpy.
757 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
758 Dst += sizeof(uint64_t);
761 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
767 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
770 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
772 if (sys::littleEndianHost() != getTargetData()->isLittleEndian()) {
773 // Host and target are different endian - reverse copy the stored
774 // bytes into a buffer, and load from that.
775 uint8_t *Src = (uint8_t*)Ptr;
776 uint8_t *Buf = (uint8_t*)alloca(LoadBytes);
777 std::reverse_copy(Src, Src + LoadBytes, Buf);
778 Ptr = (GenericValue*)Buf;
781 switch (Ty->getTypeID()) {
782 case Type::IntegerTyID:
783 // An APInt with all words initially zero.
784 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
785 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
787 case Type::FloatTyID:
788 Result.FloatVal = *((float*)Ptr);
790 case Type::DoubleTyID:
791 Result.DoubleVal = *((double*)Ptr);
793 case Type::PointerTyID:
794 Result.PointerVal = *((PointerTy*)Ptr);
796 case Type::X86_FP80TyID: {
797 // This is endian dependent, but it will only work on x86 anyway.
798 // FIXME: Will not trap if loading a signaling NaN.
799 uint16_t *p = (uint16_t*)Ptr;
809 Result.IntVal = APInt(80, 2, y);
813 cerr << "Cannot load value of type " << *Ty << "!\n";
818 // InitializeMemory - Recursive function to apply a Constant value into the
819 // specified memory location...
821 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
822 if (isa<UndefValue>(Init)) {
824 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
825 unsigned ElementSize =
826 getTargetData()->getABITypeSize(CP->getType()->getElementType());
827 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
828 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
830 } else if (isa<ConstantAggregateZero>(Init)) {
831 memset(Addr, 0, (size_t)getTargetData()->getABITypeSize(Init->getType()));
833 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
834 unsigned ElementSize =
835 getTargetData()->getABITypeSize(CPA->getType()->getElementType());
836 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
837 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
839 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
840 const StructLayout *SL =
841 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
842 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
843 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
845 } else if (Init->getType()->isFirstClassType()) {
846 GenericValue Val = getConstantValue(Init);
847 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
851 cerr << "Bad Type: " << *Init->getType() << "\n";
852 assert(0 && "Unknown constant type to initialize memory with!");
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.
859 void ExecutionEngine::emitGlobals() {
860 const TargetData *TD = getTargetData();
862 // Loop over all of the global variables in the program, allocating the memory
863 // to hold them. If there is more than one module, do a prepass over globals
864 // to figure out how the different modules should link together.
866 std::map<std::pair<std::string, const Type*>,
867 const GlobalValue*> LinkedGlobalsMap;
869 if (Modules.size() != 1) {
870 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
871 Module &M = *Modules[m]->getModule();
872 for (Module::const_global_iterator I = M.global_begin(),
873 E = M.global_end(); I != E; ++I) {
874 const GlobalValue *GV = I;
875 if (GV->hasInternalLinkage() || GV->isDeclaration() ||
876 GV->hasAppendingLinkage() || !GV->hasName())
877 continue;// Ignore external globals and globals with internal linkage.
879 const GlobalValue *&GVEntry =
880 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
882 // If this is the first time we've seen this global, it is the canonical
889 // If the existing global is strong, never replace it.
890 if (GVEntry->hasExternalLinkage() ||
891 GVEntry->hasDLLImportLinkage() ||
892 GVEntry->hasDLLExportLinkage())
895 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
896 // symbol. FIXME is this right for common?
897 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
903 std::vector<const GlobalValue*> NonCanonicalGlobals;
904 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
905 Module &M = *Modules[m]->getModule();
906 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
908 // In the multi-module case, see what this global maps to.
909 if (!LinkedGlobalsMap.empty()) {
910 if (const GlobalValue *GVEntry =
911 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
912 // If something else is the canonical global, ignore this one.
913 if (GVEntry != &*I) {
914 NonCanonicalGlobals.push_back(I);
920 if (!I->isDeclaration()) {
921 // Get the type of the global.
922 const Type *Ty = I->getType()->getElementType();
924 // Allocate some memory for it!
925 unsigned Size = TD->getABITypeSize(Ty);
926 addGlobalMapping(I, new char[Size]);
928 // External variable reference. Try to use the dynamic loader to
929 // get a pointer to it.
931 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
932 addGlobalMapping(I, SymAddr);
934 cerr << "Could not resolve external global address: "
935 << I->getName() << "\n";
941 // If there are multiple modules, map the non-canonical globals to their
942 // canonical location.
943 if (!NonCanonicalGlobals.empty()) {
944 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
945 const GlobalValue *GV = NonCanonicalGlobals[i];
946 const GlobalValue *CGV =
947 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
948 void *Ptr = getPointerToGlobalIfAvailable(CGV);
949 assert(Ptr && "Canonical global wasn't codegen'd!");
950 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
954 // Now that all of the globals are set up in memory, loop through them all
955 // and initialize their contents.
956 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
958 if (!I->isDeclaration()) {
959 if (!LinkedGlobalsMap.empty()) {
960 if (const GlobalValue *GVEntry =
961 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
962 if (GVEntry != &*I) // Not the canonical variable.
965 EmitGlobalVariable(I);
971 // EmitGlobalVariable - This method emits the specified global variable to the
972 // address specified in GlobalAddresses, or allocates new memory if it's not
973 // already in the map.
974 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
975 void *GA = getPointerToGlobalIfAvailable(GV);
976 DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
978 const Type *ElTy = GV->getType()->getElementType();
979 size_t GVSize = (size_t)getTargetData()->getABITypeSize(ElTy);
981 // If it's not already specified, allocate memory for the global.
982 GA = new char[GVSize];
983 addGlobalMapping(GV, GA);
986 InitializeMemory(GV->getInitializer(), GA);
987 NumInitBytes += (unsigned)GVSize;