d25abfb63f7d9f770d1aa73b8a03869801ae3c92
[oota-llvm.git] / lib / ExecutionEngine / ExecutionEngine.cpp
1 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
2 // 
3 // This file defines the common interface used by the various execution engine
4 // subclasses.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #define DEBUG_TYPE "jit"
9 #include "Interpreter/Interpreter.h"
10 #include "JIT/VM.h"
11 #include "llvm/Constants.h"
12 #include "llvm/DerivedTypes.h"
13 #include "llvm/Module.h"
14 #include "llvm/ModuleProvider.h"
15 #include "llvm/ExecutionEngine/ExecutionEngine.h"
16 #include "llvm/ExecutionEngine/GenericValue.h"
17 #include "llvm/Target/TargetData.h"
18 #include "Support/Debug.h"
19 #include "Support/Statistic.h"
20 #include "Support/DynamicLinker.h"
21 #include "Config/dlfcn.h"
22
23 Statistic<> NumInitBytes("lli", "Number of bytes of global vars initialized");
24
25 ExecutionEngine::ExecutionEngine(ModuleProvider *P) : 
26   CurMod(*P->getModule()), MP(P) {
27   assert(P && "ModuleProvider is null?");
28 }
29
30 ExecutionEngine::ExecutionEngine(Module *M) : CurMod(*M), MP(0) {
31   assert(M && "Module is null?");
32 }
33
34 ExecutionEngine::~ExecutionEngine() {
35   delete MP;
36 }
37
38 /// If possible, create a JIT, unless the caller specifically requests an
39 /// Interpreter or there's an error. If even an Interpreter cannot be created,
40 /// NULL is returned. 
41 ///
42 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP, 
43                                          bool ForceInterpreter,
44                                          bool TraceMode) {
45   ExecutionEngine *EE = 0;
46
47   // If there is nothing that is forcing us to use the interpreter, make a JIT.
48   if (!ForceInterpreter && !TraceMode)
49     EE = VM::create(MP);
50
51   // If we can't make a JIT, make an interpreter instead.
52   try {
53     if (EE == 0)
54       EE = Interpreter::create(MP->materializeModule(), TraceMode);
55   } catch (...) {
56     EE = 0;
57   }
58   return EE;
59 }
60
61 /// getPointerToGlobal - This returns the address of the specified global
62 /// value.  This may involve code generation if it's a function.
63 ///
64 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
65   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
66     return getPointerToFunction(F);
67
68   assert(GlobalAddress[GV] && "Global hasn't had an address allocated yet?");
69   return GlobalAddress[GV];
70 }
71
72 /// FIXME: document
73 /// 
74 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
75   GenericValue Result;
76
77   if (ConstantExpr *CE = const_cast<ConstantExpr*>(dyn_cast<ConstantExpr>(C))) {
78     switch (CE->getOpcode()) {
79     case Instruction::GetElementPtr: {
80       Result = getConstantValue(CE->getOperand(0));
81       std::vector<Value*> Indexes(CE->op_begin()+1, CE->op_end());
82       uint64_t Offset =
83         TD->getIndexedOffset(CE->getOperand(0)->getType(), Indexes);
84                              
85       Result.LongVal += Offset;
86       return Result;
87     }
88     case Instruction::Cast: {
89       // We only need to handle a few cases here.  Almost all casts will
90       // automatically fold, just the ones involving pointers won't.
91       //
92       Constant *Op = CE->getOperand(0);
93
94       // Handle cast of pointer to pointer...
95       if (Op->getType()->getPrimitiveID() == C->getType()->getPrimitiveID())
96         return getConstantValue(Op);
97
98       // Handle a cast of pointer to any integral type...
99       if (isa<PointerType>(Op->getType()) && C->getType()->isIntegral())
100         return getConstantValue(Op);
101         
102       // Handle cast of long to pointer...
103       if (isa<PointerType>(C->getType()) && (Op->getType() == Type::LongTy ||
104                                              Op->getType() == Type::ULongTy))
105         return getConstantValue(Op);
106       break;
107     }
108
109     case Instruction::Add:
110       if (CE->getOperand(0)->getType() == Type::LongTy ||
111           CE->getOperand(0)->getType() == Type::ULongTy)
112         Result.LongVal = getConstantValue(CE->getOperand(0)).LongVal +
113                          getConstantValue(CE->getOperand(1)).LongVal;
114       else
115         break;
116       return Result;
117
118     default:
119       break;
120     }
121     std::cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
122     abort();
123   }
124   
125   switch (C->getType()->getPrimitiveID()) {
126 #define GET_CONST_VAL(TY, CLASS) \
127   case Type::TY##TyID: Result.TY##Val = cast<CLASS>(C)->getValue(); break
128     GET_CONST_VAL(Bool   , ConstantBool);
129     GET_CONST_VAL(UByte  , ConstantUInt);
130     GET_CONST_VAL(SByte  , ConstantSInt);
131     GET_CONST_VAL(UShort , ConstantUInt);
132     GET_CONST_VAL(Short  , ConstantSInt);
133     GET_CONST_VAL(UInt   , ConstantUInt);
134     GET_CONST_VAL(Int    , ConstantSInt);
135     GET_CONST_VAL(ULong  , ConstantUInt);
136     GET_CONST_VAL(Long   , ConstantSInt);
137     GET_CONST_VAL(Float  , ConstantFP);
138     GET_CONST_VAL(Double , ConstantFP);
139 #undef GET_CONST_VAL
140   case Type::PointerTyID:
141     if (isa<ConstantPointerNull>(C)) {
142       Result.PointerVal = 0;
143     } else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)){
144       Result = PTOGV(getPointerToGlobal(CPR->getValue()));
145
146     } else {
147       assert(0 && "Unknown constant pointer type!");
148     }
149     break;
150   default:
151     std::cout << "ERROR: Constant unimp for type: " << C->getType() << "\n";
152     abort();
153   }
154   return Result;
155 }
156
157 /// FIXME: document
158 ///
159 void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
160                                          const Type *Ty) {
161   if (getTargetData().isLittleEndian()) {
162     switch (Ty->getPrimitiveID()) {
163     case Type::BoolTyID:
164     case Type::UByteTyID:
165     case Type::SByteTyID:   Ptr->Untyped[0] = Val.UByteVal; break;
166     case Type::UShortTyID:
167     case Type::ShortTyID:   Ptr->Untyped[0] = Val.UShortVal & 255;
168                             Ptr->Untyped[1] = (Val.UShortVal >> 8) & 255;
169                             break;
170     Store4BytesLittleEndian:
171     case Type::FloatTyID:
172     case Type::UIntTyID:
173     case Type::IntTyID:     Ptr->Untyped[0] =  Val.UIntVal        & 255;
174                             Ptr->Untyped[1] = (Val.UIntVal >>  8) & 255;
175                             Ptr->Untyped[2] = (Val.UIntVal >> 16) & 255;
176                             Ptr->Untyped[3] = (Val.UIntVal >> 24) & 255;
177                             break;
178     case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
179                               goto Store4BytesLittleEndian;
180     case Type::DoubleTyID:
181     case Type::ULongTyID:
182     case Type::LongTyID:    Ptr->Untyped[0] =  Val.ULongVal        & 255;
183                             Ptr->Untyped[1] = (Val.ULongVal >>  8) & 255;
184                             Ptr->Untyped[2] = (Val.ULongVal >> 16) & 255;
185                             Ptr->Untyped[3] = (Val.ULongVal >> 24) & 255;
186                             Ptr->Untyped[4] = (Val.ULongVal >> 32) & 255;
187                             Ptr->Untyped[5] = (Val.ULongVal >> 40) & 255;
188                             Ptr->Untyped[6] = (Val.ULongVal >> 48) & 255;
189                             Ptr->Untyped[7] = (Val.ULongVal >> 56) & 255;
190                             break;
191     default:
192       std::cout << "Cannot store value of type " << Ty << "!\n";
193     }
194   } else {
195     switch (Ty->getPrimitiveID()) {
196     case Type::BoolTyID:
197     case Type::UByteTyID:
198     case Type::SByteTyID:   Ptr->Untyped[0] = Val.UByteVal; break;
199     case Type::UShortTyID:
200     case Type::ShortTyID:   Ptr->Untyped[1] = Val.UShortVal & 255;
201                             Ptr->Untyped[0] = (Val.UShortVal >> 8) & 255;
202                             break;
203     Store4BytesBigEndian:
204     case Type::FloatTyID:
205     case Type::UIntTyID:
206     case Type::IntTyID:     Ptr->Untyped[3] =  Val.UIntVal        & 255;
207                             Ptr->Untyped[2] = (Val.UIntVal >>  8) & 255;
208                             Ptr->Untyped[1] = (Val.UIntVal >> 16) & 255;
209                             Ptr->Untyped[0] = (Val.UIntVal >> 24) & 255;
210                             break;
211     case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
212                               goto Store4BytesBigEndian;
213     case Type::DoubleTyID:
214     case Type::ULongTyID:
215     case Type::LongTyID:    Ptr->Untyped[7] =  Val.ULongVal        & 255;
216                             Ptr->Untyped[6] = (Val.ULongVal >>  8) & 255;
217                             Ptr->Untyped[5] = (Val.ULongVal >> 16) & 255;
218                             Ptr->Untyped[4] = (Val.ULongVal >> 24) & 255;
219                             Ptr->Untyped[3] = (Val.ULongVal >> 32) & 255;
220                             Ptr->Untyped[2] = (Val.ULongVal >> 40) & 255;
221                             Ptr->Untyped[1] = (Val.ULongVal >> 48) & 255;
222                             Ptr->Untyped[0] = (Val.ULongVal >> 56) & 255;
223                             break;
224     default:
225       std::cout << "Cannot store value of type " << Ty << "!\n";
226     }
227   }
228 }
229
230 /// FIXME: document
231 ///
232 GenericValue ExecutionEngine::LoadValueFromMemory(GenericValue *Ptr,
233                                                   const Type *Ty) {
234   GenericValue Result;
235   if (getTargetData().isLittleEndian()) {
236     switch (Ty->getPrimitiveID()) {
237     case Type::BoolTyID:
238     case Type::UByteTyID:
239     case Type::SByteTyID:   Result.UByteVal = Ptr->Untyped[0]; break;
240     case Type::UShortTyID:
241     case Type::ShortTyID:   Result.UShortVal = (unsigned)Ptr->Untyped[0] |
242                                               ((unsigned)Ptr->Untyped[1] << 8);
243                             break;
244     Load4BytesLittleEndian:                            
245     case Type::FloatTyID:
246     case Type::UIntTyID:
247     case Type::IntTyID:     Result.UIntVal = (unsigned)Ptr->Untyped[0] |
248                                             ((unsigned)Ptr->Untyped[1] <<  8) |
249                                             ((unsigned)Ptr->Untyped[2] << 16) |
250                                             ((unsigned)Ptr->Untyped[3] << 24);
251                             break;
252     case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
253                               goto Load4BytesLittleEndian;
254     case Type::DoubleTyID:
255     case Type::ULongTyID:
256     case Type::LongTyID:    Result.ULongVal = (uint64_t)Ptr->Untyped[0] |
257                                              ((uint64_t)Ptr->Untyped[1] <<  8) |
258                                              ((uint64_t)Ptr->Untyped[2] << 16) |
259                                              ((uint64_t)Ptr->Untyped[3] << 24) |
260                                              ((uint64_t)Ptr->Untyped[4] << 32) |
261                                              ((uint64_t)Ptr->Untyped[5] << 40) |
262                                              ((uint64_t)Ptr->Untyped[6] << 48) |
263                                              ((uint64_t)Ptr->Untyped[7] << 56);
264                             break;
265     default:
266       std::cout << "Cannot load value of type " << *Ty << "!\n";
267       abort();
268     }
269   } else {
270     switch (Ty->getPrimitiveID()) {
271     case Type::BoolTyID:
272     case Type::UByteTyID:
273     case Type::SByteTyID:   Result.UByteVal = Ptr->Untyped[0]; break;
274     case Type::UShortTyID:
275     case Type::ShortTyID:   Result.UShortVal = (unsigned)Ptr->Untyped[1] |
276                                               ((unsigned)Ptr->Untyped[0] << 8);
277                             break;
278     Load4BytesBigEndian:
279     case Type::FloatTyID:
280     case Type::UIntTyID:
281     case Type::IntTyID:     Result.UIntVal = (unsigned)Ptr->Untyped[3] |
282                                             ((unsigned)Ptr->Untyped[2] <<  8) |
283                                             ((unsigned)Ptr->Untyped[1] << 16) |
284                                             ((unsigned)Ptr->Untyped[0] << 24);
285                             break;
286     case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
287                               goto Load4BytesBigEndian;
288     case Type::DoubleTyID:
289     case Type::ULongTyID:
290     case Type::LongTyID:    Result.ULongVal = (uint64_t)Ptr->Untyped[7] |
291                                              ((uint64_t)Ptr->Untyped[6] <<  8) |
292                                              ((uint64_t)Ptr->Untyped[5] << 16) |
293                                              ((uint64_t)Ptr->Untyped[4] << 24) |
294                                              ((uint64_t)Ptr->Untyped[3] << 32) |
295                                              ((uint64_t)Ptr->Untyped[2] << 40) |
296                                              ((uint64_t)Ptr->Untyped[1] << 48) |
297                                              ((uint64_t)Ptr->Untyped[0] << 56);
298                             break;
299     default:
300       std::cout << "Cannot load value of type " << *Ty << "!\n";
301       abort();
302     }
303   }
304   return Result;
305 }
306
307 // InitializeMemory - Recursive function to apply a Constant value into the
308 // specified memory location...
309 //
310 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
311   if (Init->getType()->isFirstClassType()) {
312     GenericValue Val = getConstantValue(Init);
313     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
314     return;
315   }
316
317   switch (Init->getType()->getPrimitiveID()) {
318   case Type::ArrayTyID: {
319     const ConstantArray *CPA = cast<ConstantArray>(Init);
320     const std::vector<Use> &Val = CPA->getValues();
321     unsigned ElementSize = 
322       getTargetData().getTypeSize(cast<ArrayType>(CPA->getType())->getElementType());
323     for (unsigned i = 0; i < Val.size(); ++i)
324       InitializeMemory(cast<Constant>(Val[i].get()), (char*)Addr+i*ElementSize);
325     return;
326   }
327
328   case Type::StructTyID: {
329     const ConstantStruct *CPS = cast<ConstantStruct>(Init);
330     const StructLayout *SL =
331       getTargetData().getStructLayout(cast<StructType>(CPS->getType()));
332     const std::vector<Use> &Val = CPS->getValues();
333     for (unsigned i = 0; i < Val.size(); ++i)
334       InitializeMemory(cast<Constant>(Val[i].get()),
335                        (char*)Addr+SL->MemberOffsets[i]);
336     return;
337   }
338
339   default:
340     std::cerr << "Bad Type: " << Init->getType() << "\n";
341     assert(0 && "Unknown constant type to initialize memory with!");
342   }
343 }
344
345 /// EmitGlobals - Emit all of the global variables to memory, storing their
346 /// addresses into GlobalAddress.  This must make sure to copy the contents of
347 /// their initializers into the memory.
348 ///
349 void ExecutionEngine::emitGlobals() {
350   const TargetData &TD = getTargetData();
351   
352   // Loop over all of the global variables in the program, allocating the memory
353   // to hold them.
354   for (Module::giterator I = getModule().gbegin(), E = getModule().gend();
355        I != E; ++I)
356     if (!I->isExternal()) {
357       // Get the type of the global...
358       const Type *Ty = I->getType()->getElementType();
359       
360       // Allocate some memory for it!
361       unsigned Size = TD.getTypeSize(Ty);
362       GlobalAddress[I] = new char[Size];
363       NumInitBytes += Size;
364
365       DEBUG(std::cerr << "Global '" << I->getName() << "' -> "
366                       << (void*)GlobalAddress[I] << "\n");
367     } else {
368       // External variable reference. Try to use the dynamic loader to
369       // get a pointer to it.
370       if (void *SymAddr = GetAddressOfSymbol(I->getName().c_str()))
371         GlobalAddress[I] = SymAddr;
372       else {
373         std::cerr << "Could not resolve external global address: "
374                   << I->getName() << "\n";
375         abort();
376       }
377     }
378   
379   // Now that all of the globals are set up in memory, loop through them all and
380   // initialize their contents.
381   for (Module::giterator I = getModule().gbegin(), E = getModule().gend();
382        I != E; ++I)
383     if (!I->isExternal())
384       InitializeMemory(I->getInitializer(), GlobalAddress[I]);
385 }
386