c8b3b3abdd0dd6e84e8b6d84f559d199619f6ecb
[oota-llvm.git] / lib / Bytecode / Reader / ReaderInternals.h
1 //===-- ReaderInternals.h - Definitions internal to the reader --*- C++ -*-===//
2 //
3 //  This header file defines various stuff that is used by the bytecode reader.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #ifndef READER_INTERNALS_H
8 #define READER_INTERNALS_H
9
10 #include "llvm/Constant.h"
11 #include "llvm/DerivedTypes.h"
12 #include "llvm/Function.h"
13 #include "llvm/ModuleProvider.h"
14 #include "llvm/Bytecode/Primitives.h"
15 #include <utility>
16 #include <map>
17
18 // Enable to trace to figure out what the heck is going on when parsing fails
19 //#define TRACE_LEVEL 10
20
21 #if TRACE_LEVEL    // ByteCodeReading_TRACEr
22 #define BCR_TRACE(n, X) \
23     if (n < TRACE_LEVEL) std::cerr << std::string(n*2, ' ') << X
24 #else
25 #define BCR_TRACE(n, X)
26 #endif
27
28 struct LazyFunctionInfo {
29   const unsigned char *Buf, *EndBuf;
30   unsigned FunctionSlot;
31 };
32
33 class BytecodeParser : public ModuleProvider {
34   BytecodeParser(const BytecodeParser &);  // DO NOT IMPLEMENT
35   void operator=(const BytecodeParser &);  // DO NOT IMPLEMENT
36 public:
37   BytecodeParser() {
38     // Define this in case we don't see a ModuleGlobalInfo block.
39     FirstDerivedTyID = Type::FirstDerivedTyID;
40   }
41   
42   ~BytecodeParser() {
43     freeState();
44   }
45   void freeState() {
46     freeTable(Values);
47     freeTable(ModuleValues);
48   }
49
50   Module* releaseModule() {
51     // Since we're losing control of this Module, we must hand it back complete
52     Module *M = ModuleProvider::releaseModule();
53     freeState();
54     return M;
55   }
56
57   void ParseBytecode(const unsigned char *Buf, unsigned Length,
58                      const std::string &ModuleID);
59
60   void dump() const {
61     std::cerr << "BytecodeParser instance!\n";
62   }
63
64 private:
65   struct ValueList : public User {
66     ValueList() : User(Type::TypeTy, Value::TypeVal) {}
67
68     // vector compatibility methods
69     unsigned size() const { return getNumOperands(); }
70     void push_back(Value *V) { Operands.push_back(Use(V, this)); }
71     Value *back() const { return Operands.back(); }
72     void pop_back() { Operands.pop_back(); }
73     bool empty() const { return Operands.empty(); }
74
75     virtual void print(std::ostream& OS) const {
76       OS << "Bytecode Reader UseHandle!";
77     }
78   };
79
80   // Information about the module, extracted from the bytecode revision number.
81   unsigned char RevisionNum;        // The rev # itself
82   unsigned char FirstDerivedTyID;   // First variable index to use for type
83   bool hasInternalMarkerOnly;       // Only types of linkage are intern/external
84   bool hasExtendedLinkageSpecs;     // Supports more than 4 linkage types
85   bool hasOldStyleVarargs;          // Has old version of varargs intrinsics?
86   bool hasVarArgCallPadding;        // Bytecode has extra padding in vararg call
87
88   bool usesOldStyleVarargs;         // Does this module USE old style varargs?
89
90   typedef std::vector<ValueList*> ValueTable;
91   ValueTable Values;
92   ValueTable ModuleValues;
93   std::map<std::pair<unsigned,unsigned>, Value*> ForwardReferences;
94
95   std::vector<BasicBlock*> ParsedBasicBlocks;
96
97   // GlobalRefs - This maintains a mapping between <Type, Slot #>'s and forward
98   // references to global values or constants.  Such values may be referenced
99   // before they are defined, and if so, the temporary object that they
100   // represent is held here.
101   //
102   typedef std::map<std::pair<const Type *, unsigned>, Value*>  GlobalRefsType;
103   GlobalRefsType GlobalRefs;
104
105   // TypesLoaded - This vector mirrors the Values[TypeTyID] plane.  It is used
106   // to deal with forward references to types.
107   //
108   typedef std::vector<PATypeHolder> TypeValuesListTy;
109   TypeValuesListTy ModuleTypeValues;
110   TypeValuesListTy FunctionTypeValues;
111
112   // When the ModuleGlobalInfo section is read, we create a function object for
113   // each function in the module.  When the function is loaded, this function is
114   // filled in.
115   //
116   std::vector<std::pair<Function*, unsigned> > FunctionSignatureList;
117
118   // Constant values are read in after global variables.  Because of this, we
119   // must defer setting the initializers on global variables until after module
120   // level constants have been read.  In the mean time, this list keeps track of
121   // what we must do.
122   //
123   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
124
125   // For lazy reading-in of functions, we need to save away several pieces of
126   // information about each function: its begin and end pointer in the buffer
127   // and its FunctionSlot.
128   // 
129   std::map<Function*, LazyFunctionInfo*> LazyFunctionLoadMap;
130   
131 private:
132   void freeTable(ValueTable &Tab) {
133     while (!Tab.empty()) {
134       delete Tab.back();
135       Tab.pop_back();
136     }
137   }
138
139 public:
140   void ParseModule(const unsigned char * Buf, const unsigned char *End);
141   void materializeFunction(Function *F);
142
143 private:
144   void ParseVersionInfo   (const unsigned char *&Buf, const unsigned char *End);
145   void ParseModuleGlobalInfo(const unsigned char *&Buf, const unsigned char *E);
146   void ParseSymbolTable(const unsigned char *&Buf, const unsigned char *End,
147                         SymbolTable *, Function *CurrentFunction);
148   void ParseFunction(const unsigned char *&Buf, const unsigned char *End);
149   void ParseGlobalTypes(const unsigned char *&Buf, const unsigned char *EndBuf);
150
151   BasicBlock *ParseBasicBlock(const unsigned char *&Buf,
152                               const unsigned char *End,
153                               unsigned BlockNo);
154
155   void ParseInstruction(const unsigned char *&Buf, const unsigned char *End,
156                         std::vector<unsigned> &Args, BasicBlock *BB);
157
158   void ParseConstantPool(const unsigned char *&Buf, const unsigned char *EndBuf,
159                          ValueTable &Tab, TypeValuesListTy &TypeTab);
160   Constant *parseConstantValue(const unsigned char *&Buf,
161                                const unsigned char *End,
162                                const Type *Ty);
163   void parseTypeConstants(const unsigned char *&Buf,
164                           const unsigned char *EndBuf,
165                           TypeValuesListTy &Tab, unsigned NumEntries);
166   const Type *parseTypeConstant(const unsigned char *&Buf,
167                                 const unsigned char *EndBuf);
168
169   Value      *getValue(const Type *Ty, unsigned num, bool Create = true);
170   Value      *getValue(unsigned TypeID, unsigned num, bool Create = true);
171   const Type *getType(unsigned ID);
172   BasicBlock *getBasicBlock(unsigned ID);
173   Constant   *getConstantValue(const Type *Ty, unsigned num);
174
175   unsigned insertValue(Value *V, ValueTable &Table);
176   unsigned insertValue(Value *V, unsigned Type, ValueTable &Table);
177
178   unsigned getTypeSlot(const Type *Ty);
179
180   // resolve all references to the placeholder (if any) for the given value
181   void ResolveReferencesToValue(Value *Val, unsigned Slot);
182 };
183
184 template<class SuperType>
185 class PlaceholderDef : public SuperType {
186   unsigned ID;
187   PlaceholderDef();                       // DO NOT IMPLEMENT
188   void operator=(const PlaceholderDef &); // DO NOT IMPLEMENT
189 public:
190   PlaceholderDef(const Type *Ty, unsigned id) : SuperType(Ty), ID(id) {}
191   unsigned getID() { return ID; }
192 };
193
194 struct ConstantPlaceHolderHelper : public Constant {
195   ConstantPlaceHolderHelper(const Type *Ty)
196     : Constant(Ty) {}
197   virtual bool isNullValue() const { return false; }
198 };
199
200 typedef PlaceholderDef<ConstantPlaceHolderHelper>  ConstPHolder;
201
202 // Some common errors we find
203 static const std::string Error_readvbr   = "read_vbr(): error reading.";
204 static const std::string Error_read      = "read(): error reading.";
205 static const std::string Error_inputdata = "input_data(): error reading.";
206 static const std::string Error_DestSlot  = "No destination slot found.";
207
208 static inline void readBlock(const unsigned char *&Buf,
209                              const unsigned char *EndBuf, 
210                              unsigned &Type, unsigned &Size) {
211 #if DEBUG_OUTPUT
212   bool Result = read(Buf, EndBuf, Type) || read(Buf, EndBuf, Size);
213   std::cerr << "StartLoc = " << ((unsigned)Buf & 4095)
214        << " Type = " << Type << " Size = " << Size << endl;
215   if (Result) throw Error_read;
216 #else
217   if (read(Buf, EndBuf, Type) || read(Buf, EndBuf, Size)) throw Error_read;
218 #endif
219 }
220
221 #endif