1 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the common interface used by the various execution engine
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "jit"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Config/alloca.h"
22 #include "llvm/ExecutionEngine/ExecutionEngine.h"
23 #include "llvm/ExecutionEngine/GenericValue.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/MutexGuard.h"
26 #include "llvm/System/DynamicLibrary.h"
27 #include "llvm/System/Host.h"
28 #include "llvm/Target/TargetData.h"
32 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
33 STATISTIC(NumGlobals , "Number of global vars initialized");
35 ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
36 ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
37 ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
40 ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) {
41 LazyCompilationDisabled = false;
43 assert(P && "ModuleProvider is null?");
46 ExecutionEngine::~ExecutionEngine() {
47 clearAllGlobalMappings();
48 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
52 /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
53 /// Release module from ModuleProvider.
54 Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P,
55 std::string *ErrInfo) {
56 for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
57 E = Modules.end(); I != E; ++I) {
58 ModuleProvider *MP = *I;
61 return MP->releaseModule(ErrInfo);
67 /// FindFunctionNamed - Search all of the active modules to find the one that
68 /// defines FnName. This is very slow operation and shouldn't be used for
70 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
71 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
72 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
79 /// addGlobalMapping - Tell the execution engine that the specified global is
80 /// at the specified location. This is used internally as functions are JIT'd
81 /// and as global variables are laid out in memory. It can and should also be
82 /// used by clients of the EE that want to have an LLVM global overlay
83 /// existing data in memory.
84 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
85 MutexGuard locked(lock);
87 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
88 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
91 // If we are using the reverse mapping, add it too
92 if (!state.getGlobalAddressReverseMap(locked).empty()) {
93 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
94 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
99 /// clearAllGlobalMappings - Clear all global mappings and start over again
100 /// use in dynamic compilation scenarios when you want to move globals
101 void ExecutionEngine::clearAllGlobalMappings() {
102 MutexGuard locked(lock);
104 state.getGlobalAddressMap(locked).clear();
105 state.getGlobalAddressReverseMap(locked).clear();
108 /// updateGlobalMapping - Replace an existing mapping for GV with a new
109 /// address. This updates both maps as required. If "Addr" is null, the
110 /// entry for the global is removed from the mappings.
111 void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
112 MutexGuard locked(lock);
114 // Deleting from the mapping?
116 state.getGlobalAddressMap(locked).erase(GV);
117 if (!state.getGlobalAddressReverseMap(locked).empty())
118 state.getGlobalAddressReverseMap(locked).erase(Addr);
122 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
123 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
124 state.getGlobalAddressReverseMap(locked).erase(CurVal);
127 // If we are using the reverse mapping, add it too
128 if (!state.getGlobalAddressReverseMap(locked).empty()) {
129 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
130 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
135 /// getPointerToGlobalIfAvailable - This returns the address of the specified
136 /// global value if it is has already been codegen'd, otherwise it returns null.
138 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
139 MutexGuard locked(lock);
141 std::map<const GlobalValue*, void*>::iterator I =
142 state.getGlobalAddressMap(locked).find(GV);
143 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
146 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
147 /// at the specified address.
149 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
150 MutexGuard locked(lock);
152 // If we haven't computed the reverse mapping yet, do so first.
153 if (state.getGlobalAddressReverseMap(locked).empty()) {
154 for (std::map<const GlobalValue*, void *>::iterator
155 I = state.getGlobalAddressMap(locked).begin(),
156 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
157 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
161 std::map<void *, const GlobalValue*>::iterator I =
162 state.getGlobalAddressReverseMap(locked).find(Addr);
163 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
166 // CreateArgv - Turn a vector of strings into a nice argv style array of
167 // pointers to null terminated strings.
169 static void *CreateArgv(ExecutionEngine *EE,
170 const std::vector<std::string> &InputArgv) {
171 unsigned PtrSize = EE->getTargetData()->getPointerSize();
172 char *Result = new char[(InputArgv.size()+1)*PtrSize];
174 DOUT << "ARGV = " << (void*)Result << "\n";
175 const Type *SBytePtr = PointerType::getUnqual(Type::Int8Ty);
177 for (unsigned i = 0; i != InputArgv.size(); ++i) {
178 unsigned Size = InputArgv[i].size()+1;
179 char *Dest = new char[Size];
180 DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
182 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
185 // Endian safe: Result[i] = (PointerTy)Dest;
186 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
191 EE->StoreValueToMemory(PTOGV(0),
192 (GenericValue*)(Result+InputArgv.size()*PtrSize),
198 /// runStaticConstructorsDestructors - This method is used to execute all of
199 /// the static constructors or destructors for a program, depending on the
200 /// value of isDtors.
201 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
202 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
204 // Execute global ctors/dtors for each module in the program.
205 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
206 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
208 // If this global has internal linkage, or if it has a use, then it must be
209 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
210 // this is the case, don't execute any of the global ctors, __main will do
212 if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
214 // Should be an array of '{ int, void ()* }' structs. The first value is
215 // the init priority, which we ignore.
216 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
217 if (!InitList) continue;
218 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
219 if (ConstantStruct *CS =
220 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
221 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
223 Constant *FP = CS->getOperand(1);
224 if (FP->isNullValue())
225 break; // Found a null terminator, exit.
227 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
229 FP = CE->getOperand(0);
230 if (Function *F = dyn_cast<Function>(FP)) {
231 // Execute the ctor/dtor function!
232 runFunction(F, std::vector<GenericValue>());
238 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
239 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
240 unsigned PtrSize = EE->getTargetData()->getPointerSize();
241 for (unsigned i = 0; i < PtrSize; ++i)
242 if (*(i + (uint8_t*)Loc))
247 /// runFunctionAsMain - This is a helper function which wraps runFunction to
248 /// handle the common task of starting up main with the specified argc, argv,
249 /// and envp parameters.
250 int ExecutionEngine::runFunctionAsMain(Function *Fn,
251 const std::vector<std::string> &argv,
252 const char * const * envp) {
253 std::vector<GenericValue> GVArgs;
255 GVArgc.IntVal = APInt(32, argv.size());
258 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
259 const FunctionType *FTy = Fn->getFunctionType();
260 const Type* PPInt8Ty =
261 PointerType::getUnqual(PointerType::getUnqual(Type::Int8Ty));
264 if (FTy->getParamType(2) != PPInt8Ty) {
265 cerr << "Invalid type for third argument of main() supplied\n";
270 if (FTy->getParamType(1) != PPInt8Ty) {
271 cerr << "Invalid type for second argument of main() supplied\n";
276 if (FTy->getParamType(0) != Type::Int32Ty) {
277 cerr << "Invalid type for first argument of main() supplied\n";
282 if (FTy->getReturnType() != Type::Int32Ty &&
283 FTy->getReturnType() != Type::VoidTy) {
284 cerr << "Invalid return type of main() supplied\n";
289 cerr << "Invalid number of arguments of main() supplied\n";
294 GVArgs.push_back(GVArgc); // Arg #0 = argc.
296 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
297 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
298 "argv[0] was null after CreateArgv");
300 std::vector<std::string> EnvVars;
301 for (unsigned i = 0; envp[i]; ++i)
302 EnvVars.push_back(envp[i]);
303 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
307 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
310 /// If possible, create a JIT, unless the caller specifically requests an
311 /// Interpreter or there's an error. If even an Interpreter cannot be created,
312 /// NULL is returned.
314 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
315 bool ForceInterpreter,
316 std::string *ErrorStr) {
317 ExecutionEngine *EE = 0;
319 // Unless the interpreter was explicitly selected, try making a JIT.
320 if (!ForceInterpreter && JITCtor)
321 EE = JITCtor(MP, ErrorStr);
323 // If we can't make a JIT, make an interpreter instead.
324 if (EE == 0 && InterpCtor)
325 EE = InterpCtor(MP, ErrorStr);
328 // Make sure we can resolve symbols in the program as well. The zero arg
329 // to the function tells DynamicLibrary to load the program, not a library.
330 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr)) {
339 ExecutionEngine *ExecutionEngine::create(Module *M) {
340 return create(new ExistingModuleProvider(M));
343 /// getPointerToGlobal - This returns the address of the specified global
344 /// value. This may involve code generation if it's a function.
346 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
347 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
348 return getPointerToFunction(F);
350 MutexGuard locked(lock);
351 void *p = state.getGlobalAddressMap(locked)[GV];
355 // Global variable might have been added since interpreter started.
356 if (GlobalVariable *GVar =
357 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
358 EmitGlobalVariable(GVar);
360 assert(0 && "Global hasn't had an address allocated yet!");
361 return state.getGlobalAddressMap(locked)[GV];
364 /// This function converts a Constant* into a GenericValue. The interesting
365 /// part is if C is a ConstantExpr.
366 /// @brief Get a GenericValue for a Constant*
367 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
368 // If its undefined, return the garbage.
369 if (isa<UndefValue>(C))
370 return GenericValue();
372 // If the value is a ConstantExpr
373 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
374 Constant *Op0 = CE->getOperand(0);
375 switch (CE->getOpcode()) {
376 case Instruction::GetElementPtr: {
378 GenericValue Result = getConstantValue(Op0);
379 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
381 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
383 char* tmp = (char*) Result.PointerVal;
384 Result = PTOGV(tmp + Offset);
387 case Instruction::Trunc: {
388 GenericValue GV = getConstantValue(Op0);
389 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
390 GV.IntVal = GV.IntVal.trunc(BitWidth);
393 case Instruction::ZExt: {
394 GenericValue GV = getConstantValue(Op0);
395 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
396 GV.IntVal = GV.IntVal.zext(BitWidth);
399 case Instruction::SExt: {
400 GenericValue GV = getConstantValue(Op0);
401 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
402 GV.IntVal = GV.IntVal.sext(BitWidth);
405 case Instruction::FPTrunc: {
407 GenericValue GV = getConstantValue(Op0);
408 GV.FloatVal = float(GV.DoubleVal);
411 case Instruction::FPExt:{
413 GenericValue GV = getConstantValue(Op0);
414 GV.DoubleVal = double(GV.FloatVal);
417 case Instruction::UIToFP: {
418 GenericValue GV = getConstantValue(Op0);
419 if (CE->getType() == Type::FloatTy)
420 GV.FloatVal = float(GV.IntVal.roundToDouble());
421 else if (CE->getType() == Type::DoubleTy)
422 GV.DoubleVal = GV.IntVal.roundToDouble();
423 else if (CE->getType() == Type::X86_FP80Ty) {
424 const uint64_t zero[] = {0, 0};
425 APFloat apf = APFloat(APInt(80, 2, zero));
426 (void)apf.convertFromZeroExtendedInteger(GV.IntVal.getRawData(),
427 GV.IntVal.getBitWidth(), false,
428 APFloat::rmNearestTiesToEven);
429 GV.IntVal = apf.convertToAPInt();
433 case Instruction::SIToFP: {
434 GenericValue GV = getConstantValue(Op0);
435 if (CE->getType() == Type::FloatTy)
436 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
437 else if (CE->getType() == Type::DoubleTy)
438 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
439 else if (CE->getType() == Type::X86_FP80Ty) {
440 const uint64_t zero[] = { 0, 0};
441 APFloat apf = APFloat(APInt(80, 2, zero));
442 (void)apf.convertFromZeroExtendedInteger(GV.IntVal.getRawData(),
443 GV.IntVal.getBitWidth(), true,
444 APFloat::rmNearestTiesToEven);
445 GV.IntVal = apf.convertToAPInt();
449 case Instruction::FPToUI: // double->APInt conversion handles sign
450 case Instruction::FPToSI: {
451 GenericValue GV = getConstantValue(Op0);
452 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
453 if (Op0->getType() == Type::FloatTy)
454 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
455 else if (Op0->getType() == Type::DoubleTy)
456 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
457 else if (Op0->getType() == Type::X86_FP80Ty) {
458 APFloat apf = APFloat(GV.IntVal);
460 (void)apf.convertToInteger(&v, BitWidth,
461 CE->getOpcode()==Instruction::FPToSI,
462 APFloat::rmTowardZero);
463 GV.IntVal = v; // endian?
467 case Instruction::PtrToInt: {
468 GenericValue GV = getConstantValue(Op0);
469 uint32_t PtrWidth = TD->getPointerSizeInBits();
470 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
473 case Instruction::IntToPtr: {
474 GenericValue GV = getConstantValue(Op0);
475 uint32_t PtrWidth = TD->getPointerSizeInBits();
476 if (PtrWidth != GV.IntVal.getBitWidth())
477 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
478 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
479 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
482 case Instruction::BitCast: {
483 GenericValue GV = getConstantValue(Op0);
484 const Type* DestTy = CE->getType();
485 switch (Op0->getType()->getTypeID()) {
486 default: assert(0 && "Invalid bitcast operand");
487 case Type::IntegerTyID:
488 assert(DestTy->isFloatingPoint() && "invalid bitcast");
489 if (DestTy == Type::FloatTy)
490 GV.FloatVal = GV.IntVal.bitsToFloat();
491 else if (DestTy == Type::DoubleTy)
492 GV.DoubleVal = GV.IntVal.bitsToDouble();
494 case Type::FloatTyID:
495 assert(DestTy == Type::Int32Ty && "Invalid bitcast");
496 GV.IntVal.floatToBits(GV.FloatVal);
498 case Type::DoubleTyID:
499 assert(DestTy == Type::Int64Ty && "Invalid bitcast");
500 GV.IntVal.doubleToBits(GV.DoubleVal);
502 case Type::PointerTyID:
503 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
504 break; // getConstantValue(Op0) above already converted it
508 case Instruction::Add:
509 case Instruction::Sub:
510 case Instruction::Mul:
511 case Instruction::UDiv:
512 case Instruction::SDiv:
513 case Instruction::URem:
514 case Instruction::SRem:
515 case Instruction::And:
516 case Instruction::Or:
517 case Instruction::Xor: {
518 GenericValue LHS = getConstantValue(Op0);
519 GenericValue RHS = getConstantValue(CE->getOperand(1));
521 switch (CE->getOperand(0)->getType()->getTypeID()) {
522 default: assert(0 && "Bad add type!"); abort();
523 case Type::IntegerTyID:
524 switch (CE->getOpcode()) {
525 default: assert(0 && "Invalid integer opcode");
526 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
527 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
528 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
529 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
530 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
531 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
532 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
533 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
534 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
535 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
538 case Type::FloatTyID:
539 switch (CE->getOpcode()) {
540 default: assert(0 && "Invalid float opcode"); abort();
541 case Instruction::Add:
542 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
543 case Instruction::Sub:
544 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
545 case Instruction::Mul:
546 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
547 case Instruction::FDiv:
548 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
549 case Instruction::FRem:
550 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
553 case Type::DoubleTyID:
554 switch (CE->getOpcode()) {
555 default: assert(0 && "Invalid double opcode"); abort();
556 case Instruction::Add:
557 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
558 case Instruction::Sub:
559 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
560 case Instruction::Mul:
561 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
562 case Instruction::FDiv:
563 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
564 case Instruction::FRem:
565 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
568 case Type::X86_FP80TyID:
569 case Type::PPC_FP128TyID:
570 case Type::FP128TyID: {
571 APFloat apfLHS = APFloat(LHS.IntVal);
572 switch (CE->getOpcode()) {
573 default: assert(0 && "Invalid long double opcode"); abort();
574 case Instruction::Add:
575 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
576 GV.IntVal = apfLHS.convertToAPInt();
578 case Instruction::Sub:
579 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
580 GV.IntVal = apfLHS.convertToAPInt();
582 case Instruction::Mul:
583 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
584 GV.IntVal = apfLHS.convertToAPInt();
586 case Instruction::FDiv:
587 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
588 GV.IntVal = apfLHS.convertToAPInt();
590 case Instruction::FRem:
591 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
592 GV.IntVal = apfLHS.convertToAPInt();
603 cerr << "ConstantExpr not handled: " << *CE << "\n";
608 switch (C->getType()->getTypeID()) {
609 case Type::FloatTyID:
610 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
612 case Type::DoubleTyID:
613 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
615 case Type::X86_FP80TyID:
616 case Type::FP128TyID:
617 case Type::PPC_FP128TyID:
618 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt();
620 case Type::IntegerTyID:
621 Result.IntVal = cast<ConstantInt>(C)->getValue();
623 case Type::PointerTyID:
624 if (isa<ConstantPointerNull>(C))
625 Result.PointerVal = 0;
626 else if (const Function *F = dyn_cast<Function>(C))
627 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
628 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
629 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
631 assert(0 && "Unknown constant pointer type!");
634 cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
640 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
641 /// with the integer held in IntVal.
642 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
643 unsigned StoreBytes) {
644 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
645 uint8_t *Src = (uint8_t *)IntVal.getRawData();
647 if (sys::littleEndianHost())
648 // Little-endian host - the source is ordered from LSB to MSB. Order the
649 // destination from LSB to MSB: Do a straight copy.
650 memcpy(Dst, Src, StoreBytes);
652 // Big-endian host - the source is an array of 64 bit words ordered from
653 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
654 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
655 while (StoreBytes > sizeof(uint64_t)) {
656 StoreBytes -= sizeof(uint64_t);
657 // May not be aligned so use memcpy.
658 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
659 Src += sizeof(uint64_t);
662 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
666 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
667 /// is the address of the memory at which to store Val, cast to GenericValue *.
668 /// It is not a pointer to a GenericValue containing the address at which to
670 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
672 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
674 switch (Ty->getTypeID()) {
675 case Type::IntegerTyID:
676 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
678 case Type::FloatTyID:
679 *((float*)Ptr) = Val.FloatVal;
681 case Type::DoubleTyID:
682 *((double*)Ptr) = Val.DoubleVal;
684 case Type::X86_FP80TyID: {
685 uint16_t *Dest = (uint16_t*)Ptr;
686 const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
687 // This is endian dependent, but it will only work on x86 anyway.
695 case Type::PointerTyID:
696 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
697 if (StoreBytes != sizeof(PointerTy))
698 memset(Ptr, 0, StoreBytes);
700 *((PointerTy*)Ptr) = Val.PointerVal;
703 cerr << "Cannot store value of type " << *Ty << "!\n";
706 if (sys::littleEndianHost() != getTargetData()->isLittleEndian())
707 // Host and target are different endian - reverse the stored bytes.
708 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
711 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
712 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
713 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
714 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
715 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
717 if (sys::littleEndianHost())
718 // Little-endian host - the destination must be ordered from LSB to MSB.
719 // The source is ordered from LSB to MSB: Do a straight copy.
720 memcpy(Dst, Src, LoadBytes);
722 // Big-endian - the destination is an array of 64 bit words ordered from
723 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
724 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
726 while (LoadBytes > sizeof(uint64_t)) {
727 LoadBytes -= sizeof(uint64_t);
728 // May not be aligned so use memcpy.
729 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
730 Dst += sizeof(uint64_t);
733 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
739 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
742 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
744 if (sys::littleEndianHost() != getTargetData()->isLittleEndian()) {
745 // Host and target are different endian - reverse copy the stored
746 // bytes into a buffer, and load from that.
747 uint8_t *Src = (uint8_t*)Ptr;
748 uint8_t *Buf = (uint8_t*)alloca(LoadBytes);
749 std::reverse_copy(Src, Src + LoadBytes, Buf);
750 Ptr = (GenericValue*)Buf;
753 switch (Ty->getTypeID()) {
754 case Type::IntegerTyID:
755 // An APInt with all words initially zero.
756 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
757 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
759 case Type::FloatTyID:
760 Result.FloatVal = *((float*)Ptr);
762 case Type::DoubleTyID:
763 Result.DoubleVal = *((double*)Ptr);
765 case Type::PointerTyID:
766 Result.PointerVal = *((PointerTy*)Ptr);
768 case Type::X86_FP80TyID: {
769 // This is endian dependent, but it will only work on x86 anyway.
770 // FIXME: Will not trap if loading a signaling NaN.
771 uint16_t *p = (uint16_t*)Ptr;
781 Result.IntVal = APInt(80, 2, y);
785 cerr << "Cannot load value of type " << *Ty << "!\n";
790 // InitializeMemory - Recursive function to apply a Constant value into the
791 // specified memory location...
793 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
794 if (isa<UndefValue>(Init)) {
796 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
797 unsigned ElementSize =
798 getTargetData()->getABITypeSize(CP->getType()->getElementType());
799 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
800 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
802 } else if (isa<ConstantAggregateZero>(Init)) {
803 memset(Addr, 0, (size_t)getTargetData()->getABITypeSize(Init->getType()));
805 } else if (Init->getType()->isFirstClassType()) {
806 GenericValue Val = getConstantValue(Init);
807 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
811 switch (Init->getType()->getTypeID()) {
812 case Type::ArrayTyID: {
813 const ConstantArray *CPA = cast<ConstantArray>(Init);
814 unsigned ElementSize =
815 getTargetData()->getABITypeSize(CPA->getType()->getElementType());
816 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
817 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
821 case Type::StructTyID: {
822 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
823 const StructLayout *SL =
824 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
825 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
826 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
831 cerr << "Bad Type: " << *Init->getType() << "\n";
832 assert(0 && "Unknown constant type to initialize memory with!");
836 /// EmitGlobals - Emit all of the global variables to memory, storing their
837 /// addresses into GlobalAddress. This must make sure to copy the contents of
838 /// their initializers into the memory.
840 void ExecutionEngine::emitGlobals() {
841 const TargetData *TD = getTargetData();
843 // Loop over all of the global variables in the program, allocating the memory
844 // to hold them. If there is more than one module, do a prepass over globals
845 // to figure out how the different modules should link together.
847 std::map<std::pair<std::string, const Type*>,
848 const GlobalValue*> LinkedGlobalsMap;
850 if (Modules.size() != 1) {
851 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
852 Module &M = *Modules[m]->getModule();
853 for (Module::const_global_iterator I = M.global_begin(),
854 E = M.global_end(); I != E; ++I) {
855 const GlobalValue *GV = I;
856 if (GV->hasInternalLinkage() || GV->isDeclaration() ||
857 GV->hasAppendingLinkage() || !GV->hasName())
858 continue;// Ignore external globals and globals with internal linkage.
860 const GlobalValue *&GVEntry =
861 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
863 // If this is the first time we've seen this global, it is the canonical
870 // If the existing global is strong, never replace it.
871 if (GVEntry->hasExternalLinkage() ||
872 GVEntry->hasDLLImportLinkage() ||
873 GVEntry->hasDLLExportLinkage())
876 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
878 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
884 std::vector<const GlobalValue*> NonCanonicalGlobals;
885 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
886 Module &M = *Modules[m]->getModule();
887 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
889 // In the multi-module case, see what this global maps to.
890 if (!LinkedGlobalsMap.empty()) {
891 if (const GlobalValue *GVEntry =
892 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
893 // If something else is the canonical global, ignore this one.
894 if (GVEntry != &*I) {
895 NonCanonicalGlobals.push_back(I);
901 if (!I->isDeclaration()) {
902 // Get the type of the global.
903 const Type *Ty = I->getType()->getElementType();
905 // Allocate some memory for it!
906 unsigned Size = TD->getABITypeSize(Ty);
907 addGlobalMapping(I, new char[Size]);
909 // External variable reference. Try to use the dynamic loader to
910 // get a pointer to it.
912 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
913 addGlobalMapping(I, SymAddr);
915 cerr << "Could not resolve external global address: "
916 << I->getName() << "\n";
922 // If there are multiple modules, map the non-canonical globals to their
923 // canonical location.
924 if (!NonCanonicalGlobals.empty()) {
925 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
926 const GlobalValue *GV = NonCanonicalGlobals[i];
927 const GlobalValue *CGV =
928 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
929 void *Ptr = getPointerToGlobalIfAvailable(CGV);
930 assert(Ptr && "Canonical global wasn't codegen'd!");
931 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
935 // Now that all of the globals are set up in memory, loop through them all
936 // and initialize their contents.
937 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
939 if (!I->isDeclaration()) {
940 if (!LinkedGlobalsMap.empty()) {
941 if (const GlobalValue *GVEntry =
942 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
943 if (GVEntry != &*I) // Not the canonical variable.
946 EmitGlobalVariable(I);
952 // EmitGlobalVariable - This method emits the specified global variable to the
953 // address specified in GlobalAddresses, or allocates new memory if it's not
954 // already in the map.
955 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
956 void *GA = getPointerToGlobalIfAvailable(GV);
957 DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
959 const Type *ElTy = GV->getType()->getElementType();
960 size_t GVSize = (size_t)getTargetData()->getABITypeSize(ElTy);
962 // If it's not already specified, allocate memory for the global.
963 GA = new char[GVSize];
964 addGlobalMapping(GV, GA);
967 InitializeMemory(GV->getInitializer(), GA);
968 NumInitBytes += (unsigned)GVSize;