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/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/ExecutionEngine/GenericValue.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/MutexGuard.h"
28 #include "llvm/Support/ValueHandle.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Support/DynamicLibrary.h"
31 #include "llvm/Support/Host.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/DataLayout.h"
34 #include "llvm/Target/TargetMachine.h"
39 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
40 STATISTIC(NumGlobals , "Number of global vars initialized");
42 ExecutionEngine *(*ExecutionEngine::JITCtor)(
44 std::string *ErrorStr,
45 JITMemoryManager *JMM,
47 TargetMachine *TM) = 0;
48 ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
50 std::string *ErrorStr,
51 JITMemoryManager *JMM,
53 TargetMachine *TM) = 0;
54 ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
55 std::string *ErrorStr) = 0;
57 ExecutionEngine::ExecutionEngine(Module *M)
59 LazyFunctionCreator(0),
60 ExceptionTableRegister(0),
61 ExceptionTableDeregister(0) {
62 CompilingLazily = false;
63 GVCompilationDisabled = false;
64 SymbolSearchingDisabled = false;
66 assert(M && "Module is null?");
69 ExecutionEngine::~ExecutionEngine() {
70 clearAllGlobalMappings();
71 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
75 void ExecutionEngine::DeregisterAllTables() {
76 if (ExceptionTableDeregister) {
77 DenseMap<const Function*, void*>::iterator it = AllExceptionTables.begin();
78 DenseMap<const Function*, void*>::iterator ite = AllExceptionTables.end();
79 for (; it != ite; ++it)
80 ExceptionTableDeregister(it->second);
81 AllExceptionTables.clear();
86 /// \brief Helper class which uses a value handler to automatically deletes the
87 /// memory block when the GlobalVariable is destroyed.
88 class GVMemoryBlock : public CallbackVH {
89 GVMemoryBlock(const GlobalVariable *GV)
90 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
93 /// \brief Returns the address the GlobalVariable should be written into. The
94 /// GVMemoryBlock object prefixes that.
95 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
96 Type *ElTy = GV->getType()->getElementType();
97 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
98 void *RawMemory = ::operator new(
99 DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock),
100 TD.getPreferredAlignment(GV))
102 new(RawMemory) GVMemoryBlock(GV);
103 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
106 virtual void deleted() {
107 // We allocated with operator new and with some extra memory hanging off the
108 // end, so don't just delete this. I'm not sure if this is actually
110 this->~GVMemoryBlock();
111 ::operator delete(this);
114 } // anonymous namespace
116 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
117 return GVMemoryBlock::Create(GV, *getDataLayout());
120 bool ExecutionEngine::removeModule(Module *M) {
121 for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
122 E = Modules.end(); I != E; ++I) {
126 clearGlobalMappingsFromModule(M);
133 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
134 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
135 if (Function *F = Modules[i]->getFunction(FnName))
142 void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
143 const GlobalValue *ToUnmap) {
144 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
147 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
149 if (I == GlobalAddressMap.end())
153 GlobalAddressMap.erase(I);
156 GlobalAddressReverseMap.erase(OldVal);
160 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
161 MutexGuard locked(lock);
163 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
164 << "\' to [" << Addr << "]\n";);
165 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
166 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
169 // If we are using the reverse mapping, add it too.
170 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
171 AssertingVH<const GlobalValue> &V =
172 EEState.getGlobalAddressReverseMap(locked)[Addr];
173 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
178 void ExecutionEngine::clearAllGlobalMappings() {
179 MutexGuard locked(lock);
181 EEState.getGlobalAddressMap(locked).clear();
182 EEState.getGlobalAddressReverseMap(locked).clear();
185 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
186 MutexGuard locked(lock);
188 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
189 EEState.RemoveMapping(locked, FI);
190 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
192 EEState.RemoveMapping(locked, GI);
195 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
196 MutexGuard locked(lock);
198 ExecutionEngineState::GlobalAddressMapTy &Map =
199 EEState.getGlobalAddressMap(locked);
201 // Deleting from the mapping?
203 return EEState.RemoveMapping(locked, GV);
205 void *&CurVal = Map[GV];
206 void *OldVal = CurVal;
208 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
209 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
212 // If we are using the reverse mapping, add it too.
213 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
214 AssertingVH<const GlobalValue> &V =
215 EEState.getGlobalAddressReverseMap(locked)[Addr];
216 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
222 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
223 MutexGuard locked(lock);
225 ExecutionEngineState::GlobalAddressMapTy::iterator I =
226 EEState.getGlobalAddressMap(locked).find(GV);
227 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
230 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
231 MutexGuard locked(lock);
233 // If we haven't computed the reverse mapping yet, do so first.
234 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
235 for (ExecutionEngineState::GlobalAddressMapTy::iterator
236 I = EEState.getGlobalAddressMap(locked).begin(),
237 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
238 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
239 I->second, I->first));
242 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
243 EEState.getGlobalAddressReverseMap(locked).find(Addr);
244 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
250 std::vector<char*> Values;
252 ArgvArray() : Array(NULL) {}
253 ~ArgvArray() { clear(); }
257 for (size_t I = 0, E = Values.size(); I != E; ++I) {
262 /// Turn a vector of strings into a nice argv style array of pointers to null
263 /// terminated strings.
264 void *reset(LLVMContext &C, ExecutionEngine *EE,
265 const std::vector<std::string> &InputArgv);
267 } // anonymous namespace
268 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
269 const std::vector<std::string> &InputArgv) {
270 clear(); // Free the old contents.
271 unsigned PtrSize = EE->getDataLayout()->getPointerSize(0);
272 Array = new char[(InputArgv.size()+1)*PtrSize];
274 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
275 Type *SBytePtr = Type::getInt8PtrTy(C);
277 for (unsigned i = 0; i != InputArgv.size(); ++i) {
278 unsigned Size = InputArgv[i].size()+1;
279 char *Dest = new char[Size];
280 Values.push_back(Dest);
281 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
283 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
286 // Endian safe: Array[i] = (PointerTy)Dest;
287 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
292 EE->StoreValueToMemory(PTOGV(0),
293 (GenericValue*)(Array+InputArgv.size()*PtrSize),
298 void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
300 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
301 GlobalVariable *GV = module->getNamedGlobal(Name);
303 // If this global has internal linkage, or if it has a use, then it must be
304 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
305 // this is the case, don't execute any of the global ctors, __main will do
307 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
309 // Should be an array of '{ i32, void ()* }' structs. The first value is
310 // the init priority, which we ignore.
311 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
314 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
315 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
316 if (CS == 0) continue;
318 Constant *FP = CS->getOperand(1);
319 if (FP->isNullValue())
320 continue; // Found a sentinal value, ignore.
322 // Strip off constant expression casts.
323 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
325 FP = CE->getOperand(0);
327 // Execute the ctor/dtor function!
328 if (Function *F = dyn_cast<Function>(FP))
329 runFunction(F, std::vector<GenericValue>());
331 // FIXME: It is marginally lame that we just do nothing here if we see an
332 // entry we don't recognize. It might not be unreasonable for the verifier
333 // to not even allow this and just assert here.
337 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
338 // Execute global ctors/dtors for each module in the program.
339 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
340 runStaticConstructorsDestructors(Modules[i], isDtors);
344 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
345 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
346 unsigned PtrSize = EE->getDataLayout()->getPointerSize(0);
347 for (unsigned i = 0; i < PtrSize; ++i)
348 if (*(i + (uint8_t*)Loc))
354 int ExecutionEngine::runFunctionAsMain(Function *Fn,
355 const std::vector<std::string> &argv,
356 const char * const * envp) {
357 std::vector<GenericValue> GVArgs;
359 GVArgc.IntVal = APInt(32, argv.size());
362 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
363 FunctionType *FTy = Fn->getFunctionType();
364 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
366 // Check the argument types.
368 report_fatal_error("Invalid number of arguments of main() supplied");
369 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
370 report_fatal_error("Invalid type for third argument of main() supplied");
371 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
372 report_fatal_error("Invalid type for second argument of main() supplied");
373 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
374 report_fatal_error("Invalid type for first argument of main() supplied");
375 if (!FTy->getReturnType()->isIntegerTy() &&
376 !FTy->getReturnType()->isVoidTy())
377 report_fatal_error("Invalid return type of main() supplied");
382 GVArgs.push_back(GVArgc); // Arg #0 = argc.
385 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
386 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
387 "argv[0] was null after CreateArgv");
389 std::vector<std::string> EnvVars;
390 for (unsigned i = 0; envp[i]; ++i)
391 EnvVars.push_back(envp[i]);
393 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
398 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
401 ExecutionEngine *ExecutionEngine::create(Module *M,
402 bool ForceInterpreter,
403 std::string *ErrorStr,
404 CodeGenOpt::Level OptLevel,
406 EngineBuilder EB = EngineBuilder(M)
407 .setEngineKind(ForceInterpreter
408 ? EngineKind::Interpreter
410 .setErrorStr(ErrorStr)
411 .setOptLevel(OptLevel)
412 .setAllocateGVsWithCode(GVsWithCode);
417 /// createJIT - This is the factory method for creating a JIT for the current
418 /// machine, it does not fall back to the interpreter. This takes ownership
420 ExecutionEngine *ExecutionEngine::createJIT(Module *M,
421 std::string *ErrorStr,
422 JITMemoryManager *JMM,
423 CodeGenOpt::Level OL,
426 CodeModel::Model CMM) {
427 if (ExecutionEngine::JITCtor == 0) {
429 *ErrorStr = "JIT has not been linked in.";
433 // Use the defaults for extra parameters. Users can use EngineBuilder to
436 EB.setEngineKind(EngineKind::JIT);
437 EB.setErrorStr(ErrorStr);
438 EB.setRelocationModel(RM);
439 EB.setCodeModel(CMM);
440 EB.setAllocateGVsWithCode(GVsWithCode);
442 EB.setJITMemoryManager(JMM);
444 // TODO: permit custom TargetOptions here
445 TargetMachine *TM = EB.selectTarget();
446 if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
448 return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
451 ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
452 OwningPtr<TargetMachine> TheTM(TM); // Take ownership.
454 // Make sure we can resolve symbols in the program as well. The zero arg
455 // to the function tells DynamicLibrary to load the program, not a library.
456 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
459 // If the user specified a memory manager but didn't specify which engine to
460 // create, we assume they only want the JIT, and we fail if they only want
463 if (WhichEngine & EngineKind::JIT)
464 WhichEngine = EngineKind::JIT;
467 *ErrorStr = "Cannot create an interpreter with a memory manager.";
472 // Unless the interpreter was explicitly selected or the JIT is not linked,
474 if ((WhichEngine & EngineKind::JIT) && TheTM) {
475 Triple TT(M->getTargetTriple());
476 if (!TM->getTarget().hasJIT()) {
477 errs() << "WARNING: This target JIT is not designed for the host"
478 << " you are running. If bad things happen, please choose"
479 << " a different -march switch.\n";
482 if (UseMCJIT && ExecutionEngine::MCJITCtor) {
483 ExecutionEngine *EE =
484 ExecutionEngine::MCJITCtor(M, ErrorStr, JMM,
485 AllocateGVsWithCode, TheTM.take());
487 } else if (ExecutionEngine::JITCtor) {
488 ExecutionEngine *EE =
489 ExecutionEngine::JITCtor(M, ErrorStr, JMM,
490 AllocateGVsWithCode, TheTM.take());
495 // If we can't make a JIT and we didn't request one specifically, try making
496 // an interpreter instead.
497 if (WhichEngine & EngineKind::Interpreter) {
498 if (ExecutionEngine::InterpCtor)
499 return ExecutionEngine::InterpCtor(M, ErrorStr);
501 *ErrorStr = "Interpreter has not been linked in.";
505 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0 &&
506 ExecutionEngine::MCJITCtor == 0) {
508 *ErrorStr = "JIT has not been linked in.";
514 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
515 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
516 return getPointerToFunction(F);
518 MutexGuard locked(lock);
519 if (void *P = EEState.getGlobalAddressMap(locked)[GV])
522 // Global variable might have been added since interpreter started.
523 if (GlobalVariable *GVar =
524 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
525 EmitGlobalVariable(GVar);
527 llvm_unreachable("Global hasn't had an address allocated yet!");
529 return EEState.getGlobalAddressMap(locked)[GV];
532 /// \brief Converts a Constant* into a GenericValue, including handling of
533 /// ConstantExpr values.
534 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
535 // If its undefined, return the garbage.
536 if (isa<UndefValue>(C)) {
538 switch (C->getType()->getTypeID()) {
539 case Type::IntegerTyID:
540 case Type::X86_FP80TyID:
541 case Type::FP128TyID:
542 case Type::PPC_FP128TyID:
543 // Although the value is undefined, we still have to construct an APInt
544 // with the correct bit width.
545 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
553 // Otherwise, if the value is a ConstantExpr...
554 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
555 Constant *Op0 = CE->getOperand(0);
556 switch (CE->getOpcode()) {
557 case Instruction::GetElementPtr: {
559 GenericValue Result = getConstantValue(Op0);
560 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
561 uint64_t Offset = TD->getIndexedOffset(Op0->getType(), Indices);
563 char* tmp = (char*) Result.PointerVal;
564 Result = PTOGV(tmp + Offset);
567 case Instruction::Trunc: {
568 GenericValue GV = getConstantValue(Op0);
569 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
570 GV.IntVal = GV.IntVal.trunc(BitWidth);
573 case Instruction::ZExt: {
574 GenericValue GV = getConstantValue(Op0);
575 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
576 GV.IntVal = GV.IntVal.zext(BitWidth);
579 case Instruction::SExt: {
580 GenericValue GV = getConstantValue(Op0);
581 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
582 GV.IntVal = GV.IntVal.sext(BitWidth);
585 case Instruction::FPTrunc: {
587 GenericValue GV = getConstantValue(Op0);
588 GV.FloatVal = float(GV.DoubleVal);
591 case Instruction::FPExt:{
593 GenericValue GV = getConstantValue(Op0);
594 GV.DoubleVal = double(GV.FloatVal);
597 case Instruction::UIToFP: {
598 GenericValue GV = getConstantValue(Op0);
599 if (CE->getType()->isFloatTy())
600 GV.FloatVal = float(GV.IntVal.roundToDouble());
601 else if (CE->getType()->isDoubleTy())
602 GV.DoubleVal = GV.IntVal.roundToDouble();
603 else if (CE->getType()->isX86_FP80Ty()) {
604 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
605 (void)apf.convertFromAPInt(GV.IntVal,
607 APFloat::rmNearestTiesToEven);
608 GV.IntVal = apf.bitcastToAPInt();
612 case Instruction::SIToFP: {
613 GenericValue GV = getConstantValue(Op0);
614 if (CE->getType()->isFloatTy())
615 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
616 else if (CE->getType()->isDoubleTy())
617 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
618 else if (CE->getType()->isX86_FP80Ty()) {
619 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
620 (void)apf.convertFromAPInt(GV.IntVal,
622 APFloat::rmNearestTiesToEven);
623 GV.IntVal = apf.bitcastToAPInt();
627 case Instruction::FPToUI: // double->APInt conversion handles sign
628 case Instruction::FPToSI: {
629 GenericValue GV = getConstantValue(Op0);
630 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
631 if (Op0->getType()->isFloatTy())
632 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
633 else if (Op0->getType()->isDoubleTy())
634 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
635 else if (Op0->getType()->isX86_FP80Ty()) {
636 APFloat apf = APFloat(GV.IntVal);
639 (void)apf.convertToInteger(&v, BitWidth,
640 CE->getOpcode()==Instruction::FPToSI,
641 APFloat::rmTowardZero, &ignored);
642 GV.IntVal = v; // endian?
646 case Instruction::PtrToInt: {
647 GenericValue GV = getConstantValue(Op0);
648 unsigned AS = cast<PtrToIntInst>(CE)->getPointerAddressSpace();
649 uint32_t PtrWidth = TD->getPointerSizeInBits(AS);
650 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
653 case Instruction::IntToPtr: {
654 GenericValue GV = getConstantValue(Op0);
655 unsigned AS = cast<IntToPtrInst>(CE)->getAddressSpace();
656 uint32_t PtrWidth = TD->getPointerSizeInBits(AS);
657 if (PtrWidth != GV.IntVal.getBitWidth())
658 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
659 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
660 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
663 case Instruction::BitCast: {
664 GenericValue GV = getConstantValue(Op0);
665 Type* DestTy = CE->getType();
666 switch (Op0->getType()->getTypeID()) {
667 default: llvm_unreachable("Invalid bitcast operand");
668 case Type::IntegerTyID:
669 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
670 if (DestTy->isFloatTy())
671 GV.FloatVal = GV.IntVal.bitsToFloat();
672 else if (DestTy->isDoubleTy())
673 GV.DoubleVal = GV.IntVal.bitsToDouble();
675 case Type::FloatTyID:
676 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
677 GV.IntVal = APInt::floatToBits(GV.FloatVal);
679 case Type::DoubleTyID:
680 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
681 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
683 case Type::PointerTyID:
684 assert(DestTy->isPointerTy() && "Invalid bitcast");
685 break; // getConstantValue(Op0) above already converted it
689 case Instruction::Add:
690 case Instruction::FAdd:
691 case Instruction::Sub:
692 case Instruction::FSub:
693 case Instruction::Mul:
694 case Instruction::FMul:
695 case Instruction::UDiv:
696 case Instruction::SDiv:
697 case Instruction::URem:
698 case Instruction::SRem:
699 case Instruction::And:
700 case Instruction::Or:
701 case Instruction::Xor: {
702 GenericValue LHS = getConstantValue(Op0);
703 GenericValue RHS = getConstantValue(CE->getOperand(1));
705 switch (CE->getOperand(0)->getType()->getTypeID()) {
706 default: llvm_unreachable("Bad add type!");
707 case Type::IntegerTyID:
708 switch (CE->getOpcode()) {
709 default: llvm_unreachable("Invalid integer opcode");
710 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
711 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
712 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
713 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
714 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
715 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
716 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
717 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
718 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
719 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
722 case Type::FloatTyID:
723 switch (CE->getOpcode()) {
724 default: llvm_unreachable("Invalid float opcode");
725 case Instruction::FAdd:
726 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
727 case Instruction::FSub:
728 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
729 case Instruction::FMul:
730 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
731 case Instruction::FDiv:
732 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
733 case Instruction::FRem:
734 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
737 case Type::DoubleTyID:
738 switch (CE->getOpcode()) {
739 default: llvm_unreachable("Invalid double opcode");
740 case Instruction::FAdd:
741 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
742 case Instruction::FSub:
743 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
744 case Instruction::FMul:
745 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
746 case Instruction::FDiv:
747 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
748 case Instruction::FRem:
749 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
752 case Type::X86_FP80TyID:
753 case Type::PPC_FP128TyID:
754 case Type::FP128TyID: {
755 APFloat apfLHS = APFloat(LHS.IntVal);
756 switch (CE->getOpcode()) {
757 default: llvm_unreachable("Invalid long double opcode");
758 case Instruction::FAdd:
759 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
760 GV.IntVal = apfLHS.bitcastToAPInt();
762 case Instruction::FSub:
763 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
764 GV.IntVal = apfLHS.bitcastToAPInt();
766 case Instruction::FMul:
767 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
768 GV.IntVal = apfLHS.bitcastToAPInt();
770 case Instruction::FDiv:
771 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
772 GV.IntVal = apfLHS.bitcastToAPInt();
774 case Instruction::FRem:
775 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
776 GV.IntVal = apfLHS.bitcastToAPInt();
788 SmallString<256> Msg;
789 raw_svector_ostream OS(Msg);
790 OS << "ConstantExpr not handled: " << *CE;
791 report_fatal_error(OS.str());
794 // Otherwise, we have a simple constant.
796 switch (C->getType()->getTypeID()) {
797 case Type::FloatTyID:
798 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
800 case Type::DoubleTyID:
801 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
803 case Type::X86_FP80TyID:
804 case Type::FP128TyID:
805 case Type::PPC_FP128TyID:
806 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
808 case Type::IntegerTyID:
809 Result.IntVal = cast<ConstantInt>(C)->getValue();
811 case Type::PointerTyID:
812 if (isa<ConstantPointerNull>(C))
813 Result.PointerVal = 0;
814 else if (const Function *F = dyn_cast<Function>(C))
815 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
816 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
817 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
818 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
819 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
820 BA->getBasicBlock())));
822 llvm_unreachable("Unknown constant pointer type!");
825 SmallString<256> Msg;
826 raw_svector_ostream OS(Msg);
827 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
828 report_fatal_error(OS.str());
834 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
835 /// with the integer held in IntVal.
836 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
837 unsigned StoreBytes) {
838 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
839 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
841 if (sys::isLittleEndianHost()) {
842 // Little-endian host - the source is ordered from LSB to MSB. Order the
843 // destination from LSB to MSB: Do a straight copy.
844 memcpy(Dst, Src, StoreBytes);
846 // Big-endian host - the source is an array of 64 bit words ordered from
847 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
848 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
849 while (StoreBytes > sizeof(uint64_t)) {
850 StoreBytes -= sizeof(uint64_t);
851 // May not be aligned so use memcpy.
852 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
853 Src += sizeof(uint64_t);
856 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
860 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
861 GenericValue *Ptr, Type *Ty) {
862 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
864 switch (Ty->getTypeID()) {
865 case Type::IntegerTyID:
866 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
868 case Type::FloatTyID:
869 *((float*)Ptr) = Val.FloatVal;
871 case Type::DoubleTyID:
872 *((double*)Ptr) = Val.DoubleVal;
874 case Type::X86_FP80TyID:
875 memcpy(Ptr, Val.IntVal.getRawData(), 10);
877 case Type::PointerTyID:
878 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
879 if (StoreBytes != sizeof(PointerTy))
880 memset(&(Ptr->PointerVal), 0, StoreBytes);
882 *((PointerTy*)Ptr) = Val.PointerVal;
885 dbgs() << "Cannot store value of type " << *Ty << "!\n";
888 if (sys::isLittleEndianHost() != getDataLayout()->isLittleEndian())
889 // Host and target are different endian - reverse the stored bytes.
890 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
893 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
894 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
895 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
896 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
897 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
899 if (sys::isLittleEndianHost())
900 // Little-endian host - the destination must be ordered from LSB to MSB.
901 // The source is ordered from LSB to MSB: Do a straight copy.
902 memcpy(Dst, Src, LoadBytes);
904 // Big-endian - the destination is an array of 64 bit words ordered from
905 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
906 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
908 while (LoadBytes > sizeof(uint64_t)) {
909 LoadBytes -= sizeof(uint64_t);
910 // May not be aligned so use memcpy.
911 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
912 Dst += sizeof(uint64_t);
915 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
921 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
924 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
926 switch (Ty->getTypeID()) {
927 case Type::IntegerTyID:
928 // An APInt with all words initially zero.
929 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
930 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
932 case Type::FloatTyID:
933 Result.FloatVal = *((float*)Ptr);
935 case Type::DoubleTyID:
936 Result.DoubleVal = *((double*)Ptr);
938 case Type::PointerTyID:
939 Result.PointerVal = *((PointerTy*)Ptr);
941 case Type::X86_FP80TyID: {
942 // This is endian dependent, but it will only work on x86 anyway.
943 // FIXME: Will not trap if loading a signaling NaN.
946 Result.IntVal = APInt(80, y);
950 SmallString<256> Msg;
951 raw_svector_ostream OS(Msg);
952 OS << "Cannot load value of type " << *Ty << "!";
953 report_fatal_error(OS.str());
957 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
958 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
960 if (isa<UndefValue>(Init))
963 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
964 unsigned ElementSize =
965 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
966 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
967 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
971 if (isa<ConstantAggregateZero>(Init)) {
972 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
976 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
977 unsigned ElementSize =
978 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
979 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
980 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
984 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
985 const StructLayout *SL =
986 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
987 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
988 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
992 if (const ConstantDataSequential *CDS =
993 dyn_cast<ConstantDataSequential>(Init)) {
994 // CDS is already laid out in host memory order.
995 StringRef Data = CDS->getRawDataValues();
996 memcpy(Addr, Data.data(), Data.size());
1000 if (Init->getType()->isFirstClassType()) {
1001 GenericValue Val = getConstantValue(Init);
1002 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1006 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1007 llvm_unreachable("Unknown constant type to initialize memory with!");
1010 /// EmitGlobals - Emit all of the global variables to memory, storing their
1011 /// addresses into GlobalAddress. This must make sure to copy the contents of
1012 /// their initializers into the memory.
1013 void ExecutionEngine::emitGlobals() {
1014 // Loop over all of the global variables in the program, allocating the memory
1015 // to hold them. If there is more than one module, do a prepass over globals
1016 // to figure out how the different modules should link together.
1017 std::map<std::pair<std::string, Type*>,
1018 const GlobalValue*> LinkedGlobalsMap;
1020 if (Modules.size() != 1) {
1021 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1022 Module &M = *Modules[m];
1023 for (Module::const_global_iterator I = M.global_begin(),
1024 E = M.global_end(); I != E; ++I) {
1025 const GlobalValue *GV = I;
1026 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
1027 GV->hasAppendingLinkage() || !GV->hasName())
1028 continue;// Ignore external globals and globals with internal linkage.
1030 const GlobalValue *&GVEntry =
1031 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1033 // If this is the first time we've seen this global, it is the canonical
1040 // If the existing global is strong, never replace it.
1041 if (GVEntry->hasExternalLinkage() ||
1042 GVEntry->hasDLLImportLinkage() ||
1043 GVEntry->hasDLLExportLinkage())
1046 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1047 // symbol. FIXME is this right for common?
1048 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1054 std::vector<const GlobalValue*> NonCanonicalGlobals;
1055 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1056 Module &M = *Modules[m];
1057 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1059 // In the multi-module case, see what this global maps to.
1060 if (!LinkedGlobalsMap.empty()) {
1061 if (const GlobalValue *GVEntry =
1062 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1063 // If something else is the canonical global, ignore this one.
1064 if (GVEntry != &*I) {
1065 NonCanonicalGlobals.push_back(I);
1071 if (!I->isDeclaration()) {
1072 addGlobalMapping(I, getMemoryForGV(I));
1074 // External variable reference. Try to use the dynamic loader to
1075 // get a pointer to it.
1077 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1078 addGlobalMapping(I, SymAddr);
1080 report_fatal_error("Could not resolve external global address: "
1086 // If there are multiple modules, map the non-canonical globals to their
1087 // canonical location.
1088 if (!NonCanonicalGlobals.empty()) {
1089 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1090 const GlobalValue *GV = NonCanonicalGlobals[i];
1091 const GlobalValue *CGV =
1092 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1093 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1094 assert(Ptr && "Canonical global wasn't codegen'd!");
1095 addGlobalMapping(GV, Ptr);
1099 // Now that all of the globals are set up in memory, loop through them all
1100 // and initialize their contents.
1101 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1103 if (!I->isDeclaration()) {
1104 if (!LinkedGlobalsMap.empty()) {
1105 if (const GlobalValue *GVEntry =
1106 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1107 if (GVEntry != &*I) // Not the canonical variable.
1110 EmitGlobalVariable(I);
1116 // EmitGlobalVariable - This method emits the specified global variable to the
1117 // address specified in GlobalAddresses, or allocates new memory if it's not
1118 // already in the map.
1119 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1120 void *GA = getPointerToGlobalIfAvailable(GV);
1123 // If it's not already specified, allocate memory for the global.
1124 GA = getMemoryForGV(GV);
1125 addGlobalMapping(GV, GA);
1128 // Don't initialize if it's thread local, let the client do it.
1129 if (!GV->isThreadLocal())
1130 InitializeMemory(GV->getInitializer(), GA);
1132 Type *ElTy = GV->getType()->getElementType();
1133 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
1134 NumInitBytes += (unsigned)GVSize;
1138 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1139 : EE(EE), GlobalAddressMap(this) {
1143 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1144 return &EES->EE.lock;
1147 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1148 const GlobalValue *Old) {
1149 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1150 EES->GlobalAddressReverseMap.erase(OldVal);
1153 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1154 const GlobalValue *,
1155 const GlobalValue *) {
1156 llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1157 " RAUW on a value it has a global mapping for.");