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