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