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/ExecutionEngine/ExecutionEngine.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Module.h"
21 #include "llvm/ExecutionEngine/GenericValue.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/MutexGuard.h"
26 #include "llvm/Support/ValueHandle.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/System/DynamicLibrary.h"
29 #include "llvm/System/Host.h"
30 #include "llvm/Target/TargetData.h"
35 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
36 STATISTIC(NumGlobals , "Number of global vars initialized");
38 ExecutionEngine *(*ExecutionEngine::JITCtor)(
40 std::string *ErrorStr,
41 JITMemoryManager *JMM,
42 CodeGenOpt::Level OptLevel,
47 const SmallVectorImpl<std::string>& MAttrs) = 0;
48 ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
49 std::string *ErrorStr) = 0;
50 ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
53 ExecutionEngine::ExecutionEngine(Module *M)
55 LazyFunctionCreator(0) {
56 CompilingLazily = false;
57 GVCompilationDisabled = false;
58 SymbolSearchingDisabled = false;
60 assert(M && "Module is null?");
63 ExecutionEngine::~ExecutionEngine() {
64 clearAllGlobalMappings();
65 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
69 char* ExecutionEngine::getMemoryForGV(const GlobalVariable* GV) {
70 const Type *ElTy = GV->getType()->getElementType();
71 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
72 return new char[GVSize];
75 /// removeModule - Remove a Module from the list of modules.
76 bool ExecutionEngine::removeModule(Module *M) {
77 for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
78 E = Modules.end(); I != E; ++I) {
82 clearGlobalMappingsFromModule(M);
89 /// FindFunctionNamed - Search all of the active modules to find the one that
90 /// defines FnName. This is very slow operation and shouldn't be used for
92 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
93 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
94 if (Function *F = Modules[i]->getFunction(FnName))
101 void *ExecutionEngineState::RemoveMapping(
102 const MutexGuard &, const GlobalValue *ToUnmap) {
103 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
105 if (I == GlobalAddressMap.end())
109 GlobalAddressMap.erase(I);
112 GlobalAddressReverseMap.erase(OldVal);
116 /// addGlobalMapping - Tell the execution engine that the specified global is
117 /// at the specified location. This is used internally as functions are JIT'd
118 /// and as global variables are laid out in memory. It can and should also be
119 /// used by clients of the EE that want to have an LLVM global overlay
120 /// existing data in memory.
121 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
122 MutexGuard locked(lock);
124 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
125 << "\' to [" << Addr << "]\n";);
126 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
127 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
130 // If we are using the reverse mapping, add it too
131 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
132 AssertingVH<const GlobalValue> &V =
133 EEState.getGlobalAddressReverseMap(locked)[Addr];
134 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
139 /// clearAllGlobalMappings - Clear all global mappings and start over again
140 /// use in dynamic compilation scenarios when you want to move globals
141 void ExecutionEngine::clearAllGlobalMappings() {
142 MutexGuard locked(lock);
144 EEState.getGlobalAddressMap(locked).clear();
145 EEState.getGlobalAddressReverseMap(locked).clear();
148 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
149 /// particular module, because it has been removed from the JIT.
150 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
151 MutexGuard locked(lock);
153 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
154 EEState.RemoveMapping(locked, FI);
156 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
158 EEState.RemoveMapping(locked, GI);
162 /// updateGlobalMapping - Replace an existing mapping for GV with a new
163 /// address. This updates both maps as required. If "Addr" is null, the
164 /// entry for the global is removed from the mappings.
165 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
166 MutexGuard locked(lock);
168 ExecutionEngineState::GlobalAddressMapTy &Map =
169 EEState.getGlobalAddressMap(locked);
171 // Deleting from the mapping?
173 return EEState.RemoveMapping(locked, GV);
176 void *&CurVal = Map[GV];
177 void *OldVal = CurVal;
179 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
180 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
183 // If we are using the reverse mapping, add it too
184 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
185 AssertingVH<const GlobalValue> &V =
186 EEState.getGlobalAddressReverseMap(locked)[Addr];
187 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
193 /// getPointerToGlobalIfAvailable - This returns the address of the specified
194 /// global value if it is has already been codegen'd, otherwise it returns null.
196 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
197 MutexGuard locked(lock);
199 ExecutionEngineState::GlobalAddressMapTy::iterator I =
200 EEState.getGlobalAddressMap(locked).find(GV);
201 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
204 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
205 /// at the specified address.
207 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
208 MutexGuard locked(lock);
210 // If we haven't computed the reverse mapping yet, do so first.
211 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
212 for (ExecutionEngineState::GlobalAddressMapTy::iterator
213 I = EEState.getGlobalAddressMap(locked).begin(),
214 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
215 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
219 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
220 EEState.getGlobalAddressReverseMap(locked).find(Addr);
221 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
227 std::vector<char*> Values;
229 ArgvArray() : Array(NULL) {}
230 ~ArgvArray() { clear(); }
234 for (size_t I = 0, E = Values.size(); I != E; ++I) {
239 /// Turn a vector of strings into a nice argv style array of pointers to null
240 /// terminated strings.
241 void *reset(LLVMContext &C, ExecutionEngine *EE,
242 const std::vector<std::string> &InputArgv);
244 } // anonymous namespace
245 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
246 const std::vector<std::string> &InputArgv) {
247 clear(); // Free the old contents.
248 unsigned PtrSize = EE->getTargetData()->getPointerSize();
249 Array = new char[(InputArgv.size()+1)*PtrSize];
251 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
252 const Type *SBytePtr = Type::getInt8PtrTy(C);
254 for (unsigned i = 0; i != InputArgv.size(); ++i) {
255 unsigned Size = InputArgv[i].size()+1;
256 char *Dest = new char[Size];
257 Values.push_back(Dest);
258 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
260 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
263 // Endian safe: Array[i] = (PointerTy)Dest;
264 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
269 EE->StoreValueToMemory(PTOGV(0),
270 (GenericValue*)(Array+InputArgv.size()*PtrSize),
276 /// runStaticConstructorsDestructors - This method is used to execute all of
277 /// the static constructors or destructors for a module, depending on the
278 /// value of isDtors.
279 void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
281 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
283 // Execute global ctors/dtors for each module in the program.
285 GlobalVariable *GV = module->getNamedGlobal(Name);
287 // If this global has internal linkage, or if it has a use, then it must be
288 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
289 // this is the case, don't execute any of the global ctors, __main will do
291 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
293 // Should be an array of '{ int, void ()* }' structs. The first value is
294 // the init priority, which we ignore.
295 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
296 if (!InitList) return;
297 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
298 if (ConstantStruct *CS =
299 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
300 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
302 Constant *FP = CS->getOperand(1);
303 if (FP->isNullValue())
304 break; // Found a null terminator, exit.
306 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
308 FP = CE->getOperand(0);
309 if (Function *F = dyn_cast<Function>(FP)) {
310 // Execute the ctor/dtor function!
311 runFunction(F, std::vector<GenericValue>());
316 /// runStaticConstructorsDestructors - This method is used to execute all of
317 /// the static constructors or destructors for a program, depending on the
318 /// value of isDtors.
319 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
320 // Execute global ctors/dtors for each module in the program.
321 for (unsigned m = 0, e = Modules.size(); m != e; ++m)
322 runStaticConstructorsDestructors(Modules[m], isDtors);
326 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
327 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
328 unsigned PtrSize = EE->getTargetData()->getPointerSize();
329 for (unsigned i = 0; i < PtrSize; ++i)
330 if (*(i + (uint8_t*)Loc))
336 /// runFunctionAsMain - This is a helper function which wraps runFunction to
337 /// handle the common task of starting up main with the specified argc, argv,
338 /// and envp parameters.
339 int ExecutionEngine::runFunctionAsMain(Function *Fn,
340 const std::vector<std::string> &argv,
341 const char * const * envp) {
342 std::vector<GenericValue> GVArgs;
344 GVArgc.IntVal = APInt(32, argv.size());
347 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
348 const FunctionType *FTy = Fn->getFunctionType();
349 const Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
352 if (FTy->getParamType(2) != PPInt8Ty) {
353 llvm_report_error("Invalid type for third argument of main() supplied");
357 if (FTy->getParamType(1) != PPInt8Ty) {
358 llvm_report_error("Invalid type for second argument of main() supplied");
362 if (!FTy->getParamType(0)->isIntegerTy(32)) {
363 llvm_report_error("Invalid type for first argument of main() supplied");
367 if (!FTy->getReturnType()->isIntegerTy() &&
368 !FTy->getReturnType()->isVoidTy()) {
369 llvm_report_error("Invalid return type of main() supplied");
373 llvm_report_error("Invalid number of arguments of main() supplied");
379 GVArgs.push_back(GVArgc); // Arg #0 = argc.
382 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
383 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
384 "argv[0] was null after CreateArgv");
386 std::vector<std::string> EnvVars;
387 for (unsigned i = 0; envp[i]; ++i)
388 EnvVars.push_back(envp[i]);
390 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
394 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
397 /// If possible, create a JIT, unless the caller specifically requests an
398 /// Interpreter or there's an error. If even an Interpreter cannot be created,
399 /// NULL is returned.
401 ExecutionEngine *ExecutionEngine::create(Module *M,
402 bool ForceInterpreter,
403 std::string *ErrorStr,
404 CodeGenOpt::Level OptLevel,
406 return EngineBuilder(M)
407 .setEngineKind(ForceInterpreter
408 ? EngineKind::Interpreter
410 .setErrorStr(ErrorStr)
411 .setOptLevel(OptLevel)
412 .setAllocateGVsWithCode(GVsWithCode)
416 ExecutionEngine *EngineBuilder::create() {
417 // Make sure we can resolve symbols in the program as well. The zero arg
418 // to the function tells DynamicLibrary to load the program, not a library.
419 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
422 // If the user specified a memory manager but didn't specify which engine to
423 // create, we assume they only want the JIT, and we fail if they only want
426 if (WhichEngine & EngineKind::JIT)
427 WhichEngine = EngineKind::JIT;
430 *ErrorStr = "Cannot create an interpreter with a memory manager.";
435 // Unless the interpreter was explicitly selected or the JIT is not linked,
437 if (WhichEngine & EngineKind::JIT) {
438 if (ExecutionEngine::JITCtor) {
439 ExecutionEngine *EE =
440 ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
441 AllocateGVsWithCode, CMModel,
442 MArch, MCPU, MAttrs);
447 // If we can't make a JIT and we didn't request one specifically, try making
448 // an interpreter instead.
449 if (WhichEngine & EngineKind::Interpreter) {
450 if (ExecutionEngine::InterpCtor)
451 return ExecutionEngine::InterpCtor(M, ErrorStr);
453 *ErrorStr = "Interpreter has not been linked in.";
457 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
459 *ErrorStr = "JIT has not been linked in.";
464 /// getPointerToGlobal - This returns the address of the specified global
465 /// value. This may involve code generation if it's a function.
467 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
468 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
469 return getPointerToFunction(F);
471 MutexGuard locked(lock);
472 void *p = EEState.getGlobalAddressMap(locked)[GV];
476 // Global variable might have been added since interpreter started.
477 if (GlobalVariable *GVar =
478 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
479 EmitGlobalVariable(GVar);
481 llvm_unreachable("Global hasn't had an address allocated yet!");
482 return EEState.getGlobalAddressMap(locked)[GV];
485 /// This function converts a Constant* into a GenericValue. The interesting
486 /// part is if C is a ConstantExpr.
487 /// @brief Get a GenericValue for a Constant*
488 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
489 // If its undefined, return the garbage.
490 if (isa<UndefValue>(C)) {
492 switch (C->getType()->getTypeID()) {
493 case Type::IntegerTyID:
494 case Type::X86_FP80TyID:
495 case Type::FP128TyID:
496 case Type::PPC_FP128TyID:
497 // Although the value is undefined, we still have to construct an APInt
498 // with the correct bit width.
499 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
507 // If the value is a ConstantExpr
508 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
509 Constant *Op0 = CE->getOperand(0);
510 switch (CE->getOpcode()) {
511 case Instruction::GetElementPtr: {
513 GenericValue Result = getConstantValue(Op0);
514 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
516 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
518 char* tmp = (char*) Result.PointerVal;
519 Result = PTOGV(tmp + Offset);
522 case Instruction::Trunc: {
523 GenericValue GV = getConstantValue(Op0);
524 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
525 GV.IntVal = GV.IntVal.trunc(BitWidth);
528 case Instruction::ZExt: {
529 GenericValue GV = getConstantValue(Op0);
530 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
531 GV.IntVal = GV.IntVal.zext(BitWidth);
534 case Instruction::SExt: {
535 GenericValue GV = getConstantValue(Op0);
536 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
537 GV.IntVal = GV.IntVal.sext(BitWidth);
540 case Instruction::FPTrunc: {
542 GenericValue GV = getConstantValue(Op0);
543 GV.FloatVal = float(GV.DoubleVal);
546 case Instruction::FPExt:{
548 GenericValue GV = getConstantValue(Op0);
549 GV.DoubleVal = double(GV.FloatVal);
552 case Instruction::UIToFP: {
553 GenericValue GV = getConstantValue(Op0);
554 if (CE->getType()->isFloatTy())
555 GV.FloatVal = float(GV.IntVal.roundToDouble());
556 else if (CE->getType()->isDoubleTy())
557 GV.DoubleVal = GV.IntVal.roundToDouble();
558 else if (CE->getType()->isX86_FP80Ty()) {
559 const uint64_t zero[] = {0, 0};
560 APFloat apf = APFloat(APInt(80, 2, zero));
561 (void)apf.convertFromAPInt(GV.IntVal,
563 APFloat::rmNearestTiesToEven);
564 GV.IntVal = apf.bitcastToAPInt();
568 case Instruction::SIToFP: {
569 GenericValue GV = getConstantValue(Op0);
570 if (CE->getType()->isFloatTy())
571 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
572 else if (CE->getType()->isDoubleTy())
573 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
574 else if (CE->getType()->isX86_FP80Ty()) {
575 const uint64_t zero[] = { 0, 0};
576 APFloat apf = APFloat(APInt(80, 2, zero));
577 (void)apf.convertFromAPInt(GV.IntVal,
579 APFloat::rmNearestTiesToEven);
580 GV.IntVal = apf.bitcastToAPInt();
584 case Instruction::FPToUI: // double->APInt conversion handles sign
585 case Instruction::FPToSI: {
586 GenericValue GV = getConstantValue(Op0);
587 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
588 if (Op0->getType()->isFloatTy())
589 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
590 else if (Op0->getType()->isDoubleTy())
591 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
592 else if (Op0->getType()->isX86_FP80Ty()) {
593 APFloat apf = APFloat(GV.IntVal);
596 (void)apf.convertToInteger(&v, BitWidth,
597 CE->getOpcode()==Instruction::FPToSI,
598 APFloat::rmTowardZero, &ignored);
599 GV.IntVal = v; // endian?
603 case Instruction::PtrToInt: {
604 GenericValue GV = getConstantValue(Op0);
605 uint32_t PtrWidth = TD->getPointerSizeInBits();
606 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
609 case Instruction::IntToPtr: {
610 GenericValue GV = getConstantValue(Op0);
611 uint32_t PtrWidth = TD->getPointerSizeInBits();
612 if (PtrWidth != GV.IntVal.getBitWidth())
613 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
614 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
615 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
618 case Instruction::BitCast: {
619 GenericValue GV = getConstantValue(Op0);
620 const Type* DestTy = CE->getType();
621 switch (Op0->getType()->getTypeID()) {
622 default: llvm_unreachable("Invalid bitcast operand");
623 case Type::IntegerTyID:
624 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
625 if (DestTy->isFloatTy())
626 GV.FloatVal = GV.IntVal.bitsToFloat();
627 else if (DestTy->isDoubleTy())
628 GV.DoubleVal = GV.IntVal.bitsToDouble();
630 case Type::FloatTyID:
631 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
632 GV.IntVal.floatToBits(GV.FloatVal);
634 case Type::DoubleTyID:
635 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
636 GV.IntVal.doubleToBits(GV.DoubleVal);
638 case Type::PointerTyID:
639 assert(DestTy->isPointerTy() && "Invalid bitcast");
640 break; // getConstantValue(Op0) above already converted it
644 case Instruction::Add:
645 case Instruction::FAdd:
646 case Instruction::Sub:
647 case Instruction::FSub:
648 case Instruction::Mul:
649 case Instruction::FMul:
650 case Instruction::UDiv:
651 case Instruction::SDiv:
652 case Instruction::URem:
653 case Instruction::SRem:
654 case Instruction::And:
655 case Instruction::Or:
656 case Instruction::Xor: {
657 GenericValue LHS = getConstantValue(Op0);
658 GenericValue RHS = getConstantValue(CE->getOperand(1));
660 switch (CE->getOperand(0)->getType()->getTypeID()) {
661 default: llvm_unreachable("Bad add type!");
662 case Type::IntegerTyID:
663 switch (CE->getOpcode()) {
664 default: llvm_unreachable("Invalid integer opcode");
665 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
666 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
667 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
668 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
669 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
670 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
671 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
672 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
673 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
674 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
677 case Type::FloatTyID:
678 switch (CE->getOpcode()) {
679 default: llvm_unreachable("Invalid float opcode");
680 case Instruction::FAdd:
681 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
682 case Instruction::FSub:
683 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
684 case Instruction::FMul:
685 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
686 case Instruction::FDiv:
687 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
688 case Instruction::FRem:
689 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
692 case Type::DoubleTyID:
693 switch (CE->getOpcode()) {
694 default: llvm_unreachable("Invalid double opcode");
695 case Instruction::FAdd:
696 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
697 case Instruction::FSub:
698 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
699 case Instruction::FMul:
700 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
701 case Instruction::FDiv:
702 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
703 case Instruction::FRem:
704 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
707 case Type::X86_FP80TyID:
708 case Type::PPC_FP128TyID:
709 case Type::FP128TyID: {
710 APFloat apfLHS = APFloat(LHS.IntVal);
711 switch (CE->getOpcode()) {
712 default: llvm_unreachable("Invalid long double opcode");llvm_unreachable(0);
713 case Instruction::FAdd:
714 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
715 GV.IntVal = apfLHS.bitcastToAPInt();
717 case Instruction::FSub:
718 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
719 GV.IntVal = apfLHS.bitcastToAPInt();
721 case Instruction::FMul:
722 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
723 GV.IntVal = apfLHS.bitcastToAPInt();
725 case Instruction::FDiv:
726 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
727 GV.IntVal = apfLHS.bitcastToAPInt();
729 case Instruction::FRem:
730 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
731 GV.IntVal = apfLHS.bitcastToAPInt();
743 raw_string_ostream Msg(msg);
744 Msg << "ConstantExpr not handled: " << *CE;
745 llvm_report_error(Msg.str());
749 switch (C->getType()->getTypeID()) {
750 case Type::FloatTyID:
751 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
753 case Type::DoubleTyID:
754 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
756 case Type::X86_FP80TyID:
757 case Type::FP128TyID:
758 case Type::PPC_FP128TyID:
759 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
761 case Type::IntegerTyID:
762 Result.IntVal = cast<ConstantInt>(C)->getValue();
764 case Type::PointerTyID:
765 if (isa<ConstantPointerNull>(C))
766 Result.PointerVal = 0;
767 else if (const Function *F = dyn_cast<Function>(C))
768 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
769 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
770 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
771 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
772 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
773 BA->getBasicBlock())));
775 llvm_unreachable("Unknown constant pointer type!");
779 raw_string_ostream Msg(msg);
780 Msg << "ERROR: Constant unimplemented for type: " << *C->getType();
781 llvm_report_error(Msg.str());
786 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
787 /// with the integer held in IntVal.
788 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
789 unsigned StoreBytes) {
790 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
791 uint8_t *Src = (uint8_t *)IntVal.getRawData();
793 if (sys::isLittleEndianHost())
794 // Little-endian host - the source is ordered from LSB to MSB. Order the
795 // destination from LSB to MSB: Do a straight copy.
796 memcpy(Dst, Src, StoreBytes);
798 // Big-endian host - the source is an array of 64 bit words ordered from
799 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
800 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
801 while (StoreBytes > sizeof(uint64_t)) {
802 StoreBytes -= sizeof(uint64_t);
803 // May not be aligned so use memcpy.
804 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
805 Src += sizeof(uint64_t);
808 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
812 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
813 /// is the address of the memory at which to store Val, cast to GenericValue *.
814 /// It is not a pointer to a GenericValue containing the address at which to
816 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
817 GenericValue *Ptr, const Type *Ty) {
818 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
820 switch (Ty->getTypeID()) {
821 case Type::IntegerTyID:
822 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
824 case Type::FloatTyID:
825 *((float*)Ptr) = Val.FloatVal;
827 case Type::DoubleTyID:
828 *((double*)Ptr) = Val.DoubleVal;
830 case Type::X86_FP80TyID:
831 memcpy(Ptr, Val.IntVal.getRawData(), 10);
833 case Type::PointerTyID:
834 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
835 if (StoreBytes != sizeof(PointerTy))
836 memset(Ptr, 0, StoreBytes);
838 *((PointerTy*)Ptr) = Val.PointerVal;
841 dbgs() << "Cannot store value of type " << *Ty << "!\n";
844 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
845 // Host and target are different endian - reverse the stored bytes.
846 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
849 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
850 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
851 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
852 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
853 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
855 if (sys::isLittleEndianHost())
856 // Little-endian host - the destination must be ordered from LSB to MSB.
857 // The source is ordered from LSB to MSB: Do a straight copy.
858 memcpy(Dst, Src, LoadBytes);
860 // Big-endian - the destination is an array of 64 bit words ordered from
861 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
862 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
864 while (LoadBytes > sizeof(uint64_t)) {
865 LoadBytes -= sizeof(uint64_t);
866 // May not be aligned so use memcpy.
867 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
868 Dst += sizeof(uint64_t);
871 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
877 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
880 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
882 switch (Ty->getTypeID()) {
883 case Type::IntegerTyID:
884 // An APInt with all words initially zero.
885 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
886 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
888 case Type::FloatTyID:
889 Result.FloatVal = *((float*)Ptr);
891 case Type::DoubleTyID:
892 Result.DoubleVal = *((double*)Ptr);
894 case Type::PointerTyID:
895 Result.PointerVal = *((PointerTy*)Ptr);
897 case Type::X86_FP80TyID: {
898 // This is endian dependent, but it will only work on x86 anyway.
899 // FIXME: Will not trap if loading a signaling NaN.
902 Result.IntVal = APInt(80, 2, y);
907 raw_string_ostream Msg(msg);
908 Msg << "Cannot load value of type " << *Ty << "!";
909 llvm_report_error(Msg.str());
913 // InitializeMemory - Recursive function to apply a Constant value into the
914 // specified memory location...
916 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
917 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
919 if (isa<UndefValue>(Init)) {
921 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
922 unsigned ElementSize =
923 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
924 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
925 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
927 } else if (isa<ConstantAggregateZero>(Init)) {
928 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
930 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
931 unsigned ElementSize =
932 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
933 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
934 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
936 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
937 const StructLayout *SL =
938 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
939 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
940 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
942 } else if (Init->getType()->isFirstClassType()) {
943 GenericValue Val = getConstantValue(Init);
944 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
948 dbgs() << "Bad Type: " << *Init->getType() << "\n";
949 llvm_unreachable("Unknown constant type to initialize memory with!");
952 /// EmitGlobals - Emit all of the global variables to memory, storing their
953 /// addresses into GlobalAddress. This must make sure to copy the contents of
954 /// their initializers into the memory.
956 void ExecutionEngine::emitGlobals() {
958 // Loop over all of the global variables in the program, allocating the memory
959 // to hold them. If there is more than one module, do a prepass over globals
960 // to figure out how the different modules should link together.
962 std::map<std::pair<std::string, const Type*>,
963 const GlobalValue*> LinkedGlobalsMap;
965 if (Modules.size() != 1) {
966 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
967 Module &M = *Modules[m];
968 for (Module::const_global_iterator I = M.global_begin(),
969 E = M.global_end(); I != E; ++I) {
970 const GlobalValue *GV = I;
971 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
972 GV->hasAppendingLinkage() || !GV->hasName())
973 continue;// Ignore external globals and globals with internal linkage.
975 const GlobalValue *&GVEntry =
976 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
978 // If this is the first time we've seen this global, it is the canonical
985 // If the existing global is strong, never replace it.
986 if (GVEntry->hasExternalLinkage() ||
987 GVEntry->hasDLLImportLinkage() ||
988 GVEntry->hasDLLExportLinkage())
991 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
992 // symbol. FIXME is this right for common?
993 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
999 std::vector<const GlobalValue*> NonCanonicalGlobals;
1000 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1001 Module &M = *Modules[m];
1002 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1004 // In the multi-module case, see what this global maps to.
1005 if (!LinkedGlobalsMap.empty()) {
1006 if (const GlobalValue *GVEntry =
1007 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1008 // If something else is the canonical global, ignore this one.
1009 if (GVEntry != &*I) {
1010 NonCanonicalGlobals.push_back(I);
1016 if (!I->isDeclaration()) {
1017 addGlobalMapping(I, getMemoryForGV(I));
1019 // External variable reference. Try to use the dynamic loader to
1020 // get a pointer to it.
1022 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1023 addGlobalMapping(I, SymAddr);
1025 llvm_report_error("Could not resolve external global address: "
1031 // If there are multiple modules, map the non-canonical globals to their
1032 // canonical location.
1033 if (!NonCanonicalGlobals.empty()) {
1034 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1035 const GlobalValue *GV = NonCanonicalGlobals[i];
1036 const GlobalValue *CGV =
1037 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1038 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1039 assert(Ptr && "Canonical global wasn't codegen'd!");
1040 addGlobalMapping(GV, Ptr);
1044 // Now that all of the globals are set up in memory, loop through them all
1045 // and initialize their contents.
1046 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1048 if (!I->isDeclaration()) {
1049 if (!LinkedGlobalsMap.empty()) {
1050 if (const GlobalValue *GVEntry =
1051 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1052 if (GVEntry != &*I) // Not the canonical variable.
1055 EmitGlobalVariable(I);
1061 // EmitGlobalVariable - This method emits the specified global variable to the
1062 // address specified in GlobalAddresses, or allocates new memory if it's not
1063 // already in the map.
1064 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1065 void *GA = getPointerToGlobalIfAvailable(GV);
1068 // If it's not already specified, allocate memory for the global.
1069 GA = getMemoryForGV(GV);
1070 addGlobalMapping(GV, GA);
1073 // Don't initialize if it's thread local, let the client do it.
1074 if (!GV->isThreadLocal())
1075 InitializeMemory(GV->getInitializer(), GA);
1077 const Type *ElTy = GV->getType()->getElementType();
1078 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
1079 NumInitBytes += (unsigned)GVSize;
1083 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1084 : EE(EE), GlobalAddressMap(this) {
1087 sys::Mutex *ExecutionEngineState::AddressMapConfig::getMutex(
1088 ExecutionEngineState *EES) {
1089 return &EES->EE.lock;
1091 void ExecutionEngineState::AddressMapConfig::onDelete(
1092 ExecutionEngineState *EES, const GlobalValue *Old) {
1093 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1094 EES->GlobalAddressReverseMap.erase(OldVal);
1097 void ExecutionEngineState::AddressMapConfig::onRAUW(
1098 ExecutionEngineState *, const GlobalValue *, const GlobalValue *) {
1099 assert(false && "The ExecutionEngine doesn't know how to handle a"
1100 " RAUW on a value it has a global mapping for.");