Fit to 80 cols
[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
60   /// @brief A convenience type for the buffer pointer
61   typedef const unsigned char* BufPtr;
62
63   /// @brief The type used for a vector of potentially abstract types
64   typedef std::vector<PATypeHolder> TypeListTy;
65
66   /// This type provides a vector of Value* via the User class for
67   /// storage of Values that have been constructed when reading the
68   /// bytecode. Because of forward referencing, constant replacement
69   /// can occur so we ensure that our list of Value* is updated
70   /// properly through those transitions. This ensures that the
71   /// correct Value* is in our list when it comes time to associate
72   /// constants with global variables at the end of reading the
73   /// globals section.
74   /// @brief A list of values as a User of those Values.
75   struct ValueList : public User {
76     ValueList() : User(Type::VoidTy, Value::ValueListVal) {}
77
78     // vector compatibility methods
79     unsigned size() const { return getNumOperands(); }
80     void push_back(Value *V) { Operands.push_back(Use(V, this)); }
81     Value *back() const { return Operands.back(); }
82     void pop_back() { Operands.pop_back(); }
83     bool empty() const { return Operands.empty(); }
84     // must override this 
85     virtual void print(std::ostream& os) const {
86       for ( unsigned i = 0; i < size(); i++ ) {
87         os << i << " ";
88         getOperand(i)->print(os);
89         os << "\n";
90       }
91     }
92   };
93
94   /// @brief A 2 dimensional table of values
95   typedef std::vector<ValueList*> ValueTable;
96
97   /// This map is needed so that forward references to constants can be looked 
98   /// up by Type and slot number when resolving those references.
99   /// @brief A mapping of a Type/slot pair to a Constant*.
100   typedef std::map<std::pair<const Type*,unsigned>, Constant*> ConstantRefsType;
101
102   /// For lazy read-in of functions, we need to save the location in the
103   /// data stream where the function is located. This structure provides that
104   /// information. Lazy read-in is used mostly by the JIT which only wants to
105   /// resolve functions as it needs them. 
106   /// @brief Keeps pointers to function contents for later use.
107   struct LazyFunctionInfo {
108     const unsigned char *Buf, *EndBuf;
109     LazyFunctionInfo(const unsigned char *B = 0, const unsigned char *EB = 0)
110       : Buf(B), EndBuf(EB) {}
111   };
112
113   /// @brief A mapping of functions to their LazyFunctionInfo for lazy reading.
114   typedef std::map<Function*, LazyFunctionInfo> LazyFunctionMap;
115
116   /// @brief A list of global variables and the slot number that initializes
117   /// them.
118   typedef std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitsList;
119
120   /// This type maps a typeslot/valueslot pair to the corresponding Value*.
121   /// It is used for dealing with forward references as values are read in.
122   /// @brief A map for dealing with forward references of values.
123   typedef std::map<std::pair<unsigned,unsigned>,Value*> ForwardReferenceMap;
124
125 /// @}
126 /// @name Methods
127 /// @{
128 public:
129   /// @brief Main interface to parsing a bytecode buffer.
130   void ParseBytecode(
131      const unsigned char *Buf,    ///< Beginning of the bytecode buffer
132      unsigned Length,             ///< Length of the bytecode buffer
133      const std::string &ModuleID  ///< An identifier for the module constructed.
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 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   ///
246   unsigned char RevisionNum;        // The rev # itself
247
248   /// Flags to distinguish LLVM 1.0 & 1.1 bytecode formats (revision #0)
249
250   /// Revision #0 had an explicit alignment of data only for the
251   /// ModuleGlobalInfo block.  This was fixed to be like all other blocks in 1.2
252   bool hasInconsistentModuleGlobalInfo;
253
254   /// Revision #0 also explicitly encoded zero values for primitive types like
255   /// int/sbyte/etc.
256   bool hasExplicitPrimitiveZeros;
257
258   // Flags to control features specific the LLVM 1.2 and before (revision #1)
259
260   /// LLVM 1.2 and earlier required that getelementptr structure indices were
261   /// ubyte constants and that sequential type indices were longs.
262   bool hasRestrictedGEPTypes;
263
264   /// LLVM 1.2 and earlier had class Type deriving from Value and the Type
265   /// objects were located in the "Type Type" plane of various lists in read
266   /// by the bytecode reader. In LLVM 1.3 this is no longer the case. Types are
267   /// completely distinct from Values. Consequently, Types are written in fixed
268   /// locations in LLVM 1.3. This flag indicates that the older Type derived
269   /// from Value style of bytecode file is being read.
270   bool hasTypeDerivedFromValue;
271
272   /// LLVM 1.2 and earlier encoded block headers as two uint (8 bytes), one for
273   /// the size and one for the type. This is a bit wasteful, especially for
274   /// small files where the 8 bytes per block is a large fraction of the total
275   /// block size. In LLVM 1.3, the block type and length are encoded into a
276   /// single uint32 by restricting the number of block types (limit 31) and the
277   /// maximum size of a block (limit 2^27-1=134,217,727). Note that the module
278   /// block still uses the 8-byte format so the maximum size of a file can be
279   /// 2^32-1 bytes long.
280   bool hasLongBlockHeaders;
281
282   /// LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
283   /// this has been reduced to vbr_uint24. It shouldn't make much difference 
284   /// since we haven't run into a module with > 24 million types, but for safety
285   /// the 24-bit restriction has been enforced in 1.3 to free some bits in
286   /// various places and to ensure consistency. In particular, global vars are
287   /// restricted to 24-bits.
288   bool has32BitTypes;
289
290   /// LLVM 1.2 and earlier did not provide a target triple nor a list of 
291   /// libraries on which the bytecode is dependent. LLVM 1.3 provides these
292   /// features, for use in future versions of LLVM.
293   bool hasNoDependentLibraries;
294
295   /// LLVM 1.3 and earlier caused blocks and other fields to start on 32-bit
296   /// aligned boundaries. This can lead to as much as 30% bytecode size overhead
297   /// in various corner cases (lots of long instructions). In LLVM 1.4,
298   /// alignment of bytecode fields was done away with completely.
299   bool hasAlignment;
300
301   // In version 4, basic blocks have a minimum index of 0 whereas all the 
302   // other primitives have a minimum index of 1 (because 0 is the "null" 
303   // value. In version 5, we made this consistent.
304   bool hasInconsistentBBSlotNums;
305
306   // In version 4, the types SByte and UByte were encoded as vbr_uint so that
307   // signed values > 63 and unsigned values >127 would be encoded as two
308   // bytes. In version 5, they are encoded directly in a single byte.
309   bool hasVBRByteTypes;
310
311   // In version 4, modules begin with a "Module Block" which encodes a 4-byte
312   // integer value 0x01 to identify the module block. This is unnecessary and
313   // removed in version 5.
314   bool hasUnnecessaryModuleBlockId;
315
316   /// CompactionTypes - If a compaction table is active in the current function,
317   /// this is the mapping that it contains.  We keep track of what resolved type
318   /// it is as well as what global type entry it is.
319   std::vector<std::pair<const Type*, unsigned> > CompactionTypes;
320
321   /// @brief If a compaction table is active in the current function,
322   /// this is the mapping that it contains.
323   std::vector<std::vector<Value*> > CompactionValues;
324
325   /// @brief This vector is used to deal with forward references to types in
326   /// a module.
327   TypeListTy ModuleTypes;
328
329   /// @brief This vector is used to deal with forward references to types in
330   /// a function.
331   TypeListTy FunctionTypes;
332
333   /// When the ModuleGlobalInfo section is read, we create a Function object
334   /// for each function in the module. When the function is loaded, after the
335   /// module global info is read, this Function is populated. Until then, the
336   /// functions in this vector just hold the function signature.
337   std::vector<Function*> FunctionSignatureList;
338
339   /// @brief This is the table of values belonging to the current function
340   ValueTable FunctionValues;
341
342   /// @brief This is the table of values belonging to the module (global)
343   ValueTable ModuleValues;
344
345   /// @brief This keeps track of function level forward references.
346   ForwardReferenceMap ForwardReferences;
347
348   /// @brief The basic blocks we've parsed, while parsing a function.
349   std::vector<BasicBlock*> ParsedBasicBlocks;
350
351   /// This maintains a mapping between <Type, Slot #>'s and forward references
352   /// to constants.  Such values may be referenced before they are defined, and
353   /// if so, the temporary object that they represent is held here.  @brief
354   /// Temporary place for forward references to constants.
355   ConstantRefsType ConstantFwdRefs;
356
357   /// Constant values are read in after global variables.  Because of this, we
358   /// must defer setting the initializers on global variables until after module
359   /// level constants have been read.  In the mean time, this list keeps track
360   /// of what we must do.
361   GlobalInitsList GlobalInits;
362
363   // For lazy reading-in of functions, we need to save away several pieces of
364   // information about each function: its begin and end pointer in the buffer
365   // and its FunctionSlot.
366   LazyFunctionMap LazyFunctionLoadMap;
367
368   /// This stores the parser's handler which is used for handling tasks other 
369   /// just than reading bytecode into the IR. If this is non-null, calls on 
370   /// the (polymorphic) BytecodeHandler interface (see llvm/Bytecode/Handler.h) 
371   /// will be made to report the logical structure of the bytecode file. What 
372   /// the handler does with the events it receives is completely orthogonal to 
373   /// the business of parsing the bytecode and building the IR.  This is used,
374   /// for example, by the llvm-abcd tool for analysis of byte code.
375   /// @brief Handler for parsing events.
376   BytecodeHandler* Handler;
377
378 /// @}
379 /// @name Implementation Details
380 /// @{
381 private:
382   /// @brief Determines if this module has a function or not.
383   bool hasFunctions() { return ! FunctionSignatureList.empty(); }
384
385   /// @brief Determines if the type id has an implicit null value.
386   bool hasImplicitNull(unsigned TyID );
387
388   /// @brief Converts a type slot number to its Type*
389   const Type *getType(unsigned ID);
390
391   /// @brief Converts a pre-sanitized type slot number to its Type* and
392   /// sanitizes the type id.
393   inline const Type* getSanitizedType(unsigned& ID );
394
395   /// @brief Read in and get a sanitized type id
396   inline const Type* BytecodeReader::readSanitizedType();
397
398   /// @brief Converts a Type* to its type slot number
399   unsigned getTypeSlot(const Type *Ty);
400
401   /// @brief Converts a normal type slot number to a compacted type slot num.
402   unsigned getCompactionTypeSlot(unsigned type);
403
404   /// @brief Gets the global type corresponding to the TypeId
405   const Type *getGlobalTableType(unsigned TypeId);
406
407   /// This is just like getTypeSlot, but when a compaction table is in use,
408   /// it is ignored. 
409   unsigned getGlobalTableTypeSlot(const Type *Ty);
410   
411   /// @brief Get a value from its typeid and slot number
412   Value* getValue(unsigned TypeID, unsigned num, bool Create = true);
413
414   /// @brief Get a value from its type and slot number, ignoring compaction
415   /// tables.
416   Value *getGlobalTableValue(unsigned TyID, unsigned SlotNo);
417
418   /// @brief Get a basic block for current function
419   BasicBlock *getBasicBlock(unsigned ID);
420
421   /// @brief Get a constant value from its typeid and value slot.
422   Constant* getConstantValue(unsigned typeSlot, unsigned valSlot);
423
424   /// @brief Convenience function for getting a constant value when
425   /// the Type has already been resolved.
426   Constant* getConstantValue(const Type *Ty, unsigned valSlot) {
427     return getConstantValue(getTypeSlot(Ty), valSlot);
428   }
429
430   /// @brief Insert a newly created value
431   unsigned insertValue(Value *V, unsigned Type, ValueTable &Table);
432
433   /// @brief Insert the arguments of a function.
434   void insertArguments(Function* F );
435
436   /// @brief Resolve all references to the placeholder (if any) for the 
437   /// given constant.
438   void ResolveReferencesToConstant(Constant *C, unsigned Slot);
439
440   /// @brief Release our memory.
441   void freeState() {
442     freeTable(FunctionValues);
443     freeTable(ModuleValues);
444   }
445
446   /// @brief Free a table, making sure to free the ValueList in the table.
447   void freeTable(ValueTable &Tab) {
448     while (!Tab.empty()) {
449       delete Tab.back();
450       Tab.pop_back();
451     }
452   }
453
454   inline void error(std::string errmsg);
455
456   BytecodeReader(const BytecodeReader &);  // DO NOT IMPLEMENT
457   void operator=(const BytecodeReader &);  // DO NOT IMPLEMENT
458
459 /// @}
460 /// @name Reader Primitives
461 /// @{
462 private:
463
464   /// @brief Is there more to parse in the current block?
465   inline bool moreInBlock();
466
467   /// @brief Have we read past the end of the block
468   inline void checkPastBlockEnd(const char * block_name);
469
470   /// @brief Align to 32 bits
471   inline void align32();
472
473   /// @brief Read an unsigned integer as 32-bits
474   inline unsigned read_uint();
475
476   /// @brief Read an unsigned integer with variable bit rate encoding
477   inline unsigned read_vbr_uint();
478
479   /// @brief Read an unsigned integer of no more than 24-bits with variable
480   /// bit rate encoding.
481   inline unsigned read_vbr_uint24();
482
483   /// @brief Read an unsigned 64-bit integer with variable bit rate encoding.
484   inline uint64_t read_vbr_uint64();
485
486   /// @brief Read a signed 64-bit integer with variable bit rate encoding.
487   inline int64_t read_vbr_int64();
488
489   /// @brief Read a string
490   inline std::string read_str();
491
492   /// @brief Read a float value
493   inline void read_float(float& FloatVal);
494
495   /// @brief Read a double value
496   inline void read_double(double& DoubleVal);
497
498   /// @brief Read an arbitrary data chunk of fixed length
499   inline void read_data(void *Ptr, void *End);
500
501   /// @brief Read a bytecode block header
502   inline void read_block(unsigned &Type, unsigned &Size);
503
504   /// @brief Read a type identifier and sanitize it.
505   inline bool read_typeid(unsigned &TypeId);
506
507   /// @brief Recalculate type ID for pre 1.3 bytecode files.
508   inline bool sanitizeTypeId(unsigned &TypeId );
509 /// @}
510 };
511
512 /// @brief A function for creating a BytecodeAnalzer as a handler
513 /// for the Bytecode reader.
514 BytecodeHandler* createBytecodeAnalyzerHandler(BytecodeAnalysis& bca, 
515                                                std::ostream* output );
516
517
518 } // End llvm namespace
519
520 // vim: sw=2
521 #endif