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 "Interpreter/Interpreter.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Module.h"
21 #include "llvm/ModuleProvider.h"
22 #include "llvm/CodeGen/IntrinsicLowering.h"
23 #include "llvm/ExecutionEngine/ExecutionEngine.h"
24 #include "llvm/ExecutionEngine/GenericValue.h"
25 #include "llvm/Target/TargetData.h"
26 #include "Support/Debug.h"
27 #include "Support/Statistic.h"
28 #include "Support/DynamicLinker.h"
32 Statistic<> NumInitBytes("lli", "Number of bytes of global vars initialized");
33 Statistic<> NumGlobals ("lli", "Number of global vars initialized");
36 ExecutionEngine::ExecutionEngine(ModuleProvider *P) :
37 CurMod(*P->getModule()), MP(P) {
38 assert(P && "ModuleProvider is null?");
41 ExecutionEngine::ExecutionEngine(Module *M) : CurMod(*M), MP(0) {
42 assert(M && "Module is null?");
45 ExecutionEngine::~ExecutionEngine() {
49 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
50 /// at the specified address.
52 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
53 // If we haven't computed the reverse mapping yet, do so first.
54 if (GlobalAddressReverseMap.empty()) {
55 for (std::map<const GlobalValue*, void *>::iterator I =
56 GlobalAddressMap.begin(), E = GlobalAddressMap.end(); I != E; ++I)
57 GlobalAddressReverseMap.insert(std::make_pair(I->second, I->first));
60 std::map<void *, const GlobalValue*>::iterator I =
61 GlobalAddressReverseMap.find(Addr);
62 return I != GlobalAddressReverseMap.end() ? I->second : 0;
65 // CreateArgv - Turn a vector of strings into a nice argv style array of
66 // pointers to null terminated strings.
68 static void *CreateArgv(ExecutionEngine *EE,
69 const std::vector<std::string> &InputArgv) {
70 unsigned PtrSize = EE->getTargetData().getPointerSize();
71 char *Result = new char[(InputArgv.size()+1)*PtrSize];
73 DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n");
74 const Type *SBytePtr = PointerType::get(Type::SByteTy);
76 for (unsigned i = 0; i != InputArgv.size(); ++i) {
77 unsigned Size = InputArgv[i].size()+1;
78 char *Dest = new char[Size];
79 DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n");
81 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
84 // Endian safe: Result[i] = (PointerTy)Dest;
85 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
90 EE->StoreValueToMemory(PTOGV(0),
91 (GenericValue*)(Result+InputArgv.size()*PtrSize),
96 /// runFunctionAsMain - This is a helper function which wraps runFunction to
97 /// handle the common task of starting up main with the specified argc, argv,
98 /// and envp parameters.
99 int ExecutionEngine::runFunctionAsMain(Function *Fn,
100 const std::vector<std::string> &argv,
101 const char * const * envp) {
102 std::vector<GenericValue> GVArgs;
104 GVArgc.IntVal = argv.size();
105 GVArgs.push_back(GVArgc); // Arg #0 = argc.
106 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
107 assert(((char **)GVTOP(GVArgs[1]))[0] && "argv[0] was null after CreateArgv");
109 std::vector<std::string> EnvVars;
110 for (unsigned i = 0; envp[i]; ++i)
111 EnvVars.push_back(envp[i]);
112 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
113 return runFunction(Fn, GVArgs).IntVal;
118 /// If possible, create a JIT, unless the caller specifically requests an
119 /// Interpreter or there's an error. If even an Interpreter cannot be created,
120 /// NULL is returned.
122 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
123 bool ForceInterpreter,
124 IntrinsicLowering *IL) {
125 ExecutionEngine *EE = 0;
127 // Unless the interpreter was explicitly selected, try making a JIT.
128 if (!ForceInterpreter)
129 EE = JIT::create(MP, IL);
131 // If we can't make a JIT, make an interpreter instead.
134 Module *M = MP->materializeModule();
136 EE = Interpreter::create(M, IL);
138 std::cerr << "Error creating the interpreter!\n";
140 } catch (std::string& errmsg) {
141 std::cerr << "Error reading the bytecode file: " << errmsg << "\n";
143 std::cerr << "Error reading the bytecode file!\n";
147 if (EE == 0) delete IL;
151 /// getPointerToGlobal - This returns the address of the specified global
152 /// value. This may involve code generation if it's a function.
154 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
155 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
156 return getPointerToFunction(F);
158 assert(GlobalAddressMap[GV] && "Global hasn't had an address allocated yet?");
159 return GlobalAddressMap[GV];
164 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
167 if (ConstantExpr *CE = const_cast<ConstantExpr*>(dyn_cast<ConstantExpr>(C))) {
168 switch (CE->getOpcode()) {
169 case Instruction::GetElementPtr: {
170 Result = getConstantValue(CE->getOperand(0));
171 std::vector<Value*> Indexes(CE->op_begin()+1, CE->op_end());
173 TD->getIndexedOffset(CE->getOperand(0)->getType(), Indexes);
175 Result.LongVal += Offset;
178 case Instruction::Cast: {
179 // We only need to handle a few cases here. Almost all casts will
180 // automatically fold, just the ones involving pointers won't.
182 Constant *Op = CE->getOperand(0);
183 GenericValue GV = getConstantValue(Op);
185 // Handle cast of pointer to pointer...
186 if (Op->getType()->getTypeID() == C->getType()->getTypeID())
189 // Handle a cast of pointer to any integral type...
190 if (isa<PointerType>(Op->getType()) && C->getType()->isIntegral())
193 // Handle cast of integer to a pointer...
194 if (isa<PointerType>(C->getType()) && Op->getType()->isIntegral())
195 switch (Op->getType()->getTypeID()) {
196 case Type::BoolTyID: return PTOGV((void*)(uintptr_t)GV.BoolVal);
197 case Type::SByteTyID: return PTOGV((void*)( intptr_t)GV.SByteVal);
198 case Type::UByteTyID: return PTOGV((void*)(uintptr_t)GV.UByteVal);
199 case Type::ShortTyID: return PTOGV((void*)( intptr_t)GV.ShortVal);
200 case Type::UShortTyID: return PTOGV((void*)(uintptr_t)GV.UShortVal);
201 case Type::IntTyID: return PTOGV((void*)( intptr_t)GV.IntVal);
202 case Type::UIntTyID: return PTOGV((void*)(uintptr_t)GV.UIntVal);
203 case Type::LongTyID: return PTOGV((void*)( intptr_t)GV.LongVal);
204 case Type::ULongTyID: return PTOGV((void*)(uintptr_t)GV.ULongVal);
205 default: assert(0 && "Unknown integral type!");
210 case Instruction::Add:
211 if (CE->getOperand(0)->getType() == Type::LongTy ||
212 CE->getOperand(0)->getType() == Type::ULongTy)
213 Result.LongVal = getConstantValue(CE->getOperand(0)).LongVal +
214 getConstantValue(CE->getOperand(1)).LongVal;
222 std::cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
226 switch (C->getType()->getTypeID()) {
227 #define GET_CONST_VAL(TY, CLASS) \
228 case Type::TY##TyID: Result.TY##Val = cast<CLASS>(C)->getValue(); break
229 GET_CONST_VAL(Bool , ConstantBool);
230 GET_CONST_VAL(UByte , ConstantUInt);
231 GET_CONST_VAL(SByte , ConstantSInt);
232 GET_CONST_VAL(UShort , ConstantUInt);
233 GET_CONST_VAL(Short , ConstantSInt);
234 GET_CONST_VAL(UInt , ConstantUInt);
235 GET_CONST_VAL(Int , ConstantSInt);
236 GET_CONST_VAL(ULong , ConstantUInt);
237 GET_CONST_VAL(Long , ConstantSInt);
238 GET_CONST_VAL(Float , ConstantFP);
239 GET_CONST_VAL(Double , ConstantFP);
241 case Type::PointerTyID:
242 if (isa<ConstantPointerNull>(C)) {
243 Result.PointerVal = 0;
244 } else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)){
246 const_cast<Function*>(dyn_cast<Function>(CPR->getValue())))
247 Result = PTOGV(getPointerToFunctionOrStub(F));
249 Result = PTOGV(getOrEmitGlobalVariable(
250 cast<GlobalVariable>(CPR->getValue())));
253 assert(0 && "Unknown constant pointer type!");
257 std::cout << "ERROR: Constant unimp for type: " << C->getType() << "\n";
265 void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
267 if (getTargetData().isLittleEndian()) {
268 switch (Ty->getTypeID()) {
270 case Type::UByteTyID:
271 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
272 case Type::UShortTyID:
273 case Type::ShortTyID: Ptr->Untyped[0] = Val.UShortVal & 255;
274 Ptr->Untyped[1] = (Val.UShortVal >> 8) & 255;
276 Store4BytesLittleEndian:
277 case Type::FloatTyID:
279 case Type::IntTyID: Ptr->Untyped[0] = Val.UIntVal & 255;
280 Ptr->Untyped[1] = (Val.UIntVal >> 8) & 255;
281 Ptr->Untyped[2] = (Val.UIntVal >> 16) & 255;
282 Ptr->Untyped[3] = (Val.UIntVal >> 24) & 255;
284 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
285 goto Store4BytesLittleEndian;
286 case Type::DoubleTyID:
287 case Type::ULongTyID:
288 case Type::LongTyID: Ptr->Untyped[0] = Val.ULongVal & 255;
289 Ptr->Untyped[1] = (Val.ULongVal >> 8) & 255;
290 Ptr->Untyped[2] = (Val.ULongVal >> 16) & 255;
291 Ptr->Untyped[3] = (Val.ULongVal >> 24) & 255;
292 Ptr->Untyped[4] = (Val.ULongVal >> 32) & 255;
293 Ptr->Untyped[5] = (Val.ULongVal >> 40) & 255;
294 Ptr->Untyped[6] = (Val.ULongVal >> 48) & 255;
295 Ptr->Untyped[7] = (Val.ULongVal >> 56) & 255;
298 std::cout << "Cannot store value of type " << Ty << "!\n";
301 switch (Ty->getTypeID()) {
303 case Type::UByteTyID:
304 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
305 case Type::UShortTyID:
306 case Type::ShortTyID: Ptr->Untyped[1] = Val.UShortVal & 255;
307 Ptr->Untyped[0] = (Val.UShortVal >> 8) & 255;
309 Store4BytesBigEndian:
310 case Type::FloatTyID:
312 case Type::IntTyID: Ptr->Untyped[3] = Val.UIntVal & 255;
313 Ptr->Untyped[2] = (Val.UIntVal >> 8) & 255;
314 Ptr->Untyped[1] = (Val.UIntVal >> 16) & 255;
315 Ptr->Untyped[0] = (Val.UIntVal >> 24) & 255;
317 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
318 goto Store4BytesBigEndian;
319 case Type::DoubleTyID:
320 case Type::ULongTyID:
321 case Type::LongTyID: Ptr->Untyped[7] = Val.ULongVal & 255;
322 Ptr->Untyped[6] = (Val.ULongVal >> 8) & 255;
323 Ptr->Untyped[5] = (Val.ULongVal >> 16) & 255;
324 Ptr->Untyped[4] = (Val.ULongVal >> 24) & 255;
325 Ptr->Untyped[3] = (Val.ULongVal >> 32) & 255;
326 Ptr->Untyped[2] = (Val.ULongVal >> 40) & 255;
327 Ptr->Untyped[1] = (Val.ULongVal >> 48) & 255;
328 Ptr->Untyped[0] = (Val.ULongVal >> 56) & 255;
331 std::cout << "Cannot store value of type " << Ty << "!\n";
338 GenericValue ExecutionEngine::LoadValueFromMemory(GenericValue *Ptr,
341 if (getTargetData().isLittleEndian()) {
342 switch (Ty->getTypeID()) {
344 case Type::UByteTyID:
345 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
346 case Type::UShortTyID:
347 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[0] |
348 ((unsigned)Ptr->Untyped[1] << 8);
350 Load4BytesLittleEndian:
351 case Type::FloatTyID:
353 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[0] |
354 ((unsigned)Ptr->Untyped[1] << 8) |
355 ((unsigned)Ptr->Untyped[2] << 16) |
356 ((unsigned)Ptr->Untyped[3] << 24);
358 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
359 goto Load4BytesLittleEndian;
360 case Type::DoubleTyID:
361 case Type::ULongTyID:
362 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[0] |
363 ((uint64_t)Ptr->Untyped[1] << 8) |
364 ((uint64_t)Ptr->Untyped[2] << 16) |
365 ((uint64_t)Ptr->Untyped[3] << 24) |
366 ((uint64_t)Ptr->Untyped[4] << 32) |
367 ((uint64_t)Ptr->Untyped[5] << 40) |
368 ((uint64_t)Ptr->Untyped[6] << 48) |
369 ((uint64_t)Ptr->Untyped[7] << 56);
372 std::cout << "Cannot load value of type " << *Ty << "!\n";
376 switch (Ty->getTypeID()) {
378 case Type::UByteTyID:
379 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
380 case Type::UShortTyID:
381 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[1] |
382 ((unsigned)Ptr->Untyped[0] << 8);
385 case Type::FloatTyID:
387 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[3] |
388 ((unsigned)Ptr->Untyped[2] << 8) |
389 ((unsigned)Ptr->Untyped[1] << 16) |
390 ((unsigned)Ptr->Untyped[0] << 24);
392 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
393 goto Load4BytesBigEndian;
394 case Type::DoubleTyID:
395 case Type::ULongTyID:
396 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[7] |
397 ((uint64_t)Ptr->Untyped[6] << 8) |
398 ((uint64_t)Ptr->Untyped[5] << 16) |
399 ((uint64_t)Ptr->Untyped[4] << 24) |
400 ((uint64_t)Ptr->Untyped[3] << 32) |
401 ((uint64_t)Ptr->Untyped[2] << 40) |
402 ((uint64_t)Ptr->Untyped[1] << 48) |
403 ((uint64_t)Ptr->Untyped[0] << 56);
406 std::cout << "Cannot load value of type " << *Ty << "!\n";
413 // InitializeMemory - Recursive function to apply a Constant value into the
414 // specified memory location...
416 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
417 if (Init->getType()->isFirstClassType()) {
418 GenericValue Val = getConstantValue(Init);
419 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
421 } else if (isa<ConstantAggregateZero>(Init)) {
422 unsigned Size = getTargetData().getTypeSize(Init->getType());
423 memset(Addr, 0, Size);
427 switch (Init->getType()->getTypeID()) {
428 case Type::ArrayTyID: {
429 const ConstantArray *CPA = cast<ConstantArray>(Init);
430 const std::vector<Use> &Val = CPA->getValues();
431 unsigned ElementSize =
432 getTargetData().getTypeSize(cast<ArrayType>(CPA->getType())->getElementType());
433 for (unsigned i = 0; i < Val.size(); ++i)
434 InitializeMemory(cast<Constant>(Val[i].get()), (char*)Addr+i*ElementSize);
438 case Type::StructTyID: {
439 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
440 const StructLayout *SL =
441 getTargetData().getStructLayout(cast<StructType>(CPS->getType()));
442 const std::vector<Use> &Val = CPS->getValues();
443 for (unsigned i = 0; i < Val.size(); ++i)
444 InitializeMemory(cast<Constant>(Val[i].get()),
445 (char*)Addr+SL->MemberOffsets[i]);
450 std::cerr << "Bad Type: " << Init->getType() << "\n";
451 assert(0 && "Unknown constant type to initialize memory with!");
455 /// EmitGlobals - Emit all of the global variables to memory, storing their
456 /// addresses into GlobalAddress. This must make sure to copy the contents of
457 /// their initializers into the memory.
459 void ExecutionEngine::emitGlobals() {
460 const TargetData &TD = getTargetData();
462 // Loop over all of the global variables in the program, allocating the memory
464 for (Module::giterator I = getModule().gbegin(), E = getModule().gend();
466 if (!I->isExternal()) {
467 // Get the type of the global...
468 const Type *Ty = I->getType()->getElementType();
470 // Allocate some memory for it!
471 unsigned Size = TD.getTypeSize(Ty);
472 addGlobalMapping(I, new char[Size]);
474 // External variable reference. Try to use the dynamic loader to
475 // get a pointer to it.
476 if (void *SymAddr = GetAddressOfSymbol(I->getName().c_str()))
477 addGlobalMapping(I, SymAddr);
479 std::cerr << "Could not resolve external global address: "
480 << I->getName() << "\n";
485 // Now that all of the globals are set up in memory, loop through them all and
486 // initialize their contents.
487 for (Module::giterator I = getModule().gbegin(), E = getModule().gend();
489 if (!I->isExternal())
490 EmitGlobalVariable(I);
493 // EmitGlobalVariable - This method emits the specified global variable to the
494 // address specified in GlobalAddresses, or allocates new memory if it's not
495 // already in the map.
496 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
497 void *GA = getPointerToGlobalIfAvailable(GV);
498 DEBUG(std::cerr << "Global '" << GV->getName() << "' -> " << GA << "\n");
500 const Type *ElTy = GV->getType()->getElementType();
502 // If it's not already specified, allocate memory for the global.
503 GA = new char[getTargetData().getTypeSize(ElTy)];
504 addGlobalMapping(GV, GA);
507 InitializeMemory(GV->getInitializer(), GA);
508 NumInitBytes += getTargetData().getTypeSize(ElTy);