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