Various cleanups:
[oota-llvm.git] / lib / Bytecode / Reader / Reader.h
1 //===-- Reader.h - Interface To Bytecode Reading ----------------*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Reid Spencer and is distributed under the 
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 //  This header file defines the interface to the Bytecode Reader which is 
11 //  responsible for correctly interpreting bytecode files (backwards compatible)
12 //  and materializing a module from the bytecode read.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef BYTECODE_PARSER_H
17 #define BYTECODE_PARSER_H
18
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/GlobalValue.h"
22 #include "llvm/Function.h"
23 #include "llvm/ModuleProvider.h"
24 #include "llvm/Bytecode/Analyzer.h"
25 #include <utility>
26 #include <map>
27
28 namespace llvm {
29
30 class BytecodeHandler; ///< Forward declare the handler interface
31
32 /// This class defines the interface for parsing a buffer of bytecode. The
33 /// parser itself takes no action except to call the various functions of
34 /// the handler interface. The parser's sole responsibility is the correct
35 /// interpretation of the bytecode buffer. The handler is responsible for 
36 /// instantiating and keeping track of all values. As a convenience, the parser 
37 /// is responsible for materializing types and will pass them through the
38 /// handler interface as necessary.
39 /// @see BytecodeHandler
40 /// @brief Bytecode Reader interface
41 class BytecodeReader : public ModuleProvider {
42
43 /// @name Constructors
44 /// @{
45 public:
46   /// @brief Default constructor. By default, no handler is used.
47   BytecodeReader( 
48     BytecodeHandler* h = 0
49   ) { 
50     Handler = h; 
51   }
52
53   ~BytecodeReader() { freeState(); }
54
55 /// @}
56 /// @name Types
57 /// @{
58 public:
59   /// @brief A convenience type for the buffer pointer
60   typedef const unsigned char* BufPtr;
61
62   /// @brief The type used for a vector of potentially abstract types
63   typedef std::vector<PATypeHolder> TypeListTy;
64
65   /// This type provides a vector of Value* via the User class for
66   /// storage of Values that have been constructed when reading the
67   /// bytecode. Because of forward referencing, constant replacement
68   /// can occur so we ensure that our list of Value* is updated
69   /// properly through those transitions. This ensures that the
70   /// correct Value* is in our list when it comes time to associate
71   /// constants with global variables at the end of reading the
72   /// globals section.
73   /// @brief A list of values as a User of those Values.
74   struct ValueList : public User {
75     ValueList() : User(Type::VoidTy, Value::FunctionVal) {}
76
77     // vector compatibility methods
78     unsigned size() const { return getNumOperands(); }
79     void push_back(Value *V) { Operands.push_back(Use(V, this)); }
80     Value *back() const { return Operands.back(); }
81     void pop_back() { Operands.pop_back(); }
82     bool empty() const { return Operands.empty(); }
83     // must override this 
84     virtual void print(std::ostream& os) const {
85       for ( unsigned i = 0; i < size(); i++ ) {
86         os << i << " ";
87         getOperand(i)->print(os);
88         os << "\n";
89       }
90     }
91   };
92
93   /// @brief A 2 dimensional table of values
94   typedef std::vector<ValueList*> ValueTable;
95
96   /// This map is needed so that forward references to constants can be looked 
97   /// up by Type and slot number when resolving those references.
98   /// @brief A mapping of a Type/slot pair to a Constant*.
99   typedef std::map<std::pair<const Type*,unsigned>, Constant*> ConstantRefsType;
100
101   /// For lazy read-in of functions, we need to save the location in the
102   /// data stream where the function is located. This structure provides that
103   /// information. Lazy read-in is used mostly by the JIT which only wants to
104   /// resolve functions as it needs them. 
105   /// @brief Keeps pointers to function contents for later use.
106   struct LazyFunctionInfo {
107     const unsigned char *Buf, *EndBuf;
108     LazyFunctionInfo(const unsigned char *B = 0, const unsigned char *EB = 0)
109       : Buf(B), EndBuf(EB) {}
110   };
111
112   /// @brief A mapping of functions to their LazyFunctionInfo for lazy reading.
113   typedef std::map<Function*, LazyFunctionInfo> LazyFunctionMap;
114
115   /// @brief A list of global variables and the slot number that initializes
116   /// them.
117   typedef std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitsList;
118
119   /// This type maps a typeslot/valueslot pair to the corresponding Value*.
120   /// It is used for dealing with forward references as values are read in.
121   /// @brief A map for dealing with forward references of values.
122   typedef std::map<std::pair<unsigned,unsigned>,Value*> ForwardReferenceMap;
123
124 /// @}
125 /// @name Methods
126 /// @{
127 public:
128   /// @brief Main interface to parsing a bytecode buffer.
129   void ParseBytecode(
130      const unsigned char *Buf,    ///< Beginning of the bytecode buffer
131      unsigned Length,             ///< Length of the bytecode buffer
132      const std::string &ModuleID, ///< An identifier for the module constructed.
133      bool processFunctions=false  ///< Process all function bodies fully.
134   );
135
136   /// @brief Parse all function bodies
137   void ParseAllFunctionBodies();
138
139   /// @brief Parse the next function of specific type
140   void ParseFunction(Function* Func) ;
141
142   /// This method is abstract in the parent ModuleProvider class. Its
143   /// implementation is identical to the ParseFunction method.
144   /// @see ParseFunction
145   /// @brief Make a specific function materialize.
146   virtual void materializeFunction(Function *F) {
147     LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(F);
148     if (Fi == LazyFunctionLoadMap.end()) return;
149     ParseFunction(F);
150   }
151
152   /// This method is abstract in the parent ModuleProvider class. Its
153   /// implementation is identical to ParseAllFunctionBodies. 
154   /// @see ParseAllFunctionBodies
155   /// @brief Make the whole module materialize
156   virtual Module* materializeModule() {
157     ParseAllFunctionBodies();
158     return TheModule;
159   }
160
161   /// This method is provided by the parent ModuleProvde class and overriden
162   /// here. It simply releases the module from its provided and frees up our
163   /// state.
164   /// @brief Release our hold on the generated module
165   Module* releaseModule() {
166     // Since we're losing control of this Module, we must hand it back complete
167     Module *M = ModuleProvider::releaseModule();
168     freeState();
169     return M;
170   }
171
172 /// @}
173 /// @name Parsing Units For Subclasses
174 /// @{
175 protected:
176   /// @brief Parse whole module scope
177   void ParseModule();
178
179   /// @brief Parse the version information block
180   void ParseVersionInfo();
181
182   /// @brief Parse the ModuleGlobalInfo block
183   void ParseModuleGlobalInfo();
184
185   /// @brief Parse a symbol table
186   void ParseSymbolTable( Function* Func, SymbolTable *ST);
187
188   /// @brief Parse functions lazily.
189   void ParseFunctionLazily();
190
191   ///  @brief Parse a function body
192   void ParseFunctionBody(Function* Func);
193
194   /// @brief Parse the type list portion of a compaction table
195   void BytecodeReader::ParseCompactionTypes( unsigned NumEntries );
196
197   /// @brief Parse a compaction table
198   void ParseCompactionTable();
199
200   /// @brief Parse global types
201   void ParseGlobalTypes();
202
203   /// @brief Parse a basic block (for LLVM 1.0 basic block blocks)
204   BasicBlock* ParseBasicBlock(unsigned BlockNo);
205
206   /// @brief parse an instruction list (for post LLVM 1.0 instruction lists
207   /// with blocks differentiated by terminating instructions.
208   unsigned ParseInstructionList(
209     Function* F   ///< The function into which BBs will be inserted
210   );
211   
212   /// @brief Parse a single instruction.
213   void ParseInstruction(
214     std::vector<unsigned>& Args,   ///< The arguments to be filled in
215     BasicBlock* BB             ///< The BB the instruction goes in
216   );
217
218   /// @brief Parse the whole constant pool
219   void ParseConstantPool(ValueTable& Values, TypeListTy& Types, 
220                          bool isFunction);
221
222   /// @brief Parse a single constant value
223   Constant* ParseConstantValue(unsigned TypeID);
224
225   /// @brief Parse a block of types constants
226   void ParseTypes(TypeListTy &Tab, unsigned NumEntries);
227
228   /// @brief Parse a single type constant
229   const Type *ParseType();
230
231   /// @brief Parse a string constants block
232   void ParseStringConstants(unsigned NumEntries, ValueTable &Tab);
233
234 /// @}
235 /// @name Data
236 /// @{
237 private:
238   BufPtr MemStart;     ///< Start of the memory buffer
239   BufPtr MemEnd;       ///< End of the memory buffer
240   BufPtr BlockStart;   ///< Start of current block being parsed
241   BufPtr BlockEnd;     ///< End of current block being parsed
242   BufPtr At;           ///< Where we're currently parsing at
243
244   /// Information about the module, extracted from the bytecode revision number.
245   unsigned char RevisionNum;        // The rev # itself
246
247   /// Flags to distinguish LLVM 1.0 & 1.1 bytecode formats (revision #0)
248
249   /// Revision #0 had an explicit alignment of data only for the ModuleGlobalInfo
250   /// block.  This was fixed to be like all other blocks in 1.2
251   bool hasInconsistentModuleGlobalInfo;
252
253   /// Revision #0 also explicitly encoded zero values for primitive types like
254   /// int/sbyte/etc.
255   bool hasExplicitPrimitiveZeros;
256
257   // Flags to control features specific the LLVM 1.2 and before (revision #1)
258
259   /// LLVM 1.2 and earlier required that getelementptr structure indices were
260   /// ubyte constants and that sequential type indices were longs.
261   bool hasRestrictedGEPTypes;
262
263   /// LLVM 1.2 and earlier had class Type deriving from Value and the Type
264   /// objects were located in the "Type Type" plane of various lists in read
265   /// by the bytecode reader. In LLVM 1.3 this is no longer the case. Types are
266   /// completely distinct from Values. Consequently, Types are written in fixed
267   /// locations in LLVM 1.3. This flag indicates that the older Type derived
268   /// from Value style of bytecode file is being read.
269   bool hasTypeDerivedFromValue;
270
271   /// CompactionTable - If a compaction table is active in the current function,
272   /// this is the mapping that it contains.
273   std::vector<const Type*> CompactionTypes;
274
275   /// @brief If a compaction table is active in the current function,
276   /// this is the mapping that it contains.
277   std::vector<std::vector<Value*> > CompactionValues;
278
279   /// @brief This vector is used to deal with forward references to types in
280   /// a module.
281   TypeListTy ModuleTypes;
282
283   /// @brief This vector is used to deal with forward references to types in
284   /// a function.
285   TypeListTy FunctionTypes;
286
287   /// When the ModuleGlobalInfo section is read, we create a Function object
288   /// for each function in the module. When the function is loaded, after the
289   /// module global info is read, this Function is populated. Until then, the
290   /// functions in this vector just hold the function signature.
291   std::vector<Function*> FunctionSignatureList;
292
293   /// @brief This is the table of values belonging to the current function
294   ValueTable FunctionValues;
295
296   /// @brief This is the table of values belonging to the module (global)
297   ValueTable ModuleValues;
298
299   /// @brief This keeps track of function level forward references.
300   ForwardReferenceMap ForwardReferences;
301
302   /// @brief The basic blocks we've parsed, while parsing a function.
303   std::vector<BasicBlock*> ParsedBasicBlocks;
304
305   /// This maintains a mapping between <Type, Slot #>'s and
306   /// forward references to constants.  Such values may be referenced before they
307   /// are defined, and if so, the temporary object that they represent is held
308   /// here.
309   /// @brief Temporary place for forward references to constants.
310   ConstantRefsType ConstantFwdRefs;
311
312   /// Constant values are read in after global variables.  Because of this, we
313   /// must defer setting the initializers on global variables until after module
314   /// level constants have been read.  In the mean time, this list keeps track of
315   /// what we must do.
316   GlobalInitsList GlobalInits;
317
318   // For lazy reading-in of functions, we need to save away several pieces of
319   // information about each function: its begin and end pointer in the buffer
320   // and its FunctionSlot.
321   LazyFunctionMap LazyFunctionLoadMap;
322
323   /// This stores the parser's handler which is used for handling tasks other 
324   /// just than reading bytecode into the IR. If this is non-null, calls on 
325   /// the (polymorphic) BytecodeHandler interface (see llvm/Bytecode/Handler.h) 
326   /// will be made to report the logical structure of the bytecode file. What 
327   /// the handler does with the events it receives is completely orthogonal to 
328   /// the business of parsing the bytecode and building the IR.  This is used,
329   /// for example, by the llvm-abcd tool for analysis of byte code.
330   /// @brief Handler for parsing events.
331   BytecodeHandler* Handler;
332
333 /// @}
334 /// @name Implementation Details
335 /// @{
336 private:
337   /// @brief Determines if this module has a function or not.
338   bool hasFunctions() { return ! FunctionSignatureList.empty(); }
339
340   /// @brief Determines if the type id has an implicit null value.
341   bool hasImplicitNull(unsigned TyID );
342
343   /// @brief Converts a type slot number to its Type*
344   const Type *getType(unsigned ID);
345
346   /// @brief Converts a pre-sanitized type slot number to its Type* and
347   /// sanitizes the type id.
348   inline const Type* getSanitizedType(unsigned& ID );
349
350   /// @brief Read in and get a sanitized type id
351   inline const Type* BytecodeReader::readSanitizedType();
352
353   /// @brief Converts a Type* to its type slot number
354   unsigned getTypeSlot(const Type *Ty);
355
356   /// @brief Converts a normal type slot number to a compacted type slot num.
357   unsigned getCompactionTypeSlot(unsigned type);
358
359   /// @brief Gets the global type corresponding to the TypeId
360   const Type *getGlobalTableType(unsigned TypeId);
361
362   /// This is just like getTypeSlot, but when a compaction table is in use,
363   /// it is ignored. 
364   unsigned getGlobalTableTypeSlot(const Type *Ty);
365   
366   /// @brief Get a value from its typeid and slot number
367   Value* getValue(unsigned TypeID, unsigned num, bool Create = true);
368
369   /// @brief Get a value from its type and slot number, ignoring compaction tables.
370   Value *getGlobalTableValue(const Type *Ty, unsigned SlotNo);
371
372   /// @brief Get a basic block for current function
373   BasicBlock *getBasicBlock(unsigned ID);
374
375   /// @brief Get a constant value from its typeid and value slot.
376   Constant* getConstantValue(unsigned typeSlot, unsigned valSlot);
377
378   /// @brief Convenience function for getting a constant value when
379   /// the Type has already been resolved.
380   Constant* getConstantValue(const Type *Ty, unsigned valSlot) {
381     return getConstantValue(getTypeSlot(Ty), valSlot);
382   }
383
384   /// @brief Insert a newly created value
385   unsigned insertValue(Value *V, unsigned Type, ValueTable &Table);
386
387   /// @brief Insert the arguments of a function.
388   void insertArguments(Function* F );
389
390   /// @brief Resolve all references to the placeholder (if any) for the 
391   /// given constant.
392   void ResolveReferencesToConstant(Constant *C, unsigned Slot);
393
394   /// @brief Release our memory.
395   void freeState() {
396     freeTable(FunctionValues);
397     freeTable(ModuleValues);
398   }
399
400   /// @brief Free a table, making sure to free the ValueList in the table.
401   void freeTable(ValueTable &Tab) {
402     while (!Tab.empty()) {
403       delete Tab.back();
404       Tab.pop_back();
405     }
406   }
407
408   inline void error(std::string errmsg);
409
410   BytecodeReader(const BytecodeReader &);  // DO NOT IMPLEMENT
411   void operator=(const BytecodeReader &);  // DO NOT IMPLEMENT
412
413 /// @}
414 /// @name Reader Primitives
415 /// @{
416 private:
417
418   /// @brief Is there more to parse in the current block?
419   inline bool moreInBlock();
420
421   /// @brief Have we read past the end of the block
422   inline void checkPastBlockEnd(const char * block_name);
423
424   /// @brief Align to 32 bits
425   inline void align32();
426
427   /// @brief Read an unsigned integer as 32-bits
428   inline unsigned read_uint();
429
430   /// @brief Read an unsigned integer with variable bit rate encoding
431   inline unsigned read_vbr_uint();
432
433   /// @brief Read an unsigned 64-bit integer with variable bit rate encoding.
434   inline uint64_t read_vbr_uint64();
435
436   /// @brief Read a signed 64-bit integer with variable bit rate encoding.
437   inline int64_t read_vbr_int64();
438
439   /// @brief Read a string
440   inline std::string read_str();
441
442   /// @brief Read a float value
443   inline void read_float(float& FloatVal);
444
445   /// @brief Read a double value
446   inline void read_double(double& DoubleVal);
447
448   /// @brief Read an arbitrary data chunk of fixed length
449   inline void read_data(void *Ptr, void *End);
450
451   /// @brief Read a bytecode block header
452   inline void read_block(unsigned &Type, unsigned &Size);
453
454   /// @brief Read a type identifier and sanitize it.
455   inline bool read_typeid(unsigned &TypeId);
456
457   /// @brief Recalculate type ID for pre 1.3 bytecode files.
458   inline bool sanitizeTypeId(unsigned &TypeId );
459 /// @}
460 };
461
462 /// @brief A function for creating a BytecodeAnalzer as a handler
463 /// for the Bytecode reader.
464 BytecodeHandler* createBytecodeAnalyzerHandler(BytecodeAnalysis& bca );
465
466
467 } // End llvm namespace
468
469 // vim: sw=2
470 #endif