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)(Module *M,
39 std::string *ErrorStr,
40 JITMemoryManager *JMM,
41 CodeGenOpt::Level OptLevel,
43 CodeModel::Model CMM) = 0;
44 ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
45 std::string *ErrorStr) = 0;
46 ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
49 ExecutionEngine::ExecutionEngine(Module *M)
51 LazyFunctionCreator(0) {
52 CompilingLazily = false;
53 GVCompilationDisabled = false;
54 SymbolSearchingDisabled = false;
56 assert(M && "Module is null?");
59 ExecutionEngine::~ExecutionEngine() {
60 clearAllGlobalMappings();
61 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
65 char* ExecutionEngine::getMemoryForGV(const GlobalVariable* GV) {
66 const Type *ElTy = GV->getType()->getElementType();
67 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
68 return new char[GVSize];
71 /// removeModule - Remove a Module from the list of modules.
72 bool ExecutionEngine::removeModule(Module *M) {
73 for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
74 E = Modules.end(); I != E; ++I) {
78 clearGlobalMappingsFromModule(M);
85 /// FindFunctionNamed - Search all of the active modules to find the one that
86 /// defines FnName. This is very slow operation and shouldn't be used for
88 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
89 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
90 if (Function *F = Modules[i]->getFunction(FnName))
97 void *ExecutionEngineState::RemoveMapping(
98 const MutexGuard &, const GlobalValue *ToUnmap) {
99 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
101 if (I == GlobalAddressMap.end())
105 GlobalAddressMap.erase(I);
108 GlobalAddressReverseMap.erase(OldVal);
112 /// addGlobalMapping - Tell the execution engine that the specified global is
113 /// at the specified location. This is used internally as functions are JIT'd
114 /// and as global variables are laid out in memory. It can and should also be
115 /// used by clients of the EE that want to have an LLVM global overlay
116 /// existing data in memory.
117 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
118 MutexGuard locked(lock);
120 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
121 << "\' to [" << Addr << "]\n";);
122 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
123 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
126 // If we are using the reverse mapping, add it too
127 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
128 AssertingVH<const GlobalValue> &V =
129 EEState.getGlobalAddressReverseMap(locked)[Addr];
130 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
135 /// clearAllGlobalMappings - Clear all global mappings and start over again
136 /// use in dynamic compilation scenarios when you want to move globals
137 void ExecutionEngine::clearAllGlobalMappings() {
138 MutexGuard locked(lock);
140 EEState.getGlobalAddressMap(locked).clear();
141 EEState.getGlobalAddressReverseMap(locked).clear();
144 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
145 /// particular module, because it has been removed from the JIT.
146 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
147 MutexGuard locked(lock);
149 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
150 EEState.RemoveMapping(locked, FI);
152 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
154 EEState.RemoveMapping(locked, GI);
158 /// updateGlobalMapping - Replace an existing mapping for GV with a new
159 /// address. This updates both maps as required. If "Addr" is null, the
160 /// entry for the global is removed from the mappings.
161 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
162 MutexGuard locked(lock);
164 ExecutionEngineState::GlobalAddressMapTy &Map =
165 EEState.getGlobalAddressMap(locked);
167 // Deleting from the mapping?
169 return EEState.RemoveMapping(locked, GV);
172 void *&CurVal = Map[GV];
173 void *OldVal = CurVal;
175 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
176 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
179 // If we are using the reverse mapping, add it too
180 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
181 AssertingVH<const GlobalValue> &V =
182 EEState.getGlobalAddressReverseMap(locked)[Addr];
183 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
189 /// getPointerToGlobalIfAvailable - This returns the address of the specified
190 /// global value if it is has already been codegen'd, otherwise it returns null.
192 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
193 MutexGuard locked(lock);
195 ExecutionEngineState::GlobalAddressMapTy::iterator I =
196 EEState.getGlobalAddressMap(locked).find(GV);
197 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
200 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
201 /// at the specified address.
203 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
204 MutexGuard locked(lock);
206 // If we haven't computed the reverse mapping yet, do so first.
207 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
208 for (ExecutionEngineState::GlobalAddressMapTy::iterator
209 I = EEState.getGlobalAddressMap(locked).begin(),
210 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
211 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
215 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
216 EEState.getGlobalAddressReverseMap(locked).find(Addr);
217 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
220 // CreateArgv - Turn a vector of strings into a nice argv style array of
221 // pointers to null terminated strings.
223 static void *CreateArgv(LLVMContext &C, ExecutionEngine *EE,
224 const std::vector<std::string> &InputArgv) {
225 unsigned PtrSize = EE->getTargetData()->getPointerSize();
226 char *Result = new char[(InputArgv.size()+1)*PtrSize];
228 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Result << "\n");
229 const Type *SBytePtr = Type::getInt8PtrTy(C);
231 for (unsigned i = 0; i != InputArgv.size(); ++i) {
232 unsigned Size = InputArgv[i].size()+1;
233 char *Dest = new char[Size];
234 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
236 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
239 // Endian safe: Result[i] = (PointerTy)Dest;
240 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
245 EE->StoreValueToMemory(PTOGV(0),
246 (GenericValue*)(Result+InputArgv.size()*PtrSize),
252 /// runStaticConstructorsDestructors - This method is used to execute all of
253 /// the static constructors or destructors for a module, depending on the
254 /// value of isDtors.
255 void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
257 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
259 // Execute global ctors/dtors for each module in the program.
261 GlobalVariable *GV = module->getNamedGlobal(Name);
263 // If this global has internal linkage, or if it has a use, then it must be
264 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
265 // this is the case, don't execute any of the global ctors, __main will do
267 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
269 // Should be an array of '{ int, void ()* }' structs. The first value is
270 // the init priority, which we ignore.
271 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
272 if (!InitList) return;
273 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
274 if (ConstantStruct *CS =
275 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
276 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
278 Constant *FP = CS->getOperand(1);
279 if (FP->isNullValue())
280 break; // Found a null terminator, exit.
282 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
284 FP = CE->getOperand(0);
285 if (Function *F = dyn_cast<Function>(FP)) {
286 // Execute the ctor/dtor function!
287 runFunction(F, std::vector<GenericValue>());
292 /// runStaticConstructorsDestructors - This method is used to execute all of
293 /// the static constructors or destructors for a program, depending on the
294 /// value of isDtors.
295 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
296 // Execute global ctors/dtors for each module in the program.
297 for (unsigned m = 0, e = Modules.size(); m != e; ++m)
298 runStaticConstructorsDestructors(Modules[m], isDtors);
302 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
303 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
304 unsigned PtrSize = EE->getTargetData()->getPointerSize();
305 for (unsigned i = 0; i < PtrSize; ++i)
306 if (*(i + (uint8_t*)Loc))
312 /// runFunctionAsMain - This is a helper function which wraps runFunction to
313 /// handle the common task of starting up main with the specified argc, argv,
314 /// and envp parameters.
315 int ExecutionEngine::runFunctionAsMain(Function *Fn,
316 const std::vector<std::string> &argv,
317 const char * const * envp) {
318 std::vector<GenericValue> GVArgs;
320 GVArgc.IntVal = APInt(32, argv.size());
323 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
324 const FunctionType *FTy = Fn->getFunctionType();
325 const Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
328 if (FTy->getParamType(2) != PPInt8Ty) {
329 llvm_report_error("Invalid type for third argument of main() supplied");
333 if (FTy->getParamType(1) != PPInt8Ty) {
334 llvm_report_error("Invalid type for second argument of main() supplied");
338 if (!FTy->getParamType(0)->isInteger(32)) {
339 llvm_report_error("Invalid type for first argument of main() supplied");
343 if (!isa<IntegerType>(FTy->getReturnType()) &&
344 !FTy->getReturnType()->isVoidTy()) {
345 llvm_report_error("Invalid return type of main() supplied");
349 llvm_report_error("Invalid number of arguments of main() supplied");
353 GVArgs.push_back(GVArgc); // Arg #0 = argc.
356 GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, argv)));
357 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
358 "argv[0] was null after CreateArgv");
360 std::vector<std::string> EnvVars;
361 for (unsigned i = 0; envp[i]; ++i)
362 EnvVars.push_back(envp[i]);
364 GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, EnvVars)));
368 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
371 /// If possible, create a JIT, unless the caller specifically requests an
372 /// Interpreter or there's an error. If even an Interpreter cannot be created,
373 /// NULL is returned.
375 ExecutionEngine *ExecutionEngine::create(Module *M,
376 bool ForceInterpreter,
377 std::string *ErrorStr,
378 CodeGenOpt::Level OptLevel,
380 return EngineBuilder(M)
381 .setEngineKind(ForceInterpreter
382 ? EngineKind::Interpreter
384 .setErrorStr(ErrorStr)
385 .setOptLevel(OptLevel)
386 .setAllocateGVsWithCode(GVsWithCode)
390 ExecutionEngine *ExecutionEngine::create(Module *M) {
391 return EngineBuilder(M).create();
394 ExecutionEngine *EngineBuilder::create() {
395 // Make sure we can resolve symbols in the program as well. The zero arg
396 // to the function tells DynamicLibrary to load the program, not a library.
397 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
400 // If the user specified a memory manager but didn't specify which engine to
401 // create, we assume they only want the JIT, and we fail if they only want
404 if (WhichEngine & EngineKind::JIT)
405 WhichEngine = EngineKind::JIT;
408 *ErrorStr = "Cannot create an interpreter with a memory manager.";
413 // Unless the interpreter was explicitly selected or the JIT is not linked,
415 if (WhichEngine & EngineKind::JIT) {
416 if (ExecutionEngine::JITCtor) {
417 ExecutionEngine *EE =
418 ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
419 AllocateGVsWithCode, CMModel);
424 // If we can't make a JIT and we didn't request one specifically, try making
425 // an interpreter instead.
426 if (WhichEngine & EngineKind::Interpreter) {
427 if (ExecutionEngine::InterpCtor)
428 return ExecutionEngine::InterpCtor(M, ErrorStr);
430 *ErrorStr = "Interpreter has not been linked in.";
434 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
436 *ErrorStr = "JIT has not been linked in.";
441 /// getPointerToGlobal - This returns the address of the specified global
442 /// value. This may involve code generation if it's a function.
444 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
445 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
446 return getPointerToFunction(F);
448 MutexGuard locked(lock);
449 void *p = EEState.getGlobalAddressMap(locked)[GV];
453 // Global variable might have been added since interpreter started.
454 if (GlobalVariable *GVar =
455 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
456 EmitGlobalVariable(GVar);
458 llvm_unreachable("Global hasn't had an address allocated yet!");
459 return EEState.getGlobalAddressMap(locked)[GV];
462 /// This function converts a Constant* into a GenericValue. The interesting
463 /// part is if C is a ConstantExpr.
464 /// @brief Get a GenericValue for a Constant*
465 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
466 // If its undefined, return the garbage.
467 if (isa<UndefValue>(C)) {
469 switch (C->getType()->getTypeID()) {
470 case Type::IntegerTyID:
471 case Type::X86_FP80TyID:
472 case Type::FP128TyID:
473 case Type::PPC_FP128TyID:
474 // Although the value is undefined, we still have to construct an APInt
475 // with the correct bit width.
476 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
484 // If the value is a ConstantExpr
485 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
486 Constant *Op0 = CE->getOperand(0);
487 switch (CE->getOpcode()) {
488 case Instruction::GetElementPtr: {
490 GenericValue Result = getConstantValue(Op0);
491 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
493 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
495 char* tmp = (char*) Result.PointerVal;
496 Result = PTOGV(tmp + Offset);
499 case Instruction::Trunc: {
500 GenericValue GV = getConstantValue(Op0);
501 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
502 GV.IntVal = GV.IntVal.trunc(BitWidth);
505 case Instruction::ZExt: {
506 GenericValue GV = getConstantValue(Op0);
507 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
508 GV.IntVal = GV.IntVal.zext(BitWidth);
511 case Instruction::SExt: {
512 GenericValue GV = getConstantValue(Op0);
513 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
514 GV.IntVal = GV.IntVal.sext(BitWidth);
517 case Instruction::FPTrunc: {
519 GenericValue GV = getConstantValue(Op0);
520 GV.FloatVal = float(GV.DoubleVal);
523 case Instruction::FPExt:{
525 GenericValue GV = getConstantValue(Op0);
526 GV.DoubleVal = double(GV.FloatVal);
529 case Instruction::UIToFP: {
530 GenericValue GV = getConstantValue(Op0);
531 if (CE->getType()->isFloatTy())
532 GV.FloatVal = float(GV.IntVal.roundToDouble());
533 else if (CE->getType()->isDoubleTy())
534 GV.DoubleVal = GV.IntVal.roundToDouble();
535 else if (CE->getType()->isX86_FP80Ty()) {
536 const uint64_t zero[] = {0, 0};
537 APFloat apf = APFloat(APInt(80, 2, zero));
538 (void)apf.convertFromAPInt(GV.IntVal,
540 APFloat::rmNearestTiesToEven);
541 GV.IntVal = apf.bitcastToAPInt();
545 case Instruction::SIToFP: {
546 GenericValue GV = getConstantValue(Op0);
547 if (CE->getType()->isFloatTy())
548 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
549 else if (CE->getType()->isDoubleTy())
550 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
551 else if (CE->getType()->isX86_FP80Ty()) {
552 const uint64_t zero[] = { 0, 0};
553 APFloat apf = APFloat(APInt(80, 2, zero));
554 (void)apf.convertFromAPInt(GV.IntVal,
556 APFloat::rmNearestTiesToEven);
557 GV.IntVal = apf.bitcastToAPInt();
561 case Instruction::FPToUI: // double->APInt conversion handles sign
562 case Instruction::FPToSI: {
563 GenericValue GV = getConstantValue(Op0);
564 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
565 if (Op0->getType()->isFloatTy())
566 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
567 else if (Op0->getType()->isDoubleTy())
568 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
569 else if (Op0->getType()->isX86_FP80Ty()) {
570 APFloat apf = APFloat(GV.IntVal);
573 (void)apf.convertToInteger(&v, BitWidth,
574 CE->getOpcode()==Instruction::FPToSI,
575 APFloat::rmTowardZero, &ignored);
576 GV.IntVal = v; // endian?
580 case Instruction::PtrToInt: {
581 GenericValue GV = getConstantValue(Op0);
582 uint32_t PtrWidth = TD->getPointerSizeInBits();
583 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
586 case Instruction::IntToPtr: {
587 GenericValue GV = getConstantValue(Op0);
588 uint32_t PtrWidth = TD->getPointerSizeInBits();
589 if (PtrWidth != GV.IntVal.getBitWidth())
590 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
591 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
592 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
595 case Instruction::BitCast: {
596 GenericValue GV = getConstantValue(Op0);
597 const Type* DestTy = CE->getType();
598 switch (Op0->getType()->getTypeID()) {
599 default: llvm_unreachable("Invalid bitcast operand");
600 case Type::IntegerTyID:
601 assert(DestTy->isFloatingPoint() && "invalid bitcast");
602 if (DestTy->isFloatTy())
603 GV.FloatVal = GV.IntVal.bitsToFloat();
604 else if (DestTy->isDoubleTy())
605 GV.DoubleVal = GV.IntVal.bitsToDouble();
607 case Type::FloatTyID:
608 assert(DestTy->isInteger(32) && "Invalid bitcast");
609 GV.IntVal.floatToBits(GV.FloatVal);
611 case Type::DoubleTyID:
612 assert(DestTy->isInteger(64) && "Invalid bitcast");
613 GV.IntVal.doubleToBits(GV.DoubleVal);
615 case Type::PointerTyID:
616 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
617 break; // getConstantValue(Op0) above already converted it
621 case Instruction::Add:
622 case Instruction::FAdd:
623 case Instruction::Sub:
624 case Instruction::FSub:
625 case Instruction::Mul:
626 case Instruction::FMul:
627 case Instruction::UDiv:
628 case Instruction::SDiv:
629 case Instruction::URem:
630 case Instruction::SRem:
631 case Instruction::And:
632 case Instruction::Or:
633 case Instruction::Xor: {
634 GenericValue LHS = getConstantValue(Op0);
635 GenericValue RHS = getConstantValue(CE->getOperand(1));
637 switch (CE->getOperand(0)->getType()->getTypeID()) {
638 default: llvm_unreachable("Bad add type!");
639 case Type::IntegerTyID:
640 switch (CE->getOpcode()) {
641 default: llvm_unreachable("Invalid integer opcode");
642 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
643 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
644 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
645 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
646 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
647 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
648 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
649 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
650 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
651 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
654 case Type::FloatTyID:
655 switch (CE->getOpcode()) {
656 default: llvm_unreachable("Invalid float opcode");
657 case Instruction::FAdd:
658 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
659 case Instruction::FSub:
660 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
661 case Instruction::FMul:
662 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
663 case Instruction::FDiv:
664 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
665 case Instruction::FRem:
666 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
669 case Type::DoubleTyID:
670 switch (CE->getOpcode()) {
671 default: llvm_unreachable("Invalid double opcode");
672 case Instruction::FAdd:
673 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
674 case Instruction::FSub:
675 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
676 case Instruction::FMul:
677 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
678 case Instruction::FDiv:
679 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
680 case Instruction::FRem:
681 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
684 case Type::X86_FP80TyID:
685 case Type::PPC_FP128TyID:
686 case Type::FP128TyID: {
687 APFloat apfLHS = APFloat(LHS.IntVal);
688 switch (CE->getOpcode()) {
689 default: llvm_unreachable("Invalid long double opcode");llvm_unreachable(0);
690 case Instruction::FAdd:
691 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
692 GV.IntVal = apfLHS.bitcastToAPInt();
694 case Instruction::FSub:
695 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
696 GV.IntVal = apfLHS.bitcastToAPInt();
698 case Instruction::FMul:
699 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
700 GV.IntVal = apfLHS.bitcastToAPInt();
702 case Instruction::FDiv:
703 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
704 GV.IntVal = apfLHS.bitcastToAPInt();
706 case Instruction::FRem:
707 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
708 GV.IntVal = apfLHS.bitcastToAPInt();
720 raw_string_ostream Msg(msg);
721 Msg << "ConstantExpr not handled: " << *CE;
722 llvm_report_error(Msg.str());
726 switch (C->getType()->getTypeID()) {
727 case Type::FloatTyID:
728 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
730 case Type::DoubleTyID:
731 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
733 case Type::X86_FP80TyID:
734 case Type::FP128TyID:
735 case Type::PPC_FP128TyID:
736 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
738 case Type::IntegerTyID:
739 Result.IntVal = cast<ConstantInt>(C)->getValue();
741 case Type::PointerTyID:
742 if (isa<ConstantPointerNull>(C))
743 Result.PointerVal = 0;
744 else if (const Function *F = dyn_cast<Function>(C))
745 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
746 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
747 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
748 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
749 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
750 BA->getBasicBlock())));
752 llvm_unreachable("Unknown constant pointer type!");
756 raw_string_ostream Msg(msg);
757 Msg << "ERROR: Constant unimplemented for type: " << *C->getType();
758 llvm_report_error(Msg.str());
763 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
764 /// with the integer held in IntVal.
765 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
766 unsigned StoreBytes) {
767 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
768 uint8_t *Src = (uint8_t *)IntVal.getRawData();
770 if (sys::isLittleEndianHost())
771 // Little-endian host - the source is ordered from LSB to MSB. Order the
772 // destination from LSB to MSB: Do a straight copy.
773 memcpy(Dst, Src, StoreBytes);
775 // Big-endian host - the source is an array of 64 bit words ordered from
776 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
777 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
778 while (StoreBytes > sizeof(uint64_t)) {
779 StoreBytes -= sizeof(uint64_t);
780 // May not be aligned so use memcpy.
781 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
782 Src += sizeof(uint64_t);
785 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
789 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
790 /// is the address of the memory at which to store Val, cast to GenericValue *.
791 /// It is not a pointer to a GenericValue containing the address at which to
793 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
794 GenericValue *Ptr, const Type *Ty) {
795 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
797 switch (Ty->getTypeID()) {
798 case Type::IntegerTyID:
799 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
801 case Type::FloatTyID:
802 *((float*)Ptr) = Val.FloatVal;
804 case Type::DoubleTyID:
805 *((double*)Ptr) = Val.DoubleVal;
807 case Type::X86_FP80TyID:
808 memcpy(Ptr, Val.IntVal.getRawData(), 10);
810 case Type::PointerTyID:
811 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
812 if (StoreBytes != sizeof(PointerTy))
813 memset(Ptr, 0, StoreBytes);
815 *((PointerTy*)Ptr) = Val.PointerVal;
818 dbgs() << "Cannot store value of type " << *Ty << "!\n";
821 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
822 // Host and target are different endian - reverse the stored bytes.
823 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
826 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
827 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
828 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
829 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
830 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
832 if (sys::isLittleEndianHost())
833 // Little-endian host - the destination must be ordered from LSB to MSB.
834 // The source is ordered from LSB to MSB: Do a straight copy.
835 memcpy(Dst, Src, LoadBytes);
837 // Big-endian - the destination is an array of 64 bit words ordered from
838 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
839 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
841 while (LoadBytes > sizeof(uint64_t)) {
842 LoadBytes -= sizeof(uint64_t);
843 // May not be aligned so use memcpy.
844 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
845 Dst += sizeof(uint64_t);
848 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
854 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
857 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
859 switch (Ty->getTypeID()) {
860 case Type::IntegerTyID:
861 // An APInt with all words initially zero.
862 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
863 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
865 case Type::FloatTyID:
866 Result.FloatVal = *((float*)Ptr);
868 case Type::DoubleTyID:
869 Result.DoubleVal = *((double*)Ptr);
871 case Type::PointerTyID:
872 Result.PointerVal = *((PointerTy*)Ptr);
874 case Type::X86_FP80TyID: {
875 // This is endian dependent, but it will only work on x86 anyway.
876 // FIXME: Will not trap if loading a signaling NaN.
879 Result.IntVal = APInt(80, 2, y);
884 raw_string_ostream Msg(msg);
885 Msg << "Cannot load value of type " << *Ty << "!";
886 llvm_report_error(Msg.str());
890 // InitializeMemory - Recursive function to apply a Constant value into the
891 // specified memory location...
893 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
894 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
896 if (isa<UndefValue>(Init)) {
898 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
899 unsigned ElementSize =
900 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
901 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
902 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
904 } else if (isa<ConstantAggregateZero>(Init)) {
905 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
907 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
908 unsigned ElementSize =
909 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
910 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
911 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
913 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
914 const StructLayout *SL =
915 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
916 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
917 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
919 } else if (Init->getType()->isFirstClassType()) {
920 GenericValue Val = getConstantValue(Init);
921 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
925 dbgs() << "Bad Type: " << *Init->getType() << "\n";
926 llvm_unreachable("Unknown constant type to initialize memory with!");
929 /// EmitGlobals - Emit all of the global variables to memory, storing their
930 /// addresses into GlobalAddress. This must make sure to copy the contents of
931 /// their initializers into the memory.
933 void ExecutionEngine::emitGlobals() {
935 // Loop over all of the global variables in the program, allocating the memory
936 // to hold them. If there is more than one module, do a prepass over globals
937 // to figure out how the different modules should link together.
939 std::map<std::pair<std::string, const Type*>,
940 const GlobalValue*> LinkedGlobalsMap;
942 if (Modules.size() != 1) {
943 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
944 Module &M = *Modules[m];
945 for (Module::const_global_iterator I = M.global_begin(),
946 E = M.global_end(); I != E; ++I) {
947 const GlobalValue *GV = I;
948 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
949 GV->hasAppendingLinkage() || !GV->hasName())
950 continue;// Ignore external globals and globals with internal linkage.
952 const GlobalValue *&GVEntry =
953 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
955 // If this is the first time we've seen this global, it is the canonical
962 // If the existing global is strong, never replace it.
963 if (GVEntry->hasExternalLinkage() ||
964 GVEntry->hasDLLImportLinkage() ||
965 GVEntry->hasDLLExportLinkage())
968 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
969 // symbol. FIXME is this right for common?
970 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
976 std::vector<const GlobalValue*> NonCanonicalGlobals;
977 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
978 Module &M = *Modules[m];
979 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
981 // In the multi-module case, see what this global maps to.
982 if (!LinkedGlobalsMap.empty()) {
983 if (const GlobalValue *GVEntry =
984 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
985 // If something else is the canonical global, ignore this one.
986 if (GVEntry != &*I) {
987 NonCanonicalGlobals.push_back(I);
993 if (!I->isDeclaration()) {
994 addGlobalMapping(I, getMemoryForGV(I));
996 // External variable reference. Try to use the dynamic loader to
997 // get a pointer to it.
999 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1000 addGlobalMapping(I, SymAddr);
1002 llvm_report_error("Could not resolve external global address: "
1008 // If there are multiple modules, map the non-canonical globals to their
1009 // canonical location.
1010 if (!NonCanonicalGlobals.empty()) {
1011 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1012 const GlobalValue *GV = NonCanonicalGlobals[i];
1013 const GlobalValue *CGV =
1014 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1015 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1016 assert(Ptr && "Canonical global wasn't codegen'd!");
1017 addGlobalMapping(GV, Ptr);
1021 // Now that all of the globals are set up in memory, loop through them all
1022 // and initialize their contents.
1023 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1025 if (!I->isDeclaration()) {
1026 if (!LinkedGlobalsMap.empty()) {
1027 if (const GlobalValue *GVEntry =
1028 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1029 if (GVEntry != &*I) // Not the canonical variable.
1032 EmitGlobalVariable(I);
1038 // EmitGlobalVariable - This method emits the specified global variable to the
1039 // address specified in GlobalAddresses, or allocates new memory if it's not
1040 // already in the map.
1041 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1042 void *GA = getPointerToGlobalIfAvailable(GV);
1045 // If it's not already specified, allocate memory for the global.
1046 GA = getMemoryForGV(GV);
1047 addGlobalMapping(GV, GA);
1050 // Don't initialize if it's thread local, let the client do it.
1051 if (!GV->isThreadLocal())
1052 InitializeMemory(GV->getInitializer(), GA);
1054 const Type *ElTy = GV->getType()->getElementType();
1055 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
1056 NumInitBytes += (unsigned)GVSize;
1060 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1061 : EE(EE), GlobalAddressMap(this) {
1064 sys::Mutex *ExecutionEngineState::AddressMapConfig::getMutex(
1065 ExecutionEngineState *EES) {
1066 return &EES->EE.lock;
1068 void ExecutionEngineState::AddressMapConfig::onDelete(
1069 ExecutionEngineState *EES, const GlobalValue *Old) {
1070 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1071 EES->GlobalAddressReverseMap.erase(OldVal);
1074 void ExecutionEngineState::AddressMapConfig::onRAUW(
1075 ExecutionEngineState *, const GlobalValue *, const GlobalValue *) {
1076 assert(false && "The ExecutionEngine doesn't know how to handle a"
1077 " RAUW on a value it has a global mapping for.");