Merge Dumper.cpp and AnalyzerWrappers.cpp into this file. Also, adjust the
[oota-llvm.git] / lib / Bytecode / Reader / ReaderInternals.h
1 //===-- ReaderInternals.h - Definitions internal to the reader --*- C++ -*-===//
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 header file defines various stuff that is used by the bytecode reader.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef READER_INTERNALS_H
15 #define READER_INTERNALS_H
16
17 #include "ReaderPrimitives.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/ModuleProvider.h"
22 #include <utility>
23 #include <map>
24
25 namespace llvm {
26
27 // Enable to trace to figure out what the heck is going on when parsing fails
28 //#define TRACE_LEVEL 10
29 //#define DEBUG_OUTPUT
30
31 #if TRACE_LEVEL    // ByteCodeReading_TRACEr
32 #define BCR_TRACE(n, X) \
33     if (n < TRACE_LEVEL) std::cerr << std::string(n*2, ' ') << X
34 #else
35 #define BCR_TRACE(n, X)
36 #endif
37
38 struct LazyFunctionInfo {
39   const unsigned char *Buf, *EndBuf;
40   LazyFunctionInfo(const unsigned char *B = 0, const unsigned char *EB = 0)
41     : Buf(B), EndBuf(EB) {}
42 };
43
44 class BytecodeParser : public ModuleProvider {
45   BytecodeParser(const BytecodeParser &);  // DO NOT IMPLEMENT
46   void operator=(const BytecodeParser &);  // DO NOT IMPLEMENT
47 public:
48   BytecodeParser() {}
49   
50   ~BytecodeParser() {
51     freeState();
52   }
53   void freeState() {
54     freeTable(Values);
55     freeTable(ModuleValues);
56   }
57
58   Module* materializeModule() {
59     while (! LazyFunctionLoadMap.empty()) {
60       std::map<Function*, LazyFunctionInfo>::iterator i = 
61         LazyFunctionLoadMap.begin();
62       materializeFunction((*i).first);
63     }
64
65     return TheModule;
66   }
67
68   Module* releaseModule() {
69     // Since we're losing control of this Module, we must hand it back complete
70     Module *M = ModuleProvider::releaseModule();
71     freeState();
72     return M;
73   }
74
75   void ParseBytecode(const unsigned char *Buf, unsigned Length,
76                      const std::string &ModuleID);
77
78   void dump() const {
79     std::cerr << "BytecodeParser instance!\n";
80   }
81
82 private:
83   struct ValueList : public User {
84     ValueList() : User(Type::TypeTy, Value::TypeVal) {}
85
86     // vector compatibility methods
87     unsigned size() const { return getNumOperands(); }
88     void push_back(Value *V) { Operands.push_back(Use(V, this)); }
89     Value *back() const { return Operands.back(); }
90     void pop_back() { Operands.pop_back(); }
91     bool empty() const { return Operands.empty(); }
92
93     virtual void print(std::ostream& OS) const {
94       OS << "Bytecode Reader UseHandle!";
95     }
96   };
97
98   // Information about the module, extracted from the bytecode revision number.
99   unsigned char RevisionNum;        // The rev # itself
100
101   // Flags to distinguish LLVM 1.0 & 1.1 bytecode formats (revision #0)
102
103   // Revision #0 had an explicit alignment of data only for the ModuleGlobalInfo
104   // block.  This was fixed to be like all other blocks in 1.2
105   bool hasInconsistentModuleGlobalInfo;
106
107   // Revision #0 also explicitly encoded zero values for primitive types like
108   // int/sbyte/etc.
109   bool hasExplicitPrimitiveZeros;
110
111   // Flags to control features specific the LLVM 1.2 and before (revision #1)
112
113   // LLVM 1.2 and earlier required that getelementptr structure indices were
114   // ubyte constants and that sequential type indices were longs.
115   bool hasRestrictedGEPTypes;
116
117
118   typedef std::vector<ValueList*> ValueTable;
119   ValueTable Values;
120   ValueTable ModuleValues;
121   std::map<std::pair<unsigned,unsigned>, Value*> ForwardReferences;
122
123   /// CompactionTable - If a compaction table is active in the current function,
124   /// this is the mapping that it contains.
125   std::vector<std::vector<Value*> > CompactionTable;
126
127   std::vector<BasicBlock*> ParsedBasicBlocks;
128
129   // ConstantFwdRefs - This maintains a mapping between <Type, Slot #>'s and
130   // forward references to constants.  Such values may be referenced before they
131   // are defined, and if so, the temporary object that they represent is held
132   // here.
133   //
134   typedef std::map<std::pair<const Type*,unsigned>, Constant*> ConstantRefsType;
135   ConstantRefsType ConstantFwdRefs;
136
137   // TypesLoaded - This vector mirrors the Values[TypeTyID] plane.  It is used
138   // to deal with forward references to types.
139   //
140   typedef std::vector<PATypeHolder> TypeValuesListTy;
141   TypeValuesListTy ModuleTypeValues;
142   TypeValuesListTy FunctionTypeValues;
143
144   // When the ModuleGlobalInfo section is read, we create a function object for
145   // each function in the module.  When the function is loaded, this function is
146   // filled in.
147   //
148   std::vector<Function*> FunctionSignatureList;
149
150   // Constant values are read in after global variables.  Because of this, we
151   // must defer setting the initializers on global variables until after module
152   // level constants have been read.  In the mean time, this list keeps track of
153   // what we must do.
154   //
155   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
156
157   // For lazy reading-in of functions, we need to save away several pieces of
158   // information about each function: its begin and end pointer in the buffer
159   // and its FunctionSlot.
160   // 
161   std::map<Function*, LazyFunctionInfo> LazyFunctionLoadMap;
162   
163 private:
164   void freeTable(ValueTable &Tab) {
165     while (!Tab.empty()) {
166       delete Tab.back();
167       Tab.pop_back();
168     }
169   }
170
171   /// getGlobalTableType - This is just like getType, but when a compaction
172   /// table is in use, it is ignored.  Also, no forward references or other
173   /// fancy features are supported.
174   const Type *getGlobalTableType(unsigned Slot) {
175     if (Slot < Type::FirstDerivedTyID) {
176       const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
177       assert(Ty && "Not a primitive type ID?");
178       return Ty;
179     }
180     Slot -= Type::FirstDerivedTyID;
181     if (Slot >= ModuleTypeValues.size())
182       throw std::string("Illegal compaction table type reference!");
183     return ModuleTypeValues[Slot];
184   }
185
186   unsigned getGlobalTableTypeSlot(const Type *Ty) {
187     if (Ty->isPrimitiveType())
188       return Ty->getTypeID();
189     TypeValuesListTy::iterator I = find(ModuleTypeValues.begin(),
190                                         ModuleTypeValues.end(), Ty);
191     if (I == ModuleTypeValues.end())
192       throw std::string("Didn't find type in ModuleTypeValues.");
193     return Type::FirstDerivedTyID + (&*I - &ModuleTypeValues[0]);
194   }
195
196   /// getGlobalTableValue - This is just like getValue, but when a compaction
197   /// table is in use, it is ignored.  Also, no forward references or other
198   /// fancy features are supported.
199   Value *getGlobalTableValue(const Type *Ty, unsigned SlotNo) {
200     // FIXME: getTypeSlot is inefficient!
201     unsigned TyID = getGlobalTableTypeSlot(Ty);
202     
203     if (TyID != Type::LabelTyID) {
204       if (SlotNo == 0)
205         return Constant::getNullValue(Ty);
206       --SlotNo;
207     }
208
209     if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
210         SlotNo >= ModuleValues[TyID]->getNumOperands()) {
211       std::cerr << TyID << ", " << SlotNo << ": " << ModuleValues.size() << ", "
212                 << (void*)ModuleValues[TyID] << ", "
213                 << ModuleValues[TyID]->getNumOperands() << "\n";
214       throw std::string("Corrupt compaction table entry!");
215     }
216     return ModuleValues[TyID]->getOperand(SlotNo);
217   }
218
219 public:
220   void ParseModule(const unsigned char * Buf, const unsigned char *End);
221   void materializeFunction(Function *F);
222
223 private:
224   void ParseVersionInfo   (const unsigned char *&Buf, const unsigned char *End);
225   void ParseModuleGlobalInfo(const unsigned char *&Buf, const unsigned char *E);
226   void ParseSymbolTable(const unsigned char *&Buf, const unsigned char *End,
227                         SymbolTable *, Function *CurrentFunction);
228   void ParseFunction(const unsigned char *&Buf, const unsigned char *End);
229   void ParseCompactionTable(const unsigned char *&Buf,const unsigned char *End);
230   void ParseGlobalTypes(const unsigned char *&Buf, const unsigned char *EndBuf);
231
232   BasicBlock *ParseBasicBlock(const unsigned char *&Buf,
233                               const unsigned char *End,
234                               unsigned BlockNo);
235   unsigned ParseInstructionList(Function *F, const unsigned char *&Buf,
236                                 const unsigned char *EndBuf);
237   
238   void ParseInstruction(const unsigned char *&Buf, const unsigned char *End,
239                         std::vector<unsigned> &Args, BasicBlock *BB);
240
241   void ParseConstantPool(const unsigned char *&Buf, const unsigned char *EndBuf,
242                          ValueTable &Tab, TypeValuesListTy &TypeTab);
243   Constant *parseConstantValue(const unsigned char *&Buf,
244                                const unsigned char *End,
245                                unsigned TypeID);
246   void parseTypeConstants(const unsigned char *&Buf,
247                           const unsigned char *EndBuf,
248                           TypeValuesListTy &Tab, unsigned NumEntries);
249   const Type *parseTypeConstant(const unsigned char *&Buf,
250                                 const unsigned char *EndBuf);
251   void parseStringConstants(const unsigned char *&Buf,
252                             const unsigned char *EndBuf,
253                             unsigned NumEntries, ValueTable &Tab);
254
255   Value      *getValue(unsigned TypeID, unsigned num, bool Create = true);
256   const Type *getType(unsigned ID);
257   BasicBlock *getBasicBlock(unsigned ID);
258   Constant   *getConstantValue(unsigned TypeID, unsigned num);
259   Constant   *getConstantValue(const Type *Ty, unsigned num) {
260     return getConstantValue(getTypeSlot(Ty), num);
261   }
262
263   unsigned insertValue(Value *V, unsigned Type, ValueTable &Table);
264
265   unsigned getTypeSlot(const Type *Ty);
266
267   // resolve all references to the placeholder (if any) for the given constant
268   void ResolveReferencesToConstant(Constant *C, unsigned Slot);
269 };
270
271 template<class SuperType>
272 class PlaceholderDef : public SuperType {
273   unsigned ID;
274   PlaceholderDef();                       // DO NOT IMPLEMENT
275   void operator=(const PlaceholderDef &); // DO NOT IMPLEMENT
276 public:
277   PlaceholderDef(const Type *Ty, unsigned id) : SuperType(Ty), ID(id) {}
278   unsigned getID() { return ID; }
279 };
280
281 struct ConstantPlaceHolderHelper : public ConstantExpr {
282   ConstantPlaceHolderHelper(const Type *Ty)
283     : ConstantExpr(Instruction::UserOp1, Constant::getNullValue(Ty), Ty) {}
284 };
285
286 typedef PlaceholderDef<ConstantPlaceHolderHelper>  ConstPHolder;
287
288 static inline void readBlock(const unsigned char *&Buf,
289                              const unsigned char *EndBuf, 
290                              unsigned &Type, unsigned &Size) {
291   Type = read(Buf, EndBuf);
292   Size = read(Buf, EndBuf);
293 }
294
295 } // End llvm namespace
296
297 #endif