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