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"
29 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
30 STATISTIC(NumGlobals , "Number of global vars initialized");
32 ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
33 ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
35 ExecutionEngine::ExecutionEngine(ModuleProvider *P) {
36 LazyCompilationDisabled = false;
38 assert(P && "ModuleProvider is null?");
41 ExecutionEngine::ExecutionEngine(Module *M) {
42 LazyCompilationDisabled = false;
43 assert(M && "Module is null?");
44 Modules.push_back(new ExistingModuleProvider(M));
47 ExecutionEngine::~ExecutionEngine() {
48 clearAllGlobalMappings();
49 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
53 /// FindFunctionNamed - Search all of the active modules to find the one that
54 /// defines FnName. This is very slow operation and shouldn't be used for
56 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
57 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
58 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
65 /// addGlobalMapping - Tell the execution engine that the specified global is
66 /// at the specified location. This is used internally as functions are JIT'd
67 /// and as global variables are laid out in memory. It can and should also be
68 /// used by clients of the EE that want to have an LLVM global overlay
69 /// existing data in memory.
70 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
71 MutexGuard locked(lock);
73 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
74 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
77 // If we are using the reverse mapping, add it too
78 if (!state.getGlobalAddressReverseMap(locked).empty()) {
79 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
80 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
85 /// clearAllGlobalMappings - Clear all global mappings and start over again
86 /// use in dynamic compilation scenarios when you want to move globals
87 void ExecutionEngine::clearAllGlobalMappings() {
88 MutexGuard locked(lock);
90 state.getGlobalAddressMap(locked).clear();
91 state.getGlobalAddressReverseMap(locked).clear();
94 /// updateGlobalMapping - Replace an existing mapping for GV with a new
95 /// address. This updates both maps as required. If "Addr" is null, the
96 /// entry for the global is removed from the mappings.
97 void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
98 MutexGuard locked(lock);
100 // Deleting from the mapping?
102 state.getGlobalAddressMap(locked).erase(GV);
103 if (!state.getGlobalAddressReverseMap(locked).empty())
104 state.getGlobalAddressReverseMap(locked).erase(Addr);
108 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
109 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
110 state.getGlobalAddressReverseMap(locked).erase(CurVal);
113 // If we are using the reverse mapping, add it too
114 if (!state.getGlobalAddressReverseMap(locked).empty()) {
115 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
116 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
121 /// getPointerToGlobalIfAvailable - This returns the address of the specified
122 /// global value if it is has already been codegen'd, otherwise it returns null.
124 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
125 MutexGuard locked(lock);
127 std::map<const GlobalValue*, void*>::iterator I =
128 state.getGlobalAddressMap(locked).find(GV);
129 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
132 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
133 /// at the specified address.
135 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
136 MutexGuard locked(lock);
138 // If we haven't computed the reverse mapping yet, do so first.
139 if (state.getGlobalAddressReverseMap(locked).empty()) {
140 for (std::map<const GlobalValue*, void *>::iterator
141 I = state.getGlobalAddressMap(locked).begin(),
142 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
143 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
147 std::map<void *, const GlobalValue*>::iterator I =
148 state.getGlobalAddressReverseMap(locked).find(Addr);
149 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
152 // CreateArgv - Turn a vector of strings into a nice argv style array of
153 // pointers to null terminated strings.
155 static void *CreateArgv(ExecutionEngine *EE,
156 const std::vector<std::string> &InputArgv) {
157 unsigned PtrSize = EE->getTargetData()->getPointerSize();
158 char *Result = new char[(InputArgv.size()+1)*PtrSize];
160 DOUT << "ARGV = " << (void*)Result << "\n";
161 const Type *SBytePtr = PointerType::get(Type::Int8Ty);
163 for (unsigned i = 0; i != InputArgv.size(); ++i) {
164 unsigned Size = InputArgv[i].size()+1;
165 char *Dest = new char[Size];
166 DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
168 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
171 // Endian safe: Result[i] = (PointerTy)Dest;
172 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
177 EE->StoreValueToMemory(PTOGV(0),
178 (GenericValue*)(Result+InputArgv.size()*PtrSize),
184 /// runStaticConstructorsDestructors - This method is used to execute all of
185 /// the static constructors or destructors for a program, depending on the
186 /// value of isDtors.
187 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
188 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
190 // Execute global ctors/dtors for each module in the program.
191 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
192 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
194 // If this global has internal linkage, or if it has a use, then it must be
195 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
196 // this is the case, don't execute any of the global ctors, __main will do
198 if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
200 // Should be an array of '{ int, void ()* }' structs. The first value is
201 // the init priority, which we ignore.
202 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
203 if (!InitList) continue;
204 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
205 if (ConstantStruct *CS =
206 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
207 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
209 Constant *FP = CS->getOperand(1);
210 if (FP->isNullValue())
211 break; // Found a null terminator, exit.
213 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
215 FP = CE->getOperand(0);
216 if (Function *F = dyn_cast<Function>(FP)) {
217 // Execute the ctor/dtor function!
218 runFunction(F, std::vector<GenericValue>());
224 /// runFunctionAsMain - This is a helper function which wraps runFunction to
225 /// handle the common task of starting up main with the specified argc, argv,
226 /// and envp parameters.
227 int ExecutionEngine::runFunctionAsMain(Function *Fn,
228 const std::vector<std::string> &argv,
229 const char * const * envp) {
230 std::vector<GenericValue> GVArgs;
232 GVArgc.Int32Val = argv.size();
233 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
235 GVArgs.push_back(GVArgc); // Arg #0 = argc.
237 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
238 assert(((char **)GVTOP(GVArgs[1]))[0] &&
239 "argv[0] was null after CreateArgv");
241 std::vector<std::string> EnvVars;
242 for (unsigned i = 0; envp[i]; ++i)
243 EnvVars.push_back(envp[i]);
244 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
248 return runFunction(Fn, GVArgs).Int32Val;
251 /// If possible, create a JIT, unless the caller specifically requests an
252 /// Interpreter or there's an error. If even an Interpreter cannot be created,
253 /// NULL is returned.
255 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
256 bool ForceInterpreter,
257 std::string *ErrorStr) {
258 ExecutionEngine *EE = 0;
260 // Unless the interpreter was explicitly selected, try making a JIT.
261 if (!ForceInterpreter && JITCtor)
262 EE = JITCtor(MP, ErrorStr);
264 // If we can't make a JIT, make an interpreter instead.
265 if (EE == 0 && InterpCtor)
266 EE = InterpCtor(MP, ErrorStr);
269 // Make sure we can resolve symbols in the program as well. The zero arg
270 // to the function tells DynamicLibrary to load the program, not a library.
272 sys::DynamicLibrary::LoadLibraryPermanently(0);
280 /// getPointerToGlobal - This returns the address of the specified global
281 /// value. This may involve code generation if it's a function.
283 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
284 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
285 return getPointerToFunction(F);
287 MutexGuard locked(lock);
288 void *p = state.getGlobalAddressMap(locked)[GV];
292 // Global variable might have been added since interpreter started.
293 if (GlobalVariable *GVar =
294 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
295 EmitGlobalVariable(GVar);
297 assert(0 && "Global hasn't had an address allocated yet!");
298 return state.getGlobalAddressMap(locked)[GV];
301 /// This macro is used to handle a variety of situations involing integer
302 /// values where the action should be done to one of the GenericValue members.
303 /// THEINTTY is a const Type * for the integer type. ACTION1 comes before
304 /// the GenericValue, ACTION2 comes after.
305 #define DO_FOR_INTEGER(THEINTTY, ACTION) \
307 unsigned BitWidth = cast<IntegerType>(THEINTTY)->getBitWidth(); \
308 if (BitWidth == 1) {\
310 } else if (BitWidth <= 8) {\
312 } else if (BitWidth <= 16) {\
314 } else if (BitWidth <= 32) { \
316 } else if (BitWidth <= 64) { \
319 assert(0 && "Not implemented: integer types > 64 bits"); \
323 /// This function converts a Constant* into a GenericValue. The interesting
324 /// part is if C is a ConstantExpr.
325 /// @brief Get a GenericValue for a Constnat*
326 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
327 // Declare the result as garbage.
330 // If its undefined, return the garbage.
331 if (isa<UndefValue>(C)) return Result;
333 // If the value is a ConstantExpr
334 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
335 switch (CE->getOpcode()) {
336 case Instruction::GetElementPtr: {
338 Result = getConstantValue(CE->getOperand(0));
339 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
341 TD->getIndexedOffset(CE->getOperand(0)->getType(),
342 &Indices[0], Indices.size());
344 if (getTargetData()->getPointerSize() == 4)
345 Result.Int32Val += Offset;
347 Result.Int64Val += Offset;
350 case Instruction::Trunc:
351 case Instruction::ZExt:
352 case Instruction::SExt:
353 case Instruction::FPTrunc:
354 case Instruction::FPExt:
355 case Instruction::UIToFP:
356 case Instruction::SIToFP:
357 case Instruction::FPToUI:
358 case Instruction::FPToSI:
360 case Instruction::PtrToInt: {
361 Constant *Op = CE->getOperand(0);
362 GenericValue GV = getConstantValue(Op);
365 case Instruction::BitCast: {
366 // Bit casts are no-ops but we can only return the GV of the operand if
367 // they are the same basic type (pointer->pointer, packed->packed, etc.)
368 Constant *Op = CE->getOperand(0);
369 GenericValue GV = getConstantValue(Op);
370 if (Op->getType()->getTypeID() == C->getType()->getTypeID())
374 case Instruction::IntToPtr: {
375 // IntToPtr casts are just so special. Cast to intptr_t first.
376 Constant *Op = CE->getOperand(0);
377 GenericValue GV = getConstantValue(Op);
378 #define INT_TO_PTR_ACTION(FIELD) \
379 return PTOGV((void*)(uintptr_t)GV.FIELD)
380 DO_FOR_INTEGER(Op->getType(), INT_TO_PTR_ACTION)
381 #undef INT_TO_PTR_ACTION
384 case Instruction::Add:
385 switch (CE->getOperand(0)->getType()->getTypeID()) {
386 default: assert(0 && "Bad add type!"); abort();
387 case Type::IntegerTyID:
388 #define ADD_ACTION(FIELD) \
389 Result.FIELD = getConstantValue(CE->getOperand(0)).FIELD + \
390 getConstantValue(CE->getOperand(1)).FIELD;
391 DO_FOR_INTEGER(CE->getOperand(0)->getType(),ADD_ACTION);
394 case Type::FloatTyID:
395 Result.FloatVal = getConstantValue(CE->getOperand(0)).FloatVal +
396 getConstantValue(CE->getOperand(1)).FloatVal;
398 case Type::DoubleTyID:
399 Result.DoubleVal = getConstantValue(CE->getOperand(0)).DoubleVal +
400 getConstantValue(CE->getOperand(1)).DoubleVal;
407 cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
411 switch (C->getType()->getTypeID()) {
412 #define GET_CONST_VAL(TY, CTY, CLASS, GETMETH) \
413 case Type::TY##TyID: Result.TY##Val = (CTY)cast<CLASS>(C)->GETMETH(); break
414 GET_CONST_VAL(Float , float , ConstantFP, getValue);
415 GET_CONST_VAL(Double, double , ConstantFP, getValue);
417 case Type::IntegerTyID: {
418 unsigned BitWidth = cast<IntegerType>(C->getType())->getBitWidth();
420 Result.Int1Val = (bool)cast<ConstantInt>(C)->getZExtValue();
421 else if (BitWidth <= 8)
422 Result.Int8Val = (uint8_t )cast<ConstantInt>(C)->getZExtValue();
423 else if (BitWidth <= 16)
424 Result.Int16Val = (uint16_t )cast<ConstantInt>(C)->getZExtValue();
425 else if (BitWidth <= 32)
426 Result.Int32Val = (uint32_t )cast<ConstantInt>(C)->getZExtValue();
427 else if (BitWidth <= 64)
428 Result.Int64Val = (uint64_t )cast<ConstantInt>(C)->getZExtValue();
430 Result.APIntVal = const_cast<APInt*>(&cast<ConstantInt>(C)->getValue());
434 case Type::PointerTyID:
435 if (isa<ConstantPointerNull>(C))
436 Result.PointerVal = 0;
437 else if (const Function *F = dyn_cast<Function>(C))
438 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
439 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
440 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
442 assert(0 && "Unknown constant pointer type!");
445 cerr << "ERROR: Constant unimp for type: " << *C->getType() << "\n";
451 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
452 /// is the address of the memory at which to store Val, cast to GenericValue *.
453 /// It is not a pointer to a GenericValue containing the address at which to
456 void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
458 if (getTargetData()->isLittleEndian()) {
459 switch (Ty->getTypeID()) {
460 case Type::IntegerTyID: {
461 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
462 uint64_t BitMask = cast<IntegerType>(Ty)->getBitMask();
463 GenericValue TmpVal = Val;
465 Ptr->Untyped[0] = Val.Int8Val & BitMask;
466 else if (BitWidth <= 16) {
467 TmpVal.Int16Val &= BitMask;
468 Ptr->Untyped[0] = TmpVal.Int16Val & 255;
469 Ptr->Untyped[1] = (TmpVal.Int16Val >> 8) & 255;
470 } else if (BitWidth <= 32) {
471 TmpVal.Int32Val &= BitMask;
472 Ptr->Untyped[0] = TmpVal.Int32Val & 255;
473 Ptr->Untyped[1] = (TmpVal.Int32Val >> 8) & 255;
474 Ptr->Untyped[2] = (TmpVal.Int32Val >> 16) & 255;
475 Ptr->Untyped[3] = (TmpVal.Int32Val >> 24) & 255;
476 } else if (BitWidth <= 64) {
477 TmpVal.Int64Val &= BitMask;
478 Ptr->Untyped[0] = (unsigned char)(TmpVal.Int64Val );
479 Ptr->Untyped[1] = (unsigned char)(TmpVal.Int64Val >> 8);
480 Ptr->Untyped[2] = (unsigned char)(TmpVal.Int64Val >> 16);
481 Ptr->Untyped[3] = (unsigned char)(TmpVal.Int64Val >> 24);
482 Ptr->Untyped[4] = (unsigned char)(TmpVal.Int64Val >> 32);
483 Ptr->Untyped[5] = (unsigned char)(TmpVal.Int64Val >> 40);
484 Ptr->Untyped[6] = (unsigned char)(TmpVal.Int64Val >> 48);
485 Ptr->Untyped[7] = (unsigned char)(TmpVal.Int64Val >> 56);
487 uint64_t *Dest = (uint64_t*)Ptr;
488 const uint64_t *Src = Val.APIntVal->getRawData();
489 for (uint32_t i = 0; i < Val.APIntVal->getNumWords(); ++i)
494 Store4BytesLittleEndian:
495 case Type::FloatTyID:
496 Ptr->Untyped[0] = Val.Int32Val & 255;
497 Ptr->Untyped[1] = (Val.Int32Val >> 8) & 255;
498 Ptr->Untyped[2] = (Val.Int32Val >> 16) & 255;
499 Ptr->Untyped[3] = (Val.Int32Val >> 24) & 255;
501 case Type::PointerTyID:
502 if (getTargetData()->getPointerSize() == 4)
503 goto Store4BytesLittleEndian;
505 case Type::DoubleTyID:
506 Ptr->Untyped[0] = (unsigned char)(Val.Int64Val );
507 Ptr->Untyped[1] = (unsigned char)(Val.Int64Val >> 8);
508 Ptr->Untyped[2] = (unsigned char)(Val.Int64Val >> 16);
509 Ptr->Untyped[3] = (unsigned char)(Val.Int64Val >> 24);
510 Ptr->Untyped[4] = (unsigned char)(Val.Int64Val >> 32);
511 Ptr->Untyped[5] = (unsigned char)(Val.Int64Val >> 40);
512 Ptr->Untyped[6] = (unsigned char)(Val.Int64Val >> 48);
513 Ptr->Untyped[7] = (unsigned char)(Val.Int64Val >> 56);
516 cerr << "Cannot store value of type " << *Ty << "!\n";
519 switch (Ty->getTypeID()) {
520 case Type::IntegerTyID: {
521 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
522 uint64_t BitMask = cast<IntegerType>(Ty)->getBitMask();
523 GenericValue TmpVal = Val;
525 Ptr->Untyped[0] = Val.Int8Val & BitMask;
526 else if (BitWidth <= 16) {
527 TmpVal.Int16Val &= BitMask;
528 Ptr->Untyped[1] = TmpVal.Int16Val & 255;
529 Ptr->Untyped[0] = (TmpVal.Int16Val >> 8) & 255;
530 } else if (BitWidth <= 32) {
531 TmpVal.Int32Val &= BitMask;
532 Ptr->Untyped[3] = TmpVal.Int32Val & 255;
533 Ptr->Untyped[2] = (TmpVal.Int32Val >> 8) & 255;
534 Ptr->Untyped[1] = (TmpVal.Int32Val >> 16) & 255;
535 Ptr->Untyped[0] = (TmpVal.Int32Val >> 24) & 255;
536 } else if (BitWidth <= 64) {
537 TmpVal.Int64Val &= BitMask;
538 Ptr->Untyped[7] = (unsigned char)(TmpVal.Int64Val );
539 Ptr->Untyped[6] = (unsigned char)(TmpVal.Int64Val >> 8);
540 Ptr->Untyped[5] = (unsigned char)(TmpVal.Int64Val >> 16);
541 Ptr->Untyped[4] = (unsigned char)(TmpVal.Int64Val >> 24);
542 Ptr->Untyped[3] = (unsigned char)(TmpVal.Int64Val >> 32);
543 Ptr->Untyped[2] = (unsigned char)(TmpVal.Int64Val >> 40);
544 Ptr->Untyped[1] = (unsigned char)(TmpVal.Int64Val >> 48);
545 Ptr->Untyped[0] = (unsigned char)(TmpVal.Int64Val >> 56);
547 uint64_t *Dest = (uint64_t*)Ptr;
548 const uint64_t *Src = Val.APIntVal->getRawData();
549 for (uint32_t i = 0; i < Val.APIntVal->getNumWords(); ++i)
554 Store4BytesBigEndian:
555 case Type::FloatTyID:
556 Ptr->Untyped[3] = Val.Int32Val & 255;
557 Ptr->Untyped[2] = (Val.Int32Val >> 8) & 255;
558 Ptr->Untyped[1] = (Val.Int32Val >> 16) & 255;
559 Ptr->Untyped[0] = (Val.Int32Val >> 24) & 255;
561 case Type::PointerTyID:
562 if (getTargetData()->getPointerSize() == 4)
563 goto Store4BytesBigEndian;
565 case Type::DoubleTyID:
566 Ptr->Untyped[7] = (unsigned char)(Val.Int64Val );
567 Ptr->Untyped[6] = (unsigned char)(Val.Int64Val >> 8);
568 Ptr->Untyped[5] = (unsigned char)(Val.Int64Val >> 16);
569 Ptr->Untyped[4] = (unsigned char)(Val.Int64Val >> 24);
570 Ptr->Untyped[3] = (unsigned char)(Val.Int64Val >> 32);
571 Ptr->Untyped[2] = (unsigned char)(Val.Int64Val >> 40);
572 Ptr->Untyped[1] = (unsigned char)(Val.Int64Val >> 48);
573 Ptr->Untyped[0] = (unsigned char)(Val.Int64Val >> 56);
576 cerr << "Cannot store value of type " << *Ty << "!\n";
583 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
586 if (getTargetData()->isLittleEndian()) {
587 switch (Ty->getTypeID()) {
588 case Type::IntegerTyID: {
589 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
591 Result.Int8Val = Ptr->Untyped[0];
592 else if (BitWidth <= 16) {
593 Result.Int16Val = (unsigned)Ptr->Untyped[0] |
594 ((unsigned)Ptr->Untyped[1] << 8);
595 } else if (BitWidth <= 32) {
596 Result.Int32Val = (unsigned)Ptr->Untyped[0] |
597 ((unsigned)Ptr->Untyped[1] << 8) |
598 ((unsigned)Ptr->Untyped[2] << 16) |
599 ((unsigned)Ptr->Untyped[3] << 24);
600 } else if (BitWidth <= 64) {
601 Result.Int64Val = (uint64_t)Ptr->Untyped[0] |
602 ((uint64_t)Ptr->Untyped[1] << 8) |
603 ((uint64_t)Ptr->Untyped[2] << 16) |
604 ((uint64_t)Ptr->Untyped[3] << 24) |
605 ((uint64_t)Ptr->Untyped[4] << 32) |
606 ((uint64_t)Ptr->Untyped[5] << 40) |
607 ((uint64_t)Ptr->Untyped[6] << 48) |
608 ((uint64_t)Ptr->Untyped[7] << 56);
610 *(Result.APIntVal) = APInt(BitWidth, BitWidth/64, (uint64_t*)Ptr);
613 Load4BytesLittleEndian:
614 case Type::FloatTyID:
615 Result.Int32Val = (unsigned)Ptr->Untyped[0] |
616 ((unsigned)Ptr->Untyped[1] << 8) |
617 ((unsigned)Ptr->Untyped[2] << 16) |
618 ((unsigned)Ptr->Untyped[3] << 24);
620 case Type::PointerTyID:
621 if (getTargetData()->getPointerSize() == 4)
622 goto Load4BytesLittleEndian;
624 case Type::DoubleTyID:
625 Result.Int64Val = (uint64_t)Ptr->Untyped[0] |
626 ((uint64_t)Ptr->Untyped[1] << 8) |
627 ((uint64_t)Ptr->Untyped[2] << 16) |
628 ((uint64_t)Ptr->Untyped[3] << 24) |
629 ((uint64_t)Ptr->Untyped[4] << 32) |
630 ((uint64_t)Ptr->Untyped[5] << 40) |
631 ((uint64_t)Ptr->Untyped[6] << 48) |
632 ((uint64_t)Ptr->Untyped[7] << 56);
635 cerr << "Cannot load value of type " << *Ty << "!\n";
639 switch (Ty->getTypeID()) {
640 case Type::IntegerTyID: {
641 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
643 Result.Int8Val = Ptr->Untyped[0];
644 else if (BitWidth <= 16) {
645 Result.Int16Val = (unsigned)Ptr->Untyped[1] |
646 ((unsigned)Ptr->Untyped[0] << 8);
647 } else if (BitWidth <= 32) {
648 Result.Int32Val = (unsigned)Ptr->Untyped[3] |
649 ((unsigned)Ptr->Untyped[2] << 8) |
650 ((unsigned)Ptr->Untyped[1] << 16) |
651 ((unsigned)Ptr->Untyped[0] << 24);
652 } else if (BitWidth <= 64) {
653 Result.Int64Val = (uint64_t)Ptr->Untyped[7] |
654 ((uint64_t)Ptr->Untyped[6] << 8) |
655 ((uint64_t)Ptr->Untyped[5] << 16) |
656 ((uint64_t)Ptr->Untyped[4] << 24) |
657 ((uint64_t)Ptr->Untyped[3] << 32) |
658 ((uint64_t)Ptr->Untyped[2] << 40) |
659 ((uint64_t)Ptr->Untyped[1] << 48) |
660 ((uint64_t)Ptr->Untyped[0] << 56);
662 *(Result.APIntVal) = APInt(BitWidth, BitWidth/64, (uint64_t*)Ptr);
666 case Type::FloatTyID:
667 Result.Int32Val = (unsigned)Ptr->Untyped[3] |
668 ((unsigned)Ptr->Untyped[2] << 8) |
669 ((unsigned)Ptr->Untyped[1] << 16) |
670 ((unsigned)Ptr->Untyped[0] << 24);
672 case Type::PointerTyID:
673 if (getTargetData()->getPointerSize() == 4)
674 goto Load4BytesBigEndian;
676 case Type::DoubleTyID:
677 Result.Int64Val = (uint64_t)Ptr->Untyped[7] |
678 ((uint64_t)Ptr->Untyped[6] << 8) |
679 ((uint64_t)Ptr->Untyped[5] << 16) |
680 ((uint64_t)Ptr->Untyped[4] << 24) |
681 ((uint64_t)Ptr->Untyped[3] << 32) |
682 ((uint64_t)Ptr->Untyped[2] << 40) |
683 ((uint64_t)Ptr->Untyped[1] << 48) |
684 ((uint64_t)Ptr->Untyped[0] << 56);
687 cerr << "Cannot load value of type " << *Ty << "!\n";
693 // InitializeMemory - Recursive function to apply a Constant value into the
694 // specified memory location...
696 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
697 if (isa<UndefValue>(Init)) {
699 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
700 unsigned ElementSize =
701 getTargetData()->getTypeSize(CP->getType()->getElementType());
702 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
703 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
705 } else if (Init->getType()->isFirstClassType()) {
706 GenericValue Val = getConstantValue(Init);
707 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
709 } else if (isa<ConstantAggregateZero>(Init)) {
710 memset(Addr, 0, (size_t)getTargetData()->getTypeSize(Init->getType()));
714 switch (Init->getType()->getTypeID()) {
715 case Type::ArrayTyID: {
716 const ConstantArray *CPA = cast<ConstantArray>(Init);
717 unsigned ElementSize =
718 getTargetData()->getTypeSize(CPA->getType()->getElementType());
719 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
720 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
724 case Type::StructTyID: {
725 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
726 const StructLayout *SL =
727 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
728 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
729 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
734 cerr << "Bad Type: " << *Init->getType() << "\n";
735 assert(0 && "Unknown constant type to initialize memory with!");
739 /// EmitGlobals - Emit all of the global variables to memory, storing their
740 /// addresses into GlobalAddress. This must make sure to copy the contents of
741 /// their initializers into the memory.
743 void ExecutionEngine::emitGlobals() {
744 const TargetData *TD = getTargetData();
746 // Loop over all of the global variables in the program, allocating the memory
747 // to hold them. If there is more than one module, do a prepass over globals
748 // to figure out how the different modules should link together.
750 std::map<std::pair<std::string, const Type*>,
751 const GlobalValue*> LinkedGlobalsMap;
753 if (Modules.size() != 1) {
754 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
755 Module &M = *Modules[m]->getModule();
756 for (Module::const_global_iterator I = M.global_begin(),
757 E = M.global_end(); I != E; ++I) {
758 const GlobalValue *GV = I;
759 if (GV->hasInternalLinkage() || GV->isDeclaration() ||
760 GV->hasAppendingLinkage() || !GV->hasName())
761 continue;// Ignore external globals and globals with internal linkage.
763 const GlobalValue *&GVEntry =
764 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
766 // If this is the first time we've seen this global, it is the canonical
773 // If the existing global is strong, never replace it.
774 if (GVEntry->hasExternalLinkage() ||
775 GVEntry->hasDLLImportLinkage() ||
776 GVEntry->hasDLLExportLinkage())
779 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
781 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
787 std::vector<const GlobalValue*> NonCanonicalGlobals;
788 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
789 Module &M = *Modules[m]->getModule();
790 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
792 // In the multi-module case, see what this global maps to.
793 if (!LinkedGlobalsMap.empty()) {
794 if (const GlobalValue *GVEntry =
795 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
796 // If something else is the canonical global, ignore this one.
797 if (GVEntry != &*I) {
798 NonCanonicalGlobals.push_back(I);
804 if (!I->isDeclaration()) {
805 // Get the type of the global.
806 const Type *Ty = I->getType()->getElementType();
808 // Allocate some memory for it!
809 unsigned Size = TD->getTypeSize(Ty);
810 addGlobalMapping(I, new char[Size]);
812 // External variable reference. Try to use the dynamic loader to
813 // get a pointer to it.
815 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
816 addGlobalMapping(I, SymAddr);
818 cerr << "Could not resolve external global address: "
819 << I->getName() << "\n";
825 // If there are multiple modules, map the non-canonical globals to their
826 // canonical location.
827 if (!NonCanonicalGlobals.empty()) {
828 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
829 const GlobalValue *GV = NonCanonicalGlobals[i];
830 const GlobalValue *CGV =
831 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
832 void *Ptr = getPointerToGlobalIfAvailable(CGV);
833 assert(Ptr && "Canonical global wasn't codegen'd!");
834 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
838 // Now that all of the globals are set up in memory, loop through them all
839 // and initialize their contents.
840 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
842 if (!I->isDeclaration()) {
843 if (!LinkedGlobalsMap.empty()) {
844 if (const GlobalValue *GVEntry =
845 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
846 if (GVEntry != &*I) // Not the canonical variable.
849 EmitGlobalVariable(I);
855 // EmitGlobalVariable - This method emits the specified global variable to the
856 // address specified in GlobalAddresses, or allocates new memory if it's not
857 // already in the map.
858 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
859 void *GA = getPointerToGlobalIfAvailable(GV);
860 DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
862 const Type *ElTy = GV->getType()->getElementType();
863 size_t GVSize = (size_t)getTargetData()->getTypeSize(ElTy);
865 // If it's not already specified, allocate memory for the global.
866 GA = new char[GVSize];
867 addGlobalMapping(GV, GA);
870 InitializeMemory(GV->getInitializer(), GA);
871 NumInitBytes += (unsigned)GVSize;