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("lli", "Number of bytes of global vars initialized");
31 Statistic<> NumGlobals ("lli", "Number of global vars initialized");
34 ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
35 ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
37 ExecutionEngine::ExecutionEngine(ModuleProvider *P) {
38 LazyCompilationDisabled = false;
40 assert(P && "ModuleProvider is null?");
43 ExecutionEngine::ExecutionEngine(Module *M) {
44 LazyCompilationDisabled = false;
45 assert(M && "Module is null?");
46 Modules.push_back(new ExistingModuleProvider(M));
49 ExecutionEngine::~ExecutionEngine() {
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()->getNamedFunction(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::SByteTy);
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->isExternal() || 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 = argv.size();
234 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
236 GVArgs.push_back(GVArgc); // Arg #0 = argc.
238 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
239 assert(((char **)GVTOP(GVArgs[1]))[0] &&
240 "argv[0] was null after CreateArgv");
242 std::vector<std::string> EnvVars;
243 for (unsigned i = 0; envp[i]; ++i)
244 EnvVars.push_back(envp[i]);
245 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
249 return runFunction(Fn, GVArgs).IntVal;
252 /// If possible, create a JIT, unless the caller specifically requests an
253 /// Interpreter or there's an error. If even an Interpreter cannot be created,
254 /// NULL is returned.
256 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
257 bool ForceInterpreter) {
258 ExecutionEngine *EE = 0;
260 // Unless the interpreter was explicitly selected, try making a JIT.
261 if (!ForceInterpreter && JITCtor)
264 // If we can't make a JIT, make an interpreter instead.
265 if (EE == 0 && InterpCtor)
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("Global hasn't had an address allocated yet!");
298 return state.getGlobalAddressMap(locked)[GV];
301 /// This function converts a Constant* into a GenericValue. The interesting
302 /// part is if C is a ConstantExpr.
303 /// @brief Get a GenericValue for a Constnat*
304 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
305 // Declare the result as garbage.
308 // If its undefined, return the garbage.
309 if (isa<UndefValue>(C)) return Result;
311 // If the value is a ConstantExpr
312 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
313 switch (CE->getOpcode()) {
314 case Instruction::GetElementPtr: {
316 Result = getConstantValue(CE->getOperand(0));
317 std::vector<Value*> Indexes(CE->op_begin()+1, CE->op_end());
319 TD->getIndexedOffset(CE->getOperand(0)->getType(), Indexes);
321 if (getTargetData()->getPointerSize() == 4)
322 Result.IntVal += Offset;
324 Result.LongVal += Offset;
327 case Instruction::Trunc:
328 case Instruction::ZExt:
329 case Instruction::SExt:
330 case Instruction::FPTrunc:
331 case Instruction::FPExt:
332 case Instruction::UIToFP:
333 case Instruction::SIToFP:
334 case Instruction::FPToUI:
335 case Instruction::FPToSI:
337 case Instruction::PtrToInt: {
338 Constant *Op = CE->getOperand(0);
339 GenericValue GV = getConstantValue(Op);
342 case Instruction::BitCast: {
343 // Bit casts are no-ops but we can only return the GV of the operand if
344 // they are the same basic type (pointer->pointer, packed->packed, etc.)
345 Constant *Op = CE->getOperand(0);
346 GenericValue GV = getConstantValue(Op);
347 if (Op->getType()->getTypeID() == C->getType()->getTypeID())
351 case Instruction::IntToPtr: {
352 // IntToPtr casts are just so special. Cast to intptr_t first.
353 Constant *Op = CE->getOperand(0);
354 GenericValue GV = getConstantValue(Op);
355 switch (Op->getType()->getTypeID()) {
356 case Type::BoolTyID: return PTOGV((void*)(uintptr_t)GV.BoolVal);
357 case Type::SByteTyID: return PTOGV((void*)( intptr_t)GV.SByteVal);
358 case Type::UByteTyID: return PTOGV((void*)(uintptr_t)GV.UByteVal);
359 case Type::ShortTyID: return PTOGV((void*)( intptr_t)GV.ShortVal);
360 case Type::UShortTyID: return PTOGV((void*)(uintptr_t)GV.UShortVal);
361 case Type::IntTyID: return PTOGV((void*)( intptr_t)GV.IntVal);
362 case Type::UIntTyID: return PTOGV((void*)(uintptr_t)GV.UIntVal);
363 case Type::LongTyID: return PTOGV((void*)( intptr_t)GV.LongVal);
364 case Type::ULongTyID: return PTOGV((void*)(uintptr_t)GV.ULongVal);
365 default: assert(0 && "Unknown integral type!");
369 case Instruction::Add:
370 switch (CE->getOperand(0)->getType()->getTypeID()) {
371 default: assert(0 && "Bad add type!"); abort();
373 case Type::ULongTyID:
374 Result.LongVal = getConstantValue(CE->getOperand(0)).LongVal +
375 getConstantValue(CE->getOperand(1)).LongVal;
379 Result.IntVal = getConstantValue(CE->getOperand(0)).IntVal +
380 getConstantValue(CE->getOperand(1)).IntVal;
382 case Type::ShortTyID:
383 case Type::UShortTyID:
384 Result.ShortVal = getConstantValue(CE->getOperand(0)).ShortVal +
385 getConstantValue(CE->getOperand(1)).ShortVal;
387 case Type::SByteTyID:
388 case Type::UByteTyID:
389 Result.SByteVal = getConstantValue(CE->getOperand(0)).SByteVal +
390 getConstantValue(CE->getOperand(1)).SByteVal;
392 case Type::FloatTyID:
393 Result.FloatVal = getConstantValue(CE->getOperand(0)).FloatVal +
394 getConstantValue(CE->getOperand(1)).FloatVal;
396 case Type::DoubleTyID:
397 Result.DoubleVal = getConstantValue(CE->getOperand(0)).DoubleVal +
398 getConstantValue(CE->getOperand(1)).DoubleVal;
405 llvm_cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
409 switch (C->getType()->getTypeID()) {
410 #define GET_CONST_VAL(TY, CTY, CLASS, GETMETH) \
411 case Type::TY##TyID: Result.TY##Val = (CTY)cast<CLASS>(C)->GETMETH(); break
412 GET_CONST_VAL(Bool , bool , ConstantBool, getValue);
413 GET_CONST_VAL(UByte , unsigned char , ConstantInt, getZExtValue);
414 GET_CONST_VAL(SByte , signed char , ConstantInt, getSExtValue);
415 GET_CONST_VAL(UShort , unsigned short, ConstantInt, getZExtValue);
416 GET_CONST_VAL(Short , signed short , ConstantInt, getSExtValue);
417 GET_CONST_VAL(UInt , unsigned int , ConstantInt, getZExtValue);
418 GET_CONST_VAL(Int , signed int , ConstantInt, getSExtValue);
419 GET_CONST_VAL(ULong , uint64_t , ConstantInt, getZExtValue);
420 GET_CONST_VAL(Long , int64_t , ConstantInt, getSExtValue);
421 GET_CONST_VAL(Float , float , ConstantFP, getValue);
422 GET_CONST_VAL(Double , double , ConstantFP, getValue);
424 case Type::PointerTyID:
425 if (isa<ConstantPointerNull>(C))
426 Result.PointerVal = 0;
427 else if (const Function *F = dyn_cast<Function>(C))
428 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
429 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
430 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
432 assert(0 && "Unknown constant pointer type!");
435 llvm_cerr << "ERROR: Constant unimp for type: " << *C->getType() << "\n";
441 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
442 /// is the address of the memory at which to store Val, cast to GenericValue *.
443 /// It is not a pointer to a GenericValue containing the address at which to
446 void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
448 if (getTargetData()->isLittleEndian()) {
449 switch (Ty->getTypeID()) {
451 case Type::UByteTyID:
452 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
453 case Type::UShortTyID:
454 case Type::ShortTyID: Ptr->Untyped[0] = Val.UShortVal & 255;
455 Ptr->Untyped[1] = (Val.UShortVal >> 8) & 255;
457 Store4BytesLittleEndian:
458 case Type::FloatTyID:
460 case Type::IntTyID: Ptr->Untyped[0] = Val.UIntVal & 255;
461 Ptr->Untyped[1] = (Val.UIntVal >> 8) & 255;
462 Ptr->Untyped[2] = (Val.UIntVal >> 16) & 255;
463 Ptr->Untyped[3] = (Val.UIntVal >> 24) & 255;
465 case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4)
466 goto Store4BytesLittleEndian;
467 case Type::DoubleTyID:
468 case Type::ULongTyID:
470 Ptr->Untyped[0] = (unsigned char)(Val.ULongVal );
471 Ptr->Untyped[1] = (unsigned char)(Val.ULongVal >> 8);
472 Ptr->Untyped[2] = (unsigned char)(Val.ULongVal >> 16);
473 Ptr->Untyped[3] = (unsigned char)(Val.ULongVal >> 24);
474 Ptr->Untyped[4] = (unsigned char)(Val.ULongVal >> 32);
475 Ptr->Untyped[5] = (unsigned char)(Val.ULongVal >> 40);
476 Ptr->Untyped[6] = (unsigned char)(Val.ULongVal >> 48);
477 Ptr->Untyped[7] = (unsigned char)(Val.ULongVal >> 56);
480 llvm_cerr << "Cannot store value of type " << *Ty << "!\n";
483 switch (Ty->getTypeID()) {
485 case Type::UByteTyID:
486 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
487 case Type::UShortTyID:
488 case Type::ShortTyID: Ptr->Untyped[1] = Val.UShortVal & 255;
489 Ptr->Untyped[0] = (Val.UShortVal >> 8) & 255;
491 Store4BytesBigEndian:
492 case Type::FloatTyID:
494 case Type::IntTyID: Ptr->Untyped[3] = Val.UIntVal & 255;
495 Ptr->Untyped[2] = (Val.UIntVal >> 8) & 255;
496 Ptr->Untyped[1] = (Val.UIntVal >> 16) & 255;
497 Ptr->Untyped[0] = (Val.UIntVal >> 24) & 255;
499 case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4)
500 goto Store4BytesBigEndian;
501 case Type::DoubleTyID:
502 case Type::ULongTyID:
504 Ptr->Untyped[7] = (unsigned char)(Val.ULongVal );
505 Ptr->Untyped[6] = (unsigned char)(Val.ULongVal >> 8);
506 Ptr->Untyped[5] = (unsigned char)(Val.ULongVal >> 16);
507 Ptr->Untyped[4] = (unsigned char)(Val.ULongVal >> 24);
508 Ptr->Untyped[3] = (unsigned char)(Val.ULongVal >> 32);
509 Ptr->Untyped[2] = (unsigned char)(Val.ULongVal >> 40);
510 Ptr->Untyped[1] = (unsigned char)(Val.ULongVal >> 48);
511 Ptr->Untyped[0] = (unsigned char)(Val.ULongVal >> 56);
514 llvm_cerr << "Cannot store value of type " << *Ty << "!\n";
521 GenericValue ExecutionEngine::LoadValueFromMemory(GenericValue *Ptr,
524 if (getTargetData()->isLittleEndian()) {
525 switch (Ty->getTypeID()) {
527 case Type::UByteTyID:
528 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
529 case Type::UShortTyID:
530 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[0] |
531 ((unsigned)Ptr->Untyped[1] << 8);
533 Load4BytesLittleEndian:
534 case Type::FloatTyID:
536 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[0] |
537 ((unsigned)Ptr->Untyped[1] << 8) |
538 ((unsigned)Ptr->Untyped[2] << 16) |
539 ((unsigned)Ptr->Untyped[3] << 24);
541 case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4)
542 goto Load4BytesLittleEndian;
543 case Type::DoubleTyID:
544 case Type::ULongTyID:
545 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[0] |
546 ((uint64_t)Ptr->Untyped[1] << 8) |
547 ((uint64_t)Ptr->Untyped[2] << 16) |
548 ((uint64_t)Ptr->Untyped[3] << 24) |
549 ((uint64_t)Ptr->Untyped[4] << 32) |
550 ((uint64_t)Ptr->Untyped[5] << 40) |
551 ((uint64_t)Ptr->Untyped[6] << 48) |
552 ((uint64_t)Ptr->Untyped[7] << 56);
555 llvm_cerr << "Cannot load value of type " << *Ty << "!\n";
559 switch (Ty->getTypeID()) {
561 case Type::UByteTyID:
562 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
563 case Type::UShortTyID:
564 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[1] |
565 ((unsigned)Ptr->Untyped[0] << 8);
568 case Type::FloatTyID:
570 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[3] |
571 ((unsigned)Ptr->Untyped[2] << 8) |
572 ((unsigned)Ptr->Untyped[1] << 16) |
573 ((unsigned)Ptr->Untyped[0] << 24);
575 case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4)
576 goto Load4BytesBigEndian;
577 case Type::DoubleTyID:
578 case Type::ULongTyID:
579 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[7] |
580 ((uint64_t)Ptr->Untyped[6] << 8) |
581 ((uint64_t)Ptr->Untyped[5] << 16) |
582 ((uint64_t)Ptr->Untyped[4] << 24) |
583 ((uint64_t)Ptr->Untyped[3] << 32) |
584 ((uint64_t)Ptr->Untyped[2] << 40) |
585 ((uint64_t)Ptr->Untyped[1] << 48) |
586 ((uint64_t)Ptr->Untyped[0] << 56);
589 llvm_cerr << "Cannot load value of type " << *Ty << "!\n";
596 // InitializeMemory - Recursive function to apply a Constant value into the
597 // specified memory location...
599 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
600 if (isa<UndefValue>(Init)) {
602 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(Init)) {
603 unsigned ElementSize =
604 getTargetData()->getTypeSize(CP->getType()->getElementType());
605 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
606 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
608 } else if (Init->getType()->isFirstClassType()) {
609 GenericValue Val = getConstantValue(Init);
610 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
612 } else if (isa<ConstantAggregateZero>(Init)) {
613 memset(Addr, 0, (size_t)getTargetData()->getTypeSize(Init->getType()));
617 switch (Init->getType()->getTypeID()) {
618 case Type::ArrayTyID: {
619 const ConstantArray *CPA = cast<ConstantArray>(Init);
620 unsigned ElementSize =
621 getTargetData()->getTypeSize(CPA->getType()->getElementType());
622 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
623 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
627 case Type::StructTyID: {
628 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
629 const StructLayout *SL =
630 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
631 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
632 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->MemberOffsets[i]);
637 llvm_cerr << "Bad Type: " << *Init->getType() << "\n";
638 assert(0 && "Unknown constant type to initialize memory with!");
642 /// EmitGlobals - Emit all of the global variables to memory, storing their
643 /// addresses into GlobalAddress. This must make sure to copy the contents of
644 /// their initializers into the memory.
646 void ExecutionEngine::emitGlobals() {
647 const TargetData *TD = getTargetData();
649 // Loop over all of the global variables in the program, allocating the memory
650 // to hold them. If there is more than one module, do a prepass over globals
651 // to figure out how the different modules should link together.
653 std::map<std::pair<std::string, const Type*>,
654 const GlobalValue*> LinkedGlobalsMap;
656 if (Modules.size() != 1) {
657 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
658 Module &M = *Modules[m]->getModule();
659 for (Module::const_global_iterator I = M.global_begin(),
660 E = M.global_end(); I != E; ++I) {
661 const GlobalValue *GV = I;
662 if (GV->hasInternalLinkage() || GV->isExternal() ||
663 GV->hasAppendingLinkage() || !GV->hasName())
664 continue;// Ignore external globals and globals with internal linkage.
666 const GlobalValue *&GVEntry =
667 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
669 // If this is the first time we've seen this global, it is the canonical
676 // If the existing global is strong, never replace it.
677 if (GVEntry->hasExternalLinkage() ||
678 GVEntry->hasDLLImportLinkage() ||
679 GVEntry->hasDLLExportLinkage())
682 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
684 if (GV->hasExternalLinkage())
690 std::vector<const GlobalValue*> NonCanonicalGlobals;
691 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
692 Module &M = *Modules[m]->getModule();
693 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
695 // In the multi-module case, see what this global maps to.
696 if (!LinkedGlobalsMap.empty()) {
697 if (const GlobalValue *GVEntry =
698 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
699 // If something else is the canonical global, ignore this one.
700 if (GVEntry != &*I) {
701 NonCanonicalGlobals.push_back(I);
707 if (!I->isExternal()) {
708 // Get the type of the global.
709 const Type *Ty = I->getType()->getElementType();
711 // Allocate some memory for it!
712 unsigned Size = TD->getTypeSize(Ty);
713 addGlobalMapping(I, new char[Size]);
715 // External variable reference. Try to use the dynamic loader to
716 // get a pointer to it.
718 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
719 addGlobalMapping(I, SymAddr);
721 llvm_cerr << "Could not resolve external global address: "
722 << I->getName() << "\n";
728 // If there are multiple modules, map the non-canonical globals to their
729 // canonical location.
730 if (!NonCanonicalGlobals.empty()) {
731 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
732 const GlobalValue *GV = NonCanonicalGlobals[i];
733 const GlobalValue *CGV =
734 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
735 void *Ptr = getPointerToGlobalIfAvailable(CGV);
736 assert(Ptr && "Canonical global wasn't codegen'd!");
737 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
741 // Now that all of the globals are set up in memory, loop through them all and
742 // initialize their contents.
743 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
745 if (!I->isExternal()) {
746 if (!LinkedGlobalsMap.empty()) {
747 if (const GlobalValue *GVEntry =
748 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
749 if (GVEntry != &*I) // Not the canonical variable.
752 EmitGlobalVariable(I);
758 // EmitGlobalVariable - This method emits the specified global variable to the
759 // address specified in GlobalAddresses, or allocates new memory if it's not
760 // already in the map.
761 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
762 void *GA = getPointerToGlobalIfAvailable(GV);
763 DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
765 const Type *ElTy = GV->getType()->getElementType();
766 size_t GVSize = (size_t)getTargetData()->getTypeSize(ElTy);
768 // If it's not already specified, allocate memory for the global.
769 GA = new char[GVSize];
770 addGlobalMapping(GV, GA);
773 InitializeMemory(GV->getInitializer(), GA);
774 NumInitBytes += (unsigned)GVSize;