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