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