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/ExecutionEngine/ExecutionEngine.h"
23 #include "llvm/ExecutionEngine/GenericValue.h"
24 #include "llvm/Target/TargetData.h"
25 #include "Support/Debug.h"
26 #include "Support/Statistic.h"
27 #include "Support/DynamicLinker.h"
28 #include "Config/dlfcn.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() {
50 // CreateArgv - Turn a vector of strings into a nice argv style array of
51 // pointers to null terminated strings.
53 static void *CreateArgv(ExecutionEngine *EE,
54 const std::vector<std::string> &InputArgv) {
55 unsigned PtrSize = EE->getTargetData().getPointerSize();
56 char *Result = new char[(InputArgv.size()+1)*PtrSize];
58 DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n");
59 const Type *SBytePtr = PointerType::get(Type::SByteTy);
61 for (unsigned i = 0; i != InputArgv.size(); ++i) {
62 unsigned Size = InputArgv[i].size()+1;
63 char *Dest = new char[Size];
64 DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n");
66 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
69 // Endian safe: Result[i] = (PointerTy)Dest;
70 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
75 EE->StoreValueToMemory(PTOGV(0),
76 (GenericValue*)(Result+InputArgv.size()*PtrSize),
81 /// runFunctionAsMain - This is a helper function which wraps runFunction to
82 /// handle the common task of starting up main with the specified argc, argv,
83 /// and envp parameters.
84 int ExecutionEngine::runFunctionAsMain(Function *Fn,
85 const std::vector<std::string> &argv,
86 const char * const * envp) {
87 std::vector<GenericValue> GVArgs;
89 GVArgc.IntVal = argv.size();
90 GVArgs.push_back(GVArgc); // Arg #0 = argc.
91 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
92 assert(((char **)GVTOP(GVArgs[1]))[0] && "argv[0] was null after CreateArgv");
94 std::vector<std::string> EnvVars;
95 for (unsigned i = 0; envp[i]; ++i)
96 EnvVars.push_back(envp[i]);
97 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
98 return runFunction(Fn, GVArgs).IntVal;
103 /// If possible, create a JIT, unless the caller specifically requests an
104 /// Interpreter or there's an error. If even an Interpreter cannot be created,
105 /// NULL is returned.
107 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
108 bool ForceInterpreter) {
109 ExecutionEngine *EE = 0;
111 // Unless the interpreter was explicitly selected, make a JIT.
112 if (!ForceInterpreter)
113 EE = JIT::create(MP);
115 // If we can't make a JIT, make an interpreter instead.
118 EE = Interpreter::create(MP->materializeModule());
125 /// getPointerToGlobal - This returns the address of the specified global
126 /// value. This may involve code generation if it's a function.
128 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
129 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
130 return getPointerToFunction(F);
132 assert(GlobalAddress[GV] && "Global hasn't had an address allocated yet?");
133 return GlobalAddress[GV];
138 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
141 if (ConstantExpr *CE = const_cast<ConstantExpr*>(dyn_cast<ConstantExpr>(C))) {
142 switch (CE->getOpcode()) {
143 case Instruction::GetElementPtr: {
144 Result = getConstantValue(CE->getOperand(0));
145 std::vector<Value*> Indexes(CE->op_begin()+1, CE->op_end());
147 TD->getIndexedOffset(CE->getOperand(0)->getType(), Indexes);
149 Result.LongVal += Offset;
152 case Instruction::Cast: {
153 // We only need to handle a few cases here. Almost all casts will
154 // automatically fold, just the ones involving pointers won't.
156 Constant *Op = CE->getOperand(0);
158 // Handle cast of pointer to pointer...
159 if (Op->getType()->getPrimitiveID() == C->getType()->getPrimitiveID())
160 return getConstantValue(Op);
162 // Handle a cast of pointer to any integral type...
163 if (isa<PointerType>(Op->getType()) && C->getType()->isIntegral())
164 return getConstantValue(Op);
166 // Handle cast of long to pointer...
167 if (isa<PointerType>(C->getType()) && (Op->getType() == Type::LongTy ||
168 Op->getType() == Type::ULongTy))
169 return getConstantValue(Op);
173 case Instruction::Add:
174 if (CE->getOperand(0)->getType() == Type::LongTy ||
175 CE->getOperand(0)->getType() == Type::ULongTy)
176 Result.LongVal = getConstantValue(CE->getOperand(0)).LongVal +
177 getConstantValue(CE->getOperand(1)).LongVal;
185 std::cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
189 switch (C->getType()->getPrimitiveID()) {
190 #define GET_CONST_VAL(TY, CLASS) \
191 case Type::TY##TyID: Result.TY##Val = cast<CLASS>(C)->getValue(); break
192 GET_CONST_VAL(Bool , ConstantBool);
193 GET_CONST_VAL(UByte , ConstantUInt);
194 GET_CONST_VAL(SByte , ConstantSInt);
195 GET_CONST_VAL(UShort , ConstantUInt);
196 GET_CONST_VAL(Short , ConstantSInt);
197 GET_CONST_VAL(UInt , ConstantUInt);
198 GET_CONST_VAL(Int , ConstantSInt);
199 GET_CONST_VAL(ULong , ConstantUInt);
200 GET_CONST_VAL(Long , ConstantSInt);
201 GET_CONST_VAL(Float , ConstantFP);
202 GET_CONST_VAL(Double , ConstantFP);
204 case Type::PointerTyID:
205 if (isa<ConstantPointerNull>(C)) {
206 Result.PointerVal = 0;
207 } else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)){
209 const_cast<Function*>(dyn_cast<Function>(CPR->getValue())))
210 Result = PTOGV(getPointerToFunctionOrStub(F));
212 Result = PTOGV(getOrEmitGlobalVariable(
213 cast<GlobalVariable>(CPR->getValue())));
216 assert(0 && "Unknown constant pointer type!");
220 std::cout << "ERROR: Constant unimp for type: " << C->getType() << "\n";
228 void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
230 if (getTargetData().isLittleEndian()) {
231 switch (Ty->getPrimitiveID()) {
233 case Type::UByteTyID:
234 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
235 case Type::UShortTyID:
236 case Type::ShortTyID: Ptr->Untyped[0] = Val.UShortVal & 255;
237 Ptr->Untyped[1] = (Val.UShortVal >> 8) & 255;
239 Store4BytesLittleEndian:
240 case Type::FloatTyID:
242 case Type::IntTyID: Ptr->Untyped[0] = Val.UIntVal & 255;
243 Ptr->Untyped[1] = (Val.UIntVal >> 8) & 255;
244 Ptr->Untyped[2] = (Val.UIntVal >> 16) & 255;
245 Ptr->Untyped[3] = (Val.UIntVal >> 24) & 255;
247 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
248 goto Store4BytesLittleEndian;
249 case Type::DoubleTyID:
250 case Type::ULongTyID:
251 case Type::LongTyID: Ptr->Untyped[0] = Val.ULongVal & 255;
252 Ptr->Untyped[1] = (Val.ULongVal >> 8) & 255;
253 Ptr->Untyped[2] = (Val.ULongVal >> 16) & 255;
254 Ptr->Untyped[3] = (Val.ULongVal >> 24) & 255;
255 Ptr->Untyped[4] = (Val.ULongVal >> 32) & 255;
256 Ptr->Untyped[5] = (Val.ULongVal >> 40) & 255;
257 Ptr->Untyped[6] = (Val.ULongVal >> 48) & 255;
258 Ptr->Untyped[7] = (Val.ULongVal >> 56) & 255;
261 std::cout << "Cannot store value of type " << Ty << "!\n";
264 switch (Ty->getPrimitiveID()) {
266 case Type::UByteTyID:
267 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
268 case Type::UShortTyID:
269 case Type::ShortTyID: Ptr->Untyped[1] = Val.UShortVal & 255;
270 Ptr->Untyped[0] = (Val.UShortVal >> 8) & 255;
272 Store4BytesBigEndian:
273 case Type::FloatTyID:
275 case Type::IntTyID: Ptr->Untyped[3] = Val.UIntVal & 255;
276 Ptr->Untyped[2] = (Val.UIntVal >> 8) & 255;
277 Ptr->Untyped[1] = (Val.UIntVal >> 16) & 255;
278 Ptr->Untyped[0] = (Val.UIntVal >> 24) & 255;
280 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
281 goto Store4BytesBigEndian;
282 case Type::DoubleTyID:
283 case Type::ULongTyID:
284 case Type::LongTyID: Ptr->Untyped[7] = Val.ULongVal & 255;
285 Ptr->Untyped[6] = (Val.ULongVal >> 8) & 255;
286 Ptr->Untyped[5] = (Val.ULongVal >> 16) & 255;
287 Ptr->Untyped[4] = (Val.ULongVal >> 24) & 255;
288 Ptr->Untyped[3] = (Val.ULongVal >> 32) & 255;
289 Ptr->Untyped[2] = (Val.ULongVal >> 40) & 255;
290 Ptr->Untyped[1] = (Val.ULongVal >> 48) & 255;
291 Ptr->Untyped[0] = (Val.ULongVal >> 56) & 255;
294 std::cout << "Cannot store value of type " << Ty << "!\n";
301 GenericValue ExecutionEngine::LoadValueFromMemory(GenericValue *Ptr,
304 if (getTargetData().isLittleEndian()) {
305 switch (Ty->getPrimitiveID()) {
307 case Type::UByteTyID:
308 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
309 case Type::UShortTyID:
310 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[0] |
311 ((unsigned)Ptr->Untyped[1] << 8);
313 Load4BytesLittleEndian:
314 case Type::FloatTyID:
316 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[0] |
317 ((unsigned)Ptr->Untyped[1] << 8) |
318 ((unsigned)Ptr->Untyped[2] << 16) |
319 ((unsigned)Ptr->Untyped[3] << 24);
321 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
322 goto Load4BytesLittleEndian;
323 case Type::DoubleTyID:
324 case Type::ULongTyID:
325 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[0] |
326 ((uint64_t)Ptr->Untyped[1] << 8) |
327 ((uint64_t)Ptr->Untyped[2] << 16) |
328 ((uint64_t)Ptr->Untyped[3] << 24) |
329 ((uint64_t)Ptr->Untyped[4] << 32) |
330 ((uint64_t)Ptr->Untyped[5] << 40) |
331 ((uint64_t)Ptr->Untyped[6] << 48) |
332 ((uint64_t)Ptr->Untyped[7] << 56);
335 std::cout << "Cannot load value of type " << *Ty << "!\n";
339 switch (Ty->getPrimitiveID()) {
341 case Type::UByteTyID:
342 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
343 case Type::UShortTyID:
344 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[1] |
345 ((unsigned)Ptr->Untyped[0] << 8);
348 case Type::FloatTyID:
350 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[3] |
351 ((unsigned)Ptr->Untyped[2] << 8) |
352 ((unsigned)Ptr->Untyped[1] << 16) |
353 ((unsigned)Ptr->Untyped[0] << 24);
355 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
356 goto Load4BytesBigEndian;
357 case Type::DoubleTyID:
358 case Type::ULongTyID:
359 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[7] |
360 ((uint64_t)Ptr->Untyped[6] << 8) |
361 ((uint64_t)Ptr->Untyped[5] << 16) |
362 ((uint64_t)Ptr->Untyped[4] << 24) |
363 ((uint64_t)Ptr->Untyped[3] << 32) |
364 ((uint64_t)Ptr->Untyped[2] << 40) |
365 ((uint64_t)Ptr->Untyped[1] << 48) |
366 ((uint64_t)Ptr->Untyped[0] << 56);
369 std::cout << "Cannot load value of type " << *Ty << "!\n";
376 // InitializeMemory - Recursive function to apply a Constant value into the
377 // specified memory location...
379 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
380 if (Init->getType()->isFirstClassType()) {
381 GenericValue Val = getConstantValue(Init);
382 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
386 switch (Init->getType()->getPrimitiveID()) {
387 case Type::ArrayTyID: {
388 const ConstantArray *CPA = cast<ConstantArray>(Init);
389 const std::vector<Use> &Val = CPA->getValues();
390 unsigned ElementSize =
391 getTargetData().getTypeSize(cast<ArrayType>(CPA->getType())->getElementType());
392 for (unsigned i = 0; i < Val.size(); ++i)
393 InitializeMemory(cast<Constant>(Val[i].get()), (char*)Addr+i*ElementSize);
397 case Type::StructTyID: {
398 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
399 const StructLayout *SL =
400 getTargetData().getStructLayout(cast<StructType>(CPS->getType()));
401 const std::vector<Use> &Val = CPS->getValues();
402 for (unsigned i = 0; i < Val.size(); ++i)
403 InitializeMemory(cast<Constant>(Val[i].get()),
404 (char*)Addr+SL->MemberOffsets[i]);
409 std::cerr << "Bad Type: " << Init->getType() << "\n";
410 assert(0 && "Unknown constant type to initialize memory with!");
414 /// EmitGlobals - Emit all of the global variables to memory, storing their
415 /// addresses into GlobalAddress. This must make sure to copy the contents of
416 /// their initializers into the memory.
418 void ExecutionEngine::emitGlobals() {
419 const TargetData &TD = getTargetData();
421 // Loop over all of the global variables in the program, allocating the memory
423 for (Module::giterator I = getModule().gbegin(), E = getModule().gend();
425 if (!I->isExternal()) {
426 // Get the type of the global...
427 const Type *Ty = I->getType()->getElementType();
429 // Allocate some memory for it!
430 unsigned Size = TD.getTypeSize(Ty);
431 addGlobalMapping(I, new char[Size]);
433 DEBUG(std::cerr << "Global '" << I->getName() << "' -> "
434 << (void*)GlobalAddress[I] << "\n");
436 // External variable reference. Try to use the dynamic loader to
437 // get a pointer to it.
438 if (void *SymAddr = GetAddressOfSymbol(I->getName().c_str()))
439 GlobalAddress[I] = SymAddr;
441 std::cerr << "Could not resolve external global address: "
442 << I->getName() << "\n";
447 // Now that all of the globals are set up in memory, loop through them all and
448 // initialize their contents.
449 for (Module::giterator I = getModule().gbegin(), E = getModule().gend();
451 if (!I->isExternal())
452 EmitGlobalVariable(I);
455 // EmitGlobalVariable - This method emits the specified global variable to the
456 // address specified in GlobalAddresses, or allocates new memory if it's not
457 // already in the map.
458 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
459 void *&GA = GlobalAddress[GV];
460 const Type *ElTy = GV->getType()->getElementType();
462 // If it's not already specified, allocate memory for the global.
463 GA = new char[getTargetData().getTypeSize(ElTy)];
466 InitializeMemory(GV->getInitializer(), GA);
467 NumInitBytes += getTargetData().getTypeSize(ElTy);