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;
44 assert(P && "ModuleProvider is null?");
47 ExecutionEngine::~ExecutionEngine() {
48 clearAllGlobalMappings();
49 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
53 /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
54 /// Release module from ModuleProvider.
55 Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P,
56 std::string *ErrInfo) {
57 for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
58 E = Modules.end(); I != E; ++I) {
59 ModuleProvider *MP = *I;
62 clearGlobalMappingsFromModule(MP->getModule());
63 return MP->releaseModule(ErrInfo);
69 /// FindFunctionNamed - Search all of the active modules to find the one that
70 /// defines FnName. This is very slow operation and shouldn't be used for
72 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
73 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
74 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
81 /// addGlobalMapping - Tell the execution engine that the specified global is
82 /// at the specified location. This is used internally as functions are JIT'd
83 /// and as global variables are laid out in memory. It can and should also be
84 /// used by clients of the EE that want to have an LLVM global overlay
85 /// existing data in memory.
86 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
87 MutexGuard locked(lock);
89 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
90 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
93 // If we are using the reverse mapping, add it too
94 if (!state.getGlobalAddressReverseMap(locked).empty()) {
95 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
96 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
101 /// clearAllGlobalMappings - Clear all global mappings and start over again
102 /// use in dynamic compilation scenarios when you want to move globals
103 void ExecutionEngine::clearAllGlobalMappings() {
104 MutexGuard locked(lock);
106 state.getGlobalAddressMap(locked).clear();
107 state.getGlobalAddressReverseMap(locked).clear();
110 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
111 /// particular module, because it has been removed from the JIT.
112 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
113 MutexGuard locked(lock);
115 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
116 state.getGlobalAddressMap(locked).erase(FI);
117 state.getGlobalAddressReverseMap(locked).erase(FI);
119 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
121 state.getGlobalAddressMap(locked).erase(GI);
122 state.getGlobalAddressReverseMap(locked).erase(GI);
126 /// updateGlobalMapping - Replace an existing mapping for GV with a new
127 /// address. This updates both maps as required. If "Addr" is null, the
128 /// entry for the global is removed from the mappings.
129 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
130 MutexGuard locked(lock);
132 std::map<const GlobalValue*, void *> &Map = state.getGlobalAddressMap(locked);
134 // Deleting from the mapping?
136 std::map<const GlobalValue*, void *>::iterator I = Map.find(GV);
145 if (!state.getGlobalAddressReverseMap(locked).empty())
146 state.getGlobalAddressReverseMap(locked).erase(Addr);
150 void *&CurVal = Map[GV];
151 void *OldVal = CurVal;
153 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
154 state.getGlobalAddressReverseMap(locked).erase(CurVal);
157 // If we are using the reverse mapping, add it too
158 if (!state.getGlobalAddressReverseMap(locked).empty()) {
159 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
160 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
166 /// getPointerToGlobalIfAvailable - This returns the address of the specified
167 /// global value if it is has already been codegen'd, otherwise it returns null.
169 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
170 MutexGuard locked(lock);
172 std::map<const GlobalValue*, void*>::iterator I =
173 state.getGlobalAddressMap(locked).find(GV);
174 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
177 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
178 /// at the specified address.
180 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
181 MutexGuard locked(lock);
183 // If we haven't computed the reverse mapping yet, do so first.
184 if (state.getGlobalAddressReverseMap(locked).empty()) {
185 for (std::map<const GlobalValue*, void *>::iterator
186 I = state.getGlobalAddressMap(locked).begin(),
187 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
188 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
192 std::map<void *, const GlobalValue*>::iterator I =
193 state.getGlobalAddressReverseMap(locked).find(Addr);
194 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
197 // CreateArgv - Turn a vector of strings into a nice argv style array of
198 // pointers to null terminated strings.
200 static void *CreateArgv(ExecutionEngine *EE,
201 const std::vector<std::string> &InputArgv) {
202 unsigned PtrSize = EE->getTargetData()->getPointerSize();
203 char *Result = new char[(InputArgv.size()+1)*PtrSize];
205 DOUT << "ARGV = " << (void*)Result << "\n";
206 const Type *SBytePtr = PointerType::getUnqual(Type::Int8Ty);
208 for (unsigned i = 0; i != InputArgv.size(); ++i) {
209 unsigned Size = InputArgv[i].size()+1;
210 char *Dest = new char[Size];
211 DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
213 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
216 // Endian safe: Result[i] = (PointerTy)Dest;
217 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
222 EE->StoreValueToMemory(PTOGV(0),
223 (GenericValue*)(Result+InputArgv.size()*PtrSize),
229 /// runStaticConstructorsDestructors - This method is used to execute all of
230 /// the static constructors or destructors for a program, depending on the
231 /// value of isDtors.
232 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
233 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
235 // Execute global ctors/dtors for each module in the program.
236 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
237 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
239 // If this global has internal linkage, or if it has a use, then it must be
240 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
241 // this is the case, don't execute any of the global ctors, __main will do
243 if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
245 // Should be an array of '{ int, void ()* }' structs. The first value is
246 // the init priority, which we ignore.
247 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
248 if (!InitList) continue;
249 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
250 if (ConstantStruct *CS =
251 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
252 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
254 Constant *FP = CS->getOperand(1);
255 if (FP->isNullValue())
256 break; // Found a null terminator, exit.
258 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
260 FP = CE->getOperand(0);
261 if (Function *F = dyn_cast<Function>(FP)) {
262 // Execute the ctor/dtor function!
263 runFunction(F, std::vector<GenericValue>());
269 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
270 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
271 unsigned PtrSize = EE->getTargetData()->getPointerSize();
272 for (unsigned i = 0; i < PtrSize; ++i)
273 if (*(i + (uint8_t*)Loc))
278 /// runFunctionAsMain - This is a helper function which wraps runFunction to
279 /// handle the common task of starting up main with the specified argc, argv,
280 /// and envp parameters.
281 int ExecutionEngine::runFunctionAsMain(Function *Fn,
282 const std::vector<std::string> &argv,
283 const char * const * envp) {
284 std::vector<GenericValue> GVArgs;
286 GVArgc.IntVal = APInt(32, argv.size());
289 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
290 const FunctionType *FTy = Fn->getFunctionType();
291 const Type* PPInt8Ty =
292 PointerType::getUnqual(PointerType::getUnqual(Type::Int8Ty));
295 if (FTy->getParamType(2) != PPInt8Ty) {
296 cerr << "Invalid type for third argument of main() supplied\n";
301 if (FTy->getParamType(1) != PPInt8Ty) {
302 cerr << "Invalid type for second argument of main() supplied\n";
307 if (FTy->getParamType(0) != Type::Int32Ty) {
308 cerr << "Invalid type for first argument of main() supplied\n";
313 if (FTy->getReturnType() != Type::Int32Ty &&
314 FTy->getReturnType() != Type::VoidTy) {
315 cerr << "Invalid return type of main() supplied\n";
320 cerr << "Invalid number of arguments of main() supplied\n";
325 GVArgs.push_back(GVArgc); // Arg #0 = argc.
327 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
328 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
329 "argv[0] was null after CreateArgv");
331 std::vector<std::string> EnvVars;
332 for (unsigned i = 0; envp[i]; ++i)
333 EnvVars.push_back(envp[i]);
334 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
338 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
341 /// If possible, create a JIT, unless the caller specifically requests an
342 /// Interpreter or there's an error. If even an Interpreter cannot be created,
343 /// NULL is returned.
345 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
346 bool ForceInterpreter,
347 std::string *ErrorStr) {
348 ExecutionEngine *EE = 0;
350 // Make sure we can resolve symbols in the program as well. The zero arg
351 // to the function tells DynamicLibrary to load the program, not a library.
352 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
355 // Unless the interpreter was explicitly selected, try making a JIT.
356 if (!ForceInterpreter && JITCtor)
357 EE = JITCtor(MP, ErrorStr);
359 // If we can't make a JIT, make an interpreter instead.
360 if (EE == 0 && InterpCtor)
361 EE = InterpCtor(MP, ErrorStr);
366 ExecutionEngine *ExecutionEngine::create(Module *M) {
367 return create(new ExistingModuleProvider(M));
370 /// getPointerToGlobal - This returns the address of the specified global
371 /// value. This may involve code generation if it's a function.
373 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
374 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
375 return getPointerToFunction(F);
377 MutexGuard locked(lock);
378 void *p = state.getGlobalAddressMap(locked)[GV];
382 // Global variable might have been added since interpreter started.
383 if (GlobalVariable *GVar =
384 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
385 EmitGlobalVariable(GVar);
387 assert(0 && "Global hasn't had an address allocated yet!");
388 return state.getGlobalAddressMap(locked)[GV];
391 /// This function converts a Constant* into a GenericValue. The interesting
392 /// part is if C is a ConstantExpr.
393 /// @brief Get a GenericValue for a Constant*
394 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
395 // If its undefined, return the garbage.
396 if (isa<UndefValue>(C))
397 return GenericValue();
399 // If the value is a ConstantExpr
400 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
401 Constant *Op0 = CE->getOperand(0);
402 switch (CE->getOpcode()) {
403 case Instruction::GetElementPtr: {
405 GenericValue Result = getConstantValue(Op0);
406 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
408 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
410 char* tmp = (char*) Result.PointerVal;
411 Result = PTOGV(tmp + Offset);
414 case Instruction::Trunc: {
415 GenericValue GV = getConstantValue(Op0);
416 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
417 GV.IntVal = GV.IntVal.trunc(BitWidth);
420 case Instruction::ZExt: {
421 GenericValue GV = getConstantValue(Op0);
422 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
423 GV.IntVal = GV.IntVal.zext(BitWidth);
426 case Instruction::SExt: {
427 GenericValue GV = getConstantValue(Op0);
428 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
429 GV.IntVal = GV.IntVal.sext(BitWidth);
432 case Instruction::FPTrunc: {
434 GenericValue GV = getConstantValue(Op0);
435 GV.FloatVal = float(GV.DoubleVal);
438 case Instruction::FPExt:{
440 GenericValue GV = getConstantValue(Op0);
441 GV.DoubleVal = double(GV.FloatVal);
444 case Instruction::UIToFP: {
445 GenericValue GV = getConstantValue(Op0);
446 if (CE->getType() == Type::FloatTy)
447 GV.FloatVal = float(GV.IntVal.roundToDouble());
448 else if (CE->getType() == Type::DoubleTy)
449 GV.DoubleVal = GV.IntVal.roundToDouble();
450 else if (CE->getType() == Type::X86_FP80Ty) {
451 const uint64_t zero[] = {0, 0};
452 APFloat apf = APFloat(APInt(80, 2, zero));
453 (void)apf.convertFromAPInt(GV.IntVal,
455 APFloat::rmNearestTiesToEven);
456 GV.IntVal = apf.convertToAPInt();
460 case Instruction::SIToFP: {
461 GenericValue GV = getConstantValue(Op0);
462 if (CE->getType() == Type::FloatTy)
463 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
464 else if (CE->getType() == Type::DoubleTy)
465 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
466 else if (CE->getType() == Type::X86_FP80Ty) {
467 const uint64_t zero[] = { 0, 0};
468 APFloat apf = APFloat(APInt(80, 2, zero));
469 (void)apf.convertFromAPInt(GV.IntVal,
471 APFloat::rmNearestTiesToEven);
472 GV.IntVal = apf.convertToAPInt();
476 case Instruction::FPToUI: // double->APInt conversion handles sign
477 case Instruction::FPToSI: {
478 GenericValue GV = getConstantValue(Op0);
479 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
480 if (Op0->getType() == Type::FloatTy)
481 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
482 else if (Op0->getType() == Type::DoubleTy)
483 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
484 else if (Op0->getType() == Type::X86_FP80Ty) {
485 APFloat apf = APFloat(GV.IntVal);
487 (void)apf.convertToInteger(&v, BitWidth,
488 CE->getOpcode()==Instruction::FPToSI,
489 APFloat::rmTowardZero);
490 GV.IntVal = v; // endian?
494 case Instruction::PtrToInt: {
495 GenericValue GV = getConstantValue(Op0);
496 uint32_t PtrWidth = TD->getPointerSizeInBits();
497 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
500 case Instruction::IntToPtr: {
501 GenericValue GV = getConstantValue(Op0);
502 uint32_t PtrWidth = TD->getPointerSizeInBits();
503 if (PtrWidth != GV.IntVal.getBitWidth())
504 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
505 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
506 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
509 case Instruction::BitCast: {
510 GenericValue GV = getConstantValue(Op0);
511 const Type* DestTy = CE->getType();
512 switch (Op0->getType()->getTypeID()) {
513 default: assert(0 && "Invalid bitcast operand");
514 case Type::IntegerTyID:
515 assert(DestTy->isFloatingPoint() && "invalid bitcast");
516 if (DestTy == Type::FloatTy)
517 GV.FloatVal = GV.IntVal.bitsToFloat();
518 else if (DestTy == Type::DoubleTy)
519 GV.DoubleVal = GV.IntVal.bitsToDouble();
521 case Type::FloatTyID:
522 assert(DestTy == Type::Int32Ty && "Invalid bitcast");
523 GV.IntVal.floatToBits(GV.FloatVal);
525 case Type::DoubleTyID:
526 assert(DestTy == Type::Int64Ty && "Invalid bitcast");
527 GV.IntVal.doubleToBits(GV.DoubleVal);
529 case Type::PointerTyID:
530 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
531 break; // getConstantValue(Op0) above already converted it
535 case Instruction::Add:
536 case Instruction::Sub:
537 case Instruction::Mul:
538 case Instruction::UDiv:
539 case Instruction::SDiv:
540 case Instruction::URem:
541 case Instruction::SRem:
542 case Instruction::And:
543 case Instruction::Or:
544 case Instruction::Xor: {
545 GenericValue LHS = getConstantValue(Op0);
546 GenericValue RHS = getConstantValue(CE->getOperand(1));
548 switch (CE->getOperand(0)->getType()->getTypeID()) {
549 default: assert(0 && "Bad add type!"); abort();
550 case Type::IntegerTyID:
551 switch (CE->getOpcode()) {
552 default: assert(0 && "Invalid integer opcode");
553 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
554 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
555 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
556 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
557 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
558 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
559 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
560 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
561 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
562 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
565 case Type::FloatTyID:
566 switch (CE->getOpcode()) {
567 default: assert(0 && "Invalid float opcode"); abort();
568 case Instruction::Add:
569 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
570 case Instruction::Sub:
571 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
572 case Instruction::Mul:
573 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
574 case Instruction::FDiv:
575 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
576 case Instruction::FRem:
577 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
580 case Type::DoubleTyID:
581 switch (CE->getOpcode()) {
582 default: assert(0 && "Invalid double opcode"); abort();
583 case Instruction::Add:
584 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
585 case Instruction::Sub:
586 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
587 case Instruction::Mul:
588 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
589 case Instruction::FDiv:
590 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
591 case Instruction::FRem:
592 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
595 case Type::X86_FP80TyID:
596 case Type::PPC_FP128TyID:
597 case Type::FP128TyID: {
598 APFloat apfLHS = APFloat(LHS.IntVal);
599 switch (CE->getOpcode()) {
600 default: assert(0 && "Invalid long double opcode"); abort();
601 case Instruction::Add:
602 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
603 GV.IntVal = apfLHS.convertToAPInt();
605 case Instruction::Sub:
606 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
607 GV.IntVal = apfLHS.convertToAPInt();
609 case Instruction::Mul:
610 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
611 GV.IntVal = apfLHS.convertToAPInt();
613 case Instruction::FDiv:
614 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
615 GV.IntVal = apfLHS.convertToAPInt();
617 case Instruction::FRem:
618 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
619 GV.IntVal = apfLHS.convertToAPInt();
630 cerr << "ConstantExpr not handled: " << *CE << "\n";
635 switch (C->getType()->getTypeID()) {
636 case Type::FloatTyID:
637 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
639 case Type::DoubleTyID:
640 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
642 case Type::X86_FP80TyID:
643 case Type::FP128TyID:
644 case Type::PPC_FP128TyID:
645 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt();
647 case Type::IntegerTyID:
648 Result.IntVal = cast<ConstantInt>(C)->getValue();
650 case Type::PointerTyID:
651 if (isa<ConstantPointerNull>(C))
652 Result.PointerVal = 0;
653 else if (const Function *F = dyn_cast<Function>(C))
654 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
655 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
656 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
658 assert(0 && "Unknown constant pointer type!");
661 cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
667 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
668 /// with the integer held in IntVal.
669 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
670 unsigned StoreBytes) {
671 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
672 uint8_t *Src = (uint8_t *)IntVal.getRawData();
674 if (sys::littleEndianHost())
675 // Little-endian host - the source is ordered from LSB to MSB. Order the
676 // destination from LSB to MSB: Do a straight copy.
677 memcpy(Dst, Src, StoreBytes);
679 // Big-endian host - the source is an array of 64 bit words ordered from
680 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
681 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
682 while (StoreBytes > sizeof(uint64_t)) {
683 StoreBytes -= sizeof(uint64_t);
684 // May not be aligned so use memcpy.
685 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
686 Src += sizeof(uint64_t);
689 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
693 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
694 /// is the address of the memory at which to store Val, cast to GenericValue *.
695 /// It is not a pointer to a GenericValue containing the address at which to
697 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
699 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
701 switch (Ty->getTypeID()) {
702 case Type::IntegerTyID:
703 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
705 case Type::FloatTyID:
706 *((float*)Ptr) = Val.FloatVal;
708 case Type::DoubleTyID:
709 *((double*)Ptr) = Val.DoubleVal;
711 case Type::X86_FP80TyID: {
712 uint16_t *Dest = (uint16_t*)Ptr;
713 const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
714 // This is endian dependent, but it will only work on x86 anyway.
722 case Type::PointerTyID:
723 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
724 if (StoreBytes != sizeof(PointerTy))
725 memset(Ptr, 0, StoreBytes);
727 *((PointerTy*)Ptr) = Val.PointerVal;
730 cerr << "Cannot store value of type " << *Ty << "!\n";
733 if (sys::littleEndianHost() != getTargetData()->isLittleEndian())
734 // Host and target are different endian - reverse the stored bytes.
735 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
738 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
739 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
740 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
741 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
742 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
744 if (sys::littleEndianHost())
745 // Little-endian host - the destination must be ordered from LSB to MSB.
746 // The source is ordered from LSB to MSB: Do a straight copy.
747 memcpy(Dst, Src, LoadBytes);
749 // Big-endian - the destination is an array of 64 bit words ordered from
750 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
751 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
753 while (LoadBytes > sizeof(uint64_t)) {
754 LoadBytes -= sizeof(uint64_t);
755 // May not be aligned so use memcpy.
756 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
757 Dst += sizeof(uint64_t);
760 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
766 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
769 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
771 if (sys::littleEndianHost() != getTargetData()->isLittleEndian()) {
772 // Host and target are different endian - reverse copy the stored
773 // bytes into a buffer, and load from that.
774 uint8_t *Src = (uint8_t*)Ptr;
775 uint8_t *Buf = (uint8_t*)alloca(LoadBytes);
776 std::reverse_copy(Src, Src + LoadBytes, Buf);
777 Ptr = (GenericValue*)Buf;
780 switch (Ty->getTypeID()) {
781 case Type::IntegerTyID:
782 // An APInt with all words initially zero.
783 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
784 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
786 case Type::FloatTyID:
787 Result.FloatVal = *((float*)Ptr);
789 case Type::DoubleTyID:
790 Result.DoubleVal = *((double*)Ptr);
792 case Type::PointerTyID:
793 Result.PointerVal = *((PointerTy*)Ptr);
795 case Type::X86_FP80TyID: {
796 // This is endian dependent, but it will only work on x86 anyway.
797 // FIXME: Will not trap if loading a signaling NaN.
798 uint16_t *p = (uint16_t*)Ptr;
808 Result.IntVal = APInt(80, 2, y);
812 cerr << "Cannot load value of type " << *Ty << "!\n";
817 // InitializeMemory - Recursive function to apply a Constant value into the
818 // specified memory location...
820 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
821 if (isa<UndefValue>(Init)) {
823 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
824 unsigned ElementSize =
825 getTargetData()->getABITypeSize(CP->getType()->getElementType());
826 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
827 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
829 } else if (isa<ConstantAggregateZero>(Init)) {
830 memset(Addr, 0, (size_t)getTargetData()->getABITypeSize(Init->getType()));
832 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
833 unsigned ElementSize =
834 getTargetData()->getABITypeSize(CPA->getType()->getElementType());
835 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
836 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
838 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
839 const StructLayout *SL =
840 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
841 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
842 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
844 } else if (Init->getType()->isFirstClassType()) {
845 GenericValue Val = getConstantValue(Init);
846 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
850 cerr << "Bad Type: " << *Init->getType() << "\n";
851 assert(0 && "Unknown constant type to initialize memory with!");
854 /// EmitGlobals - Emit all of the global variables to memory, storing their
855 /// addresses into GlobalAddress. This must make sure to copy the contents of
856 /// their initializers into the memory.
858 void ExecutionEngine::emitGlobals() {
859 const TargetData *TD = getTargetData();
861 // Loop over all of the global variables in the program, allocating the memory
862 // to hold them. If there is more than one module, do a prepass over globals
863 // to figure out how the different modules should link together.
865 std::map<std::pair<std::string, const Type*>,
866 const GlobalValue*> LinkedGlobalsMap;
868 if (Modules.size() != 1) {
869 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
870 Module &M = *Modules[m]->getModule();
871 for (Module::const_global_iterator I = M.global_begin(),
872 E = M.global_end(); I != E; ++I) {
873 const GlobalValue *GV = I;
874 if (GV->hasInternalLinkage() || GV->isDeclaration() ||
875 GV->hasAppendingLinkage() || !GV->hasName())
876 continue;// Ignore external globals and globals with internal linkage.
878 const GlobalValue *&GVEntry =
879 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
881 // If this is the first time we've seen this global, it is the canonical
888 // If the existing global is strong, never replace it.
889 if (GVEntry->hasExternalLinkage() ||
890 GVEntry->hasDLLImportLinkage() ||
891 GVEntry->hasDLLExportLinkage())
894 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
895 // symbol. FIXME is this right for common?
896 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
902 std::vector<const GlobalValue*> NonCanonicalGlobals;
903 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
904 Module &M = *Modules[m]->getModule();
905 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
907 // In the multi-module case, see what this global maps to.
908 if (!LinkedGlobalsMap.empty()) {
909 if (const GlobalValue *GVEntry =
910 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
911 // If something else is the canonical global, ignore this one.
912 if (GVEntry != &*I) {
913 NonCanonicalGlobals.push_back(I);
919 if (!I->isDeclaration()) {
920 // Get the type of the global.
921 const Type *Ty = I->getType()->getElementType();
923 // Allocate some memory for it!
924 unsigned Size = TD->getABITypeSize(Ty);
925 addGlobalMapping(I, new char[Size]);
927 // External variable reference. Try to use the dynamic loader to
928 // get a pointer to it.
930 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
931 addGlobalMapping(I, SymAddr);
933 cerr << "Could not resolve external global address: "
934 << I->getName() << "\n";
940 // If there are multiple modules, map the non-canonical globals to their
941 // canonical location.
942 if (!NonCanonicalGlobals.empty()) {
943 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
944 const GlobalValue *GV = NonCanonicalGlobals[i];
945 const GlobalValue *CGV =
946 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
947 void *Ptr = getPointerToGlobalIfAvailable(CGV);
948 assert(Ptr && "Canonical global wasn't codegen'd!");
949 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
953 // Now that all of the globals are set up in memory, loop through them all
954 // and initialize their contents.
955 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
957 if (!I->isDeclaration()) {
958 if (!LinkedGlobalsMap.empty()) {
959 if (const GlobalValue *GVEntry =
960 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
961 if (GVEntry != &*I) // Not the canonical variable.
964 EmitGlobalVariable(I);
970 // EmitGlobalVariable - This method emits the specified global variable to the
971 // address specified in GlobalAddresses, or allocates new memory if it's not
972 // already in the map.
973 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
974 void *GA = getPointerToGlobalIfAvailable(GV);
975 DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
977 const Type *ElTy = GV->getType()->getElementType();
978 size_t GVSize = (size_t)getTargetData()->getABITypeSize(ElTy);
980 // If it's not already specified, allocate memory for the global.
981 GA = new char[GVSize];
982 addGlobalMapping(GV, GA);
985 InitializeMemory(GV->getInitializer(), GA);
986 NumInitBytes += (unsigned)GVSize;