1 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/ExecutionEngine/ExecutionEngine.h"
22 #include "llvm/ExecutionEngine/GenericValue.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/MutexGuard.h"
25 #include "llvm/System/DynamicLibrary.h"
26 #include "llvm/Target/TargetData.h"
30 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
31 STATISTIC(NumGlobals , "Number of global vars initialized");
33 ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
34 ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
36 ExecutionEngine::ExecutionEngine(ModuleProvider *P) {
37 LazyCompilationDisabled = false;
39 assert(P && "ModuleProvider is null?");
42 ExecutionEngine::ExecutionEngine(Module *M) {
43 LazyCompilationDisabled = false;
44 assert(M && "Module is null?");
45 Modules.push_back(new ExistingModuleProvider(M));
48 ExecutionEngine::~ExecutionEngine() {
49 clearAllGlobalMappings();
50 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
54 /// FindFunctionNamed - Search all of the active modules to find the one that
55 /// defines FnName. This is very slow operation and shouldn't be used for
57 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
58 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
59 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
66 /// addGlobalMapping - Tell the execution engine that the specified global is
67 /// at the specified location. This is used internally as functions are JIT'd
68 /// and as global variables are laid out in memory. It can and should also be
69 /// used by clients of the EE that want to have an LLVM global overlay
70 /// existing data in memory.
71 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
72 MutexGuard locked(lock);
74 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
75 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
78 // If we are using the reverse mapping, add it too
79 if (!state.getGlobalAddressReverseMap(locked).empty()) {
80 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
81 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
86 /// clearAllGlobalMappings - Clear all global mappings and start over again
87 /// use in dynamic compilation scenarios when you want to move globals
88 void ExecutionEngine::clearAllGlobalMappings() {
89 MutexGuard locked(lock);
91 state.getGlobalAddressMap(locked).clear();
92 state.getGlobalAddressReverseMap(locked).clear();
95 /// updateGlobalMapping - Replace an existing mapping for GV with a new
96 /// address. This updates both maps as required. If "Addr" is null, the
97 /// entry for the global is removed from the mappings.
98 void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
99 MutexGuard locked(lock);
101 // Deleting from the mapping?
103 state.getGlobalAddressMap(locked).erase(GV);
104 if (!state.getGlobalAddressReverseMap(locked).empty())
105 state.getGlobalAddressReverseMap(locked).erase(Addr);
109 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
110 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
111 state.getGlobalAddressReverseMap(locked).erase(CurVal);
114 // If we are using the reverse mapping, add it too
115 if (!state.getGlobalAddressReverseMap(locked).empty()) {
116 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
117 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
122 /// getPointerToGlobalIfAvailable - This returns the address of the specified
123 /// global value if it is has already been codegen'd, otherwise it returns null.
125 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
126 MutexGuard locked(lock);
128 std::map<const GlobalValue*, void*>::iterator I =
129 state.getGlobalAddressMap(locked).find(GV);
130 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
133 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
134 /// at the specified address.
136 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
137 MutexGuard locked(lock);
139 // If we haven't computed the reverse mapping yet, do so first.
140 if (state.getGlobalAddressReverseMap(locked).empty()) {
141 for (std::map<const GlobalValue*, void *>::iterator
142 I = state.getGlobalAddressMap(locked).begin(),
143 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
144 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
148 std::map<void *, const GlobalValue*>::iterator I =
149 state.getGlobalAddressReverseMap(locked).find(Addr);
150 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
153 // CreateArgv - Turn a vector of strings into a nice argv style array of
154 // pointers to null terminated strings.
156 static void *CreateArgv(ExecutionEngine *EE,
157 const std::vector<std::string> &InputArgv) {
158 unsigned PtrSize = EE->getTargetData()->getPointerSize();
159 char *Result = new char[(InputArgv.size()+1)*PtrSize];
161 DOUT << "ARGV = " << (void*)Result << "\n";
162 const Type *SBytePtr = PointerType::get(Type::Int8Ty);
164 for (unsigned i = 0; i != InputArgv.size(); ++i) {
165 unsigned Size = InputArgv[i].size()+1;
166 char *Dest = new char[Size];
167 DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
169 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
172 // Endian safe: Result[i] = (PointerTy)Dest;
173 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
178 EE->StoreValueToMemory(PTOGV(0),
179 (GenericValue*)(Result+InputArgv.size()*PtrSize),
185 /// runStaticConstructorsDestructors - This method is used to execute all of
186 /// the static constructors or destructors for a program, depending on the
187 /// value of isDtors.
188 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
189 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
191 // Execute global ctors/dtors for each module in the program.
192 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
193 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
195 // If this global has internal linkage, or if it has a use, then it must be
196 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
197 // this is the case, don't execute any of the global ctors, __main will do
199 if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
201 // Should be an array of '{ int, void ()* }' structs. The first value is
202 // the init priority, which we ignore.
203 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
204 if (!InitList) continue;
205 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
206 if (ConstantStruct *CS =
207 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
208 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
210 Constant *FP = CS->getOperand(1);
211 if (FP->isNullValue())
212 break; // Found a null terminator, exit.
214 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
216 FP = CE->getOperand(0);
217 if (Function *F = dyn_cast<Function>(FP)) {
218 // Execute the ctor/dtor function!
219 runFunction(F, std::vector<GenericValue>());
225 /// runFunctionAsMain - This is a helper function which wraps runFunction to
226 /// handle the common task of starting up main with the specified argc, argv,
227 /// and envp parameters.
228 int ExecutionEngine::runFunctionAsMain(Function *Fn,
229 const std::vector<std::string> &argv,
230 const char * const * envp) {
231 std::vector<GenericValue> GVArgs;
233 GVArgc.IntVal = APInt(32, argv.size());
236 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
237 const FunctionType *FTy = Fn->getFunctionType();
238 const Type* PPInt8Ty = PointerType::get(PointerType::get(Type::Int8Ty));
241 if (FTy->getParamType(2) != PPInt8Ty) {
242 cerr << "Invalid type for third argument of main() supplied\n";
247 if (FTy->getParamType(1) != PPInt8Ty) {
248 cerr << "Invalid type for second argument of main() supplied\n";
253 if (FTy->getParamType(0) != Type::Int32Ty) {
254 cerr << "Invalid type for first argument of main() supplied\n";
259 if (FTy->getReturnType() != Type::Int32Ty &&
260 FTy->getReturnType() != Type::VoidTy) {
261 cerr << "Invalid return type of main() supplied\n";
266 cerr << "Invalid number of arguments of main() supplied\n";
271 GVArgs.push_back(GVArgc); // Arg #0 = argc.
273 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
274 assert(((char **)GVTOP(GVArgs[1]))[0] &&
275 "argv[0] was null after CreateArgv");
277 std::vector<std::string> EnvVars;
278 for (unsigned i = 0; envp[i]; ++i)
279 EnvVars.push_back(envp[i]);
280 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
284 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
287 /// If possible, create a JIT, unless the caller specifically requests an
288 /// Interpreter or there's an error. If even an Interpreter cannot be created,
289 /// NULL is returned.
291 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
292 bool ForceInterpreter,
293 std::string *ErrorStr) {
294 ExecutionEngine *EE = 0;
296 // Unless the interpreter was explicitly selected, try making a JIT.
297 if (!ForceInterpreter && JITCtor)
298 EE = JITCtor(MP, ErrorStr);
300 // If we can't make a JIT, make an interpreter instead.
301 if (EE == 0 && InterpCtor)
302 EE = InterpCtor(MP, ErrorStr);
305 // Make sure we can resolve symbols in the program as well. The zero arg
306 // to the function tells DynamicLibrary to load the program, not a library.
308 sys::DynamicLibrary::LoadLibraryPermanently(0);
316 /// getPointerToGlobal - This returns the address of the specified global
317 /// value. This may involve code generation if it's a function.
319 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
320 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
321 return getPointerToFunction(F);
323 MutexGuard locked(lock);
324 void *p = state.getGlobalAddressMap(locked)[GV];
328 // Global variable might have been added since interpreter started.
329 if (GlobalVariable *GVar =
330 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
331 EmitGlobalVariable(GVar);
333 assert(0 && "Global hasn't had an address allocated yet!");
334 return state.getGlobalAddressMap(locked)[GV];
337 /// This function converts a Constant* into a GenericValue. The interesting
338 /// part is if C is a ConstantExpr.
339 /// @brief Get a GenericValue for a Constant*
340 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
341 // If its undefined, return the garbage.
342 if (isa<UndefValue>(C))
343 return GenericValue();
345 // If the value is a ConstantExpr
346 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
347 Constant *Op0 = CE->getOperand(0);
348 switch (CE->getOpcode()) {
349 case Instruction::GetElementPtr: {
351 GenericValue Result = getConstantValue(Op0);
352 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
354 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
356 char* tmp = (char*) Result.PointerVal;
357 Result = PTOGV(tmp + Offset);
360 case Instruction::Trunc: {
361 GenericValue GV = getConstantValue(Op0);
362 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
363 GV.IntVal = GV.IntVal.trunc(BitWidth);
366 case Instruction::ZExt: {
367 GenericValue GV = getConstantValue(Op0);
368 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
369 GV.IntVal = GV.IntVal.zext(BitWidth);
372 case Instruction::SExt: {
373 GenericValue GV = getConstantValue(Op0);
374 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
375 GV.IntVal = GV.IntVal.sext(BitWidth);
378 case Instruction::FPTrunc: {
380 GenericValue GV = getConstantValue(Op0);
381 GV.FloatVal = float(GV.DoubleVal);
384 case Instruction::FPExt:{
386 GenericValue GV = getConstantValue(Op0);
387 GV.DoubleVal = double(GV.FloatVal);
390 case Instruction::UIToFP: {
391 GenericValue GV = getConstantValue(Op0);
392 if (CE->getType() == Type::FloatTy)
393 GV.FloatVal = float(GV.IntVal.roundToDouble());
394 else if (CE->getType() == Type::DoubleTy)
395 GV.DoubleVal = GV.IntVal.roundToDouble();
396 else if (CE->getType() == Type::X86_FP80Ty) {
397 const uint64_t zero[] = {0, 0};
398 APFloat apf = APFloat(APInt(80, 2, zero));
399 (void)apf.convertFromInteger(GV.IntVal.getRawData(), 2, false,
400 APFloat::rmTowardZero);
401 GV.IntVal = apf.convertToAPInt();
405 case Instruction::SIToFP: {
406 GenericValue GV = getConstantValue(Op0);
407 if (CE->getType() == Type::FloatTy)
408 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
409 else if (CE->getType() == Type::DoubleTy)
410 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
411 else if (CE->getType() == Type::X86_FP80Ty) {
412 const uint64_t zero[] = { 0, 0};
413 APFloat apf = APFloat(APInt(80, 2, zero));
414 (void)apf.convertFromInteger(GV.IntVal.getRawData(), 2, true,
415 APFloat::rmTowardZero);
416 GV.IntVal = apf.convertToAPInt();
420 case Instruction::FPToUI: // double->APInt conversion handles sign
421 case Instruction::FPToSI: {
422 GenericValue GV = getConstantValue(Op0);
423 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
424 if (Op0->getType() == Type::FloatTy)
425 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
426 else if (Op0->getType() == Type::DoubleTy)
427 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
428 else if (Op0->getType() == Type::X86_FP80Ty) {
429 APFloat apf = APFloat(GV.IntVal);
431 (void)apf.convertToInteger(&v, BitWidth,
432 CE->getOpcode()==Instruction::FPToSI,
433 APFloat::rmTowardZero);
434 GV.IntVal = v; // endian?
438 case Instruction::PtrToInt: {
439 GenericValue GV = getConstantValue(Op0);
440 uint32_t PtrWidth = TD->getPointerSizeInBits();
441 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
444 case Instruction::IntToPtr: {
445 GenericValue GV = getConstantValue(Op0);
446 uint32_t PtrWidth = TD->getPointerSizeInBits();
447 if (PtrWidth != GV.IntVal.getBitWidth())
448 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
449 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
450 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
453 case Instruction::BitCast: {
454 GenericValue GV = getConstantValue(Op0);
455 const Type* DestTy = CE->getType();
456 switch (Op0->getType()->getTypeID()) {
457 default: assert(0 && "Invalid bitcast operand");
458 case Type::IntegerTyID:
459 assert(DestTy->isFloatingPoint() && "invalid bitcast");
460 if (DestTy == Type::FloatTy)
461 GV.FloatVal = GV.IntVal.bitsToFloat();
462 else if (DestTy == Type::DoubleTy)
463 GV.DoubleVal = GV.IntVal.bitsToDouble();
465 case Type::FloatTyID:
466 assert(DestTy == Type::Int32Ty && "Invalid bitcast");
467 GV.IntVal.floatToBits(GV.FloatVal);
469 case Type::DoubleTyID:
470 assert(DestTy == Type::Int64Ty && "Invalid bitcast");
471 GV.IntVal.doubleToBits(GV.DoubleVal);
473 case Type::PointerTyID:
474 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
475 break; // getConstantValue(Op0) above already converted it
479 case Instruction::Add:
480 case Instruction::Sub:
481 case Instruction::Mul:
482 case Instruction::UDiv:
483 case Instruction::SDiv:
484 case Instruction::URem:
485 case Instruction::SRem:
486 case Instruction::And:
487 case Instruction::Or:
488 case Instruction::Xor: {
489 GenericValue LHS = getConstantValue(Op0);
490 GenericValue RHS = getConstantValue(CE->getOperand(1));
492 switch (CE->getOperand(0)->getType()->getTypeID()) {
493 default: assert(0 && "Bad add type!"); abort();
494 case Type::IntegerTyID:
495 switch (CE->getOpcode()) {
496 default: assert(0 && "Invalid integer opcode");
497 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
498 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
499 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
500 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
501 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
502 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
503 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
504 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
505 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
506 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
509 case Type::FloatTyID:
510 switch (CE->getOpcode()) {
511 default: assert(0 && "Invalid float opcode"); abort();
512 case Instruction::Add:
513 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
514 case Instruction::Sub:
515 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
516 case Instruction::Mul:
517 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
518 case Instruction::FDiv:
519 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
520 case Instruction::FRem:
521 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
524 case Type::DoubleTyID:
525 switch (CE->getOpcode()) {
526 default: assert(0 && "Invalid double opcode"); abort();
527 case Instruction::Add:
528 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
529 case Instruction::Sub:
530 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
531 case Instruction::Mul:
532 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
533 case Instruction::FDiv:
534 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
535 case Instruction::FRem:
536 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
539 case Type::X86_FP80TyID:
540 case Type::PPC_FP128TyID:
541 case Type::FP128TyID: {
542 APFloat apfLHS = APFloat(LHS.IntVal);
543 switch (CE->getOpcode()) {
544 default: assert(0 && "Invalid long double opcode"); abort();
545 case Instruction::Add:
546 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
547 GV.IntVal = apfLHS.convertToAPInt();
549 case Instruction::Sub:
550 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
551 GV.IntVal = apfLHS.convertToAPInt();
553 case Instruction::Mul:
554 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
555 GV.IntVal = apfLHS.convertToAPInt();
557 case Instruction::FDiv:
558 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
559 GV.IntVal = apfLHS.convertToAPInt();
561 case Instruction::FRem:
562 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
563 GV.IntVal = apfLHS.convertToAPInt();
574 cerr << "ConstantExpr not handled: " << *CE << "\n";
579 switch (C->getType()->getTypeID()) {
580 case Type::FloatTyID:
581 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
583 case Type::DoubleTyID:
584 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
586 case Type::X86_FP80TyID:
587 case Type::FP128TyID:
588 case Type::PPC_FP128TyID:
589 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt();
591 case Type::IntegerTyID:
592 Result.IntVal = cast<ConstantInt>(C)->getValue();
594 case Type::PointerTyID:
595 if (isa<ConstantPointerNull>(C))
596 Result.PointerVal = 0;
597 else if (const Function *F = dyn_cast<Function>(C))
598 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
599 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
600 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
602 assert(0 && "Unknown constant pointer type!");
605 cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
611 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
612 /// is the address of the memory at which to store Val, cast to GenericValue *.
613 /// It is not a pointer to a GenericValue containing the address at which to
616 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
618 switch (Ty->getTypeID()) {
619 case Type::IntegerTyID: {
620 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
621 GenericValue TmpVal = Val;
623 *((uint8_t*)Ptr) = uint8_t(Val.IntVal.getZExtValue());
624 else if (BitWidth <= 16) {
625 *((uint16_t*)Ptr) = uint16_t(Val.IntVal.getZExtValue());
626 } else if (BitWidth <= 32) {
627 *((uint32_t*)Ptr) = uint32_t(Val.IntVal.getZExtValue());
628 } else if (BitWidth <= 64) {
629 *((uint64_t*)Ptr) = uint64_t(Val.IntVal.getZExtValue());
631 uint64_t *Dest = (uint64_t*)Ptr;
632 const uint64_t *Src = Val.IntVal.getRawData();
633 for (uint32_t i = 0; i < Val.IntVal.getNumWords(); ++i)
638 case Type::FloatTyID:
639 *((float*)Ptr) = Val.FloatVal;
641 case Type::DoubleTyID:
642 *((double*)Ptr) = Val.DoubleVal;
644 case Type::X86_FP80TyID: {
645 uint16_t *Dest = (uint16_t*)Ptr;
646 const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
647 // This is endian dependent, but it will only work on x86 anyway.
655 case Type::PointerTyID:
656 *((PointerTy*)Ptr) = Val.PointerVal;
659 cerr << "Cannot store value of type " << *Ty << "!\n";
665 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
668 switch (Ty->getTypeID()) {
669 case Type::IntegerTyID: {
670 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
672 Result.IntVal = APInt(BitWidth, *((uint8_t*)Ptr));
673 else if (BitWidth <= 16) {
674 Result.IntVal = APInt(BitWidth, *((uint16_t*)Ptr));
675 } else if (BitWidth <= 32) {
676 Result.IntVal = APInt(BitWidth, *((uint32_t*)Ptr));
677 } else if (BitWidth <= 64) {
678 Result.IntVal = APInt(BitWidth, *((uint64_t*)Ptr));
680 Result.IntVal = APInt(BitWidth, (BitWidth+63)/64, (uint64_t*)Ptr);
683 case Type::FloatTyID:
684 Result.FloatVal = *((float*)Ptr);
686 case Type::DoubleTyID:
687 Result.DoubleVal = *((double*)Ptr);
689 case Type::PointerTyID:
690 Result.PointerVal = *((PointerTy*)Ptr);
692 case Type::X86_FP80TyID: {
693 // This is endian dependent, but it will only work on x86 anyway.
694 uint16_t x[8], *p = (uint16_t*)Ptr;
700 Result.IntVal = APInt(80, 2, x);
704 cerr << "Cannot load value of type " << *Ty << "!\n";
709 // InitializeMemory - Recursive function to apply a Constant value into the
710 // specified memory location...
712 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
713 if (isa<UndefValue>(Init)) {
715 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
716 unsigned ElementSize =
717 getTargetData()->getTypeSize(CP->getType()->getElementType());
718 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
719 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
721 } else if (Init->getType()->isFirstClassType()) {
722 GenericValue Val = getConstantValue(Init);
723 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
725 } else if (isa<ConstantAggregateZero>(Init)) {
726 memset(Addr, 0, (size_t)getTargetData()->getTypeSize(Init->getType()));
730 switch (Init->getType()->getTypeID()) {
731 case Type::ArrayTyID: {
732 const ConstantArray *CPA = cast<ConstantArray>(Init);
733 unsigned ElementSize =
734 getTargetData()->getTypeSize(CPA->getType()->getElementType());
735 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
736 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
740 case Type::StructTyID: {
741 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
742 const StructLayout *SL =
743 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
744 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
745 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
750 cerr << "Bad Type: " << *Init->getType() << "\n";
751 assert(0 && "Unknown constant type to initialize memory with!");
755 /// EmitGlobals - Emit all of the global variables to memory, storing their
756 /// addresses into GlobalAddress. This must make sure to copy the contents of
757 /// their initializers into the memory.
759 void ExecutionEngine::emitGlobals() {
760 const TargetData *TD = getTargetData();
762 // Loop over all of the global variables in the program, allocating the memory
763 // to hold them. If there is more than one module, do a prepass over globals
764 // to figure out how the different modules should link together.
766 std::map<std::pair<std::string, const Type*>,
767 const GlobalValue*> LinkedGlobalsMap;
769 if (Modules.size() != 1) {
770 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
771 Module &M = *Modules[m]->getModule();
772 for (Module::const_global_iterator I = M.global_begin(),
773 E = M.global_end(); I != E; ++I) {
774 const GlobalValue *GV = I;
775 if (GV->hasInternalLinkage() || GV->isDeclaration() ||
776 GV->hasAppendingLinkage() || !GV->hasName())
777 continue;// Ignore external globals and globals with internal linkage.
779 const GlobalValue *&GVEntry =
780 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
782 // If this is the first time we've seen this global, it is the canonical
789 // If the existing global is strong, never replace it.
790 if (GVEntry->hasExternalLinkage() ||
791 GVEntry->hasDLLImportLinkage() ||
792 GVEntry->hasDLLExportLinkage())
795 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
797 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
803 std::vector<const GlobalValue*> NonCanonicalGlobals;
804 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
805 Module &M = *Modules[m]->getModule();
806 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
808 // In the multi-module case, see what this global maps to.
809 if (!LinkedGlobalsMap.empty()) {
810 if (const GlobalValue *GVEntry =
811 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
812 // If something else is the canonical global, ignore this one.
813 if (GVEntry != &*I) {
814 NonCanonicalGlobals.push_back(I);
820 if (!I->isDeclaration()) {
821 // Get the type of the global.
822 const Type *Ty = I->getType()->getElementType();
824 // Allocate some memory for it!
825 unsigned Size = TD->getTypeSize(Ty);
826 addGlobalMapping(I, new char[Size]);
828 // External variable reference. Try to use the dynamic loader to
829 // get a pointer to it.
831 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
832 addGlobalMapping(I, SymAddr);
834 cerr << "Could not resolve external global address: "
835 << I->getName() << "\n";
841 // If there are multiple modules, map the non-canonical globals to their
842 // canonical location.
843 if (!NonCanonicalGlobals.empty()) {
844 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
845 const GlobalValue *GV = NonCanonicalGlobals[i];
846 const GlobalValue *CGV =
847 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
848 void *Ptr = getPointerToGlobalIfAvailable(CGV);
849 assert(Ptr && "Canonical global wasn't codegen'd!");
850 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
854 // Now that all of the globals are set up in memory, loop through them all
855 // and initialize their contents.
856 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
858 if (!I->isDeclaration()) {
859 if (!LinkedGlobalsMap.empty()) {
860 if (const GlobalValue *GVEntry =
861 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
862 if (GVEntry != &*I) // Not the canonical variable.
865 EmitGlobalVariable(I);
871 // EmitGlobalVariable - This method emits the specified global variable to the
872 // address specified in GlobalAddresses, or allocates new memory if it's not
873 // already in the map.
874 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
875 void *GA = getPointerToGlobalIfAvailable(GV);
876 DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
878 const Type *ElTy = GV->getType()->getElementType();
879 size_t GVSize = (size_t)getTargetData()->getTypeSize(ElTy);
881 // If it's not already specified, allocate memory for the global.
882 GA = new char[GVSize];
883 addGlobalMapping(GV, GA);
886 InitializeMemory(GV->getInitializer(), GA);
887 NumInitBytes += (unsigned)GVSize;