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