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