Add support for compressed bytecode
[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() { 
54     freeState(); 
55     if (bi.buff != 0)
56       ::free(bi.buff);
57   }
58
59 /// @}
60 /// @name Types
61 /// @{
62 public:
63
64   /// @brief A convenience type for the buffer pointer
65   typedef const unsigned char* BufPtr;
66
67   /// @brief The type used for a vector of potentially abstract types
68   typedef std::vector<PATypeHolder> TypeListTy;
69
70   /// @brief An internal buffer object used for handling decompression
71   struct BufferInfo {
72     char* buff;
73     unsigned size;
74     BufferInfo() { buff = 0; size = 0; }
75   };
76
77   /// This type provides a vector of Value* via the User class for
78   /// storage of Values that have been constructed when reading the
79   /// bytecode. Because of forward referencing, constant replacement
80   /// can occur so we ensure that our list of Value* is updated
81   /// properly through those transitions. This ensures that the
82   /// correct Value* is in our list when it comes time to associate
83   /// constants with global variables at the end of reading the
84   /// globals section.
85   /// @brief A list of values as a User of those Values.
86   struct ValueList : public User {
87     ValueList() : User(Type::VoidTy, Value::ValueListVal) {}
88
89     // vector compatibility methods
90     unsigned size() const { return getNumOperands(); }
91     void push_back(Value *V) { Operands.push_back(Use(V, this)); }
92     Value *back() const { return Operands.back(); }
93     void pop_back() { Operands.pop_back(); }
94     bool empty() const { return Operands.empty(); }
95     // must override this 
96     virtual void print(std::ostream& os) const {
97       for ( unsigned i = 0; i < size(); i++ ) {
98         os << i << " ";
99         getOperand(i)->print(os);
100         os << "\n";
101       }
102     }
103   };
104
105   /// @brief A 2 dimensional table of values
106   typedef std::vector<ValueList*> ValueTable;
107
108   /// This map is needed so that forward references to constants can be looked 
109   /// up by Type and slot number when resolving those references.
110   /// @brief A mapping of a Type/slot pair to a Constant*.
111   typedef std::map<std::pair<const Type*,unsigned>, Constant*> ConstantRefsType;
112
113   /// For lazy read-in of functions, we need to save the location in the
114   /// data stream where the function is located. This structure provides that
115   /// information. Lazy read-in is used mostly by the JIT which only wants to
116   /// resolve functions as it needs them. 
117   /// @brief Keeps pointers to function contents for later use.
118   struct LazyFunctionInfo {
119     const unsigned char *Buf, *EndBuf;
120     LazyFunctionInfo(const unsigned char *B = 0, const unsigned char *EB = 0)
121       : Buf(B), EndBuf(EB) {}
122   };
123
124   /// @brief A mapping of functions to their LazyFunctionInfo for lazy reading.
125   typedef std::map<Function*, LazyFunctionInfo> LazyFunctionMap;
126
127   /// @brief A list of global variables and the slot number that initializes
128   /// them.
129   typedef std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitsList;
130
131   /// This type maps a typeslot/valueslot pair to the corresponding Value*.
132   /// It is used for dealing with forward references as values are read in.
133   /// @brief A map for dealing with forward references of values.
134   typedef std::map<std::pair<unsigned,unsigned>,Value*> ForwardReferenceMap;
135
136 /// @}
137 /// @name Methods
138 /// @{
139 public:
140   /// @brief Main interface to parsing a bytecode buffer.
141   void ParseBytecode(
142      const unsigned char *Buf,    ///< Beginning of the bytecode buffer
143      unsigned Length,             ///< Length of the bytecode buffer
144      const std::string &ModuleID  ///< An identifier for the module constructed.
145   );
146
147   /// @brief Parse all function bodies
148   void ParseAllFunctionBodies();
149
150   /// @brief Parse the next function of specific type
151   void ParseFunction(Function* Func) ;
152
153   /// This method is abstract in the parent ModuleProvider class. Its
154   /// implementation is identical to the ParseFunction method.
155   /// @see ParseFunction
156   /// @brief Make a specific function materialize.
157   virtual void materializeFunction(Function *F) {
158     LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(F);
159     if (Fi == LazyFunctionLoadMap.end()) return;
160     ParseFunction(F);
161   }
162
163   /// This method is abstract in the parent ModuleProvider class. Its
164   /// implementation is identical to ParseAllFunctionBodies. 
165   /// @see ParseAllFunctionBodies
166   /// @brief Make the whole module materialize
167   virtual Module* materializeModule() {
168     ParseAllFunctionBodies();
169     return TheModule;
170   }
171
172   /// This method is provided by the parent ModuleProvde class and overriden
173   /// here. It simply releases the module from its provided and frees up our
174   /// state.
175   /// @brief Release our hold on the generated module
176   Module* releaseModule() {
177     // Since we're losing control of this Module, we must hand it back complete
178     Module *M = ModuleProvider::releaseModule();
179     freeState();
180     return M;
181   }
182
183 /// @}
184 /// @name Parsing Units For Subclasses
185 /// @{
186 protected:
187   /// @brief Parse whole module scope
188   void ParseModule();
189
190   /// @brief Parse the version information block
191   void ParseVersionInfo();
192
193   /// @brief Parse the ModuleGlobalInfo block
194   void ParseModuleGlobalInfo();
195
196   /// @brief Parse a symbol table
197   void ParseSymbolTable( Function* Func, SymbolTable *ST);
198
199   /// @brief Parse functions lazily.
200   void ParseFunctionLazily();
201
202   ///  @brief Parse a function body
203   void ParseFunctionBody(Function* Func);
204
205   /// @brief Parse the type list portion of a compaction table
206   void ParseCompactionTypes(unsigned NumEntries);
207
208   /// @brief Parse a compaction table
209   void ParseCompactionTable();
210
211   /// @brief Parse global types
212   void ParseGlobalTypes();
213
214   /// @brief Parse a basic block (for LLVM 1.0 basic block blocks)
215   BasicBlock* ParseBasicBlock(unsigned BlockNo);
216
217   /// @brief parse an instruction list (for post LLVM 1.0 instruction lists
218   /// with blocks differentiated by terminating instructions.
219   unsigned ParseInstructionList(
220     Function* F   ///< The function into which BBs will be inserted
221   );
222   
223   /// @brief Parse a single instruction.
224   void ParseInstruction(
225     std::vector<unsigned>& Args,   ///< The arguments to be filled in
226     BasicBlock* BB             ///< The BB the instruction goes in
227   );
228
229   /// @brief Parse the whole constant pool
230   void ParseConstantPool(ValueTable& Values, TypeListTy& Types, 
231                          bool isFunction);
232
233   /// @brief Parse a single constant value
234   Constant* ParseConstantValue(unsigned TypeID);
235
236   /// @brief Parse a block of types constants
237   void ParseTypes(TypeListTy &Tab, unsigned NumEntries);
238
239   /// @brief Parse a single type constant
240   const Type *ParseType();
241
242   /// @brief Parse a string constants block
243   void ParseStringConstants(unsigned NumEntries, ValueTable &Tab);
244
245 /// @}
246 /// @name Data
247 /// @{
248 private:
249   BufferInfo bi;      ///< Buffer info for decompression
250
251   BufPtr MemStart;     ///< Start of the memory buffer
252   BufPtr MemEnd;       ///< End of the memory buffer
253   BufPtr BlockStart;   ///< Start of current block being parsed
254   BufPtr BlockEnd;     ///< End of current block being parsed
255   BufPtr At;           ///< Where we're currently parsing at
256
257   /// Information about the module, extracted from the bytecode revision number.
258   ///
259   unsigned char RevisionNum;        // The rev # itself
260
261   /// Flags to distinguish LLVM 1.0 & 1.1 bytecode formats (revision #0)
262
263   /// Revision #0 had an explicit alignment of data only for the
264   /// ModuleGlobalInfo block.  This was fixed to be like all other blocks in 1.2
265   bool hasInconsistentModuleGlobalInfo;
266
267   /// Revision #0 also explicitly encoded zero values for primitive types like
268   /// int/sbyte/etc.
269   bool hasExplicitPrimitiveZeros;
270
271   // Flags to control features specific the LLVM 1.2 and before (revision #1)
272
273   /// LLVM 1.2 and earlier required that getelementptr structure indices were
274   /// ubyte constants and that sequential type indices were longs.
275   bool hasRestrictedGEPTypes;
276
277   /// LLVM 1.2 and earlier had class Type deriving from Value and the Type
278   /// objects were located in the "Type Type" plane of various lists in read
279   /// by the bytecode reader. In LLVM 1.3 this is no longer the case. Types are
280   /// completely distinct from Values. Consequently, Types are written in fixed
281   /// locations in LLVM 1.3. This flag indicates that the older Type derived
282   /// from Value style of bytecode file is being read.
283   bool hasTypeDerivedFromValue;
284
285   /// LLVM 1.2 and earlier encoded block headers as two uint (8 bytes), one for
286   /// the size and one for the type. This is a bit wasteful, especially for
287   /// small files where the 8 bytes per block is a large fraction of the total
288   /// block size. In LLVM 1.3, the block type and length are encoded into a
289   /// single uint32 by restricting the number of block types (limit 31) and the
290   /// maximum size of a block (limit 2^27-1=134,217,727). Note that the module
291   /// block still uses the 8-byte format so the maximum size of a file can be
292   /// 2^32-1 bytes long.
293   bool hasLongBlockHeaders;
294
295   /// LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
296   /// this has been reduced to vbr_uint24. It shouldn't make much difference 
297   /// since we haven't run into a module with > 24 million types, but for safety
298   /// the 24-bit restriction has been enforced in 1.3 to free some bits in
299   /// various places and to ensure consistency. In particular, global vars are
300   /// restricted to 24-bits.
301   bool has32BitTypes;
302
303   /// LLVM 1.2 and earlier did not provide a target triple nor a list of 
304   /// libraries on which the bytecode is dependent. LLVM 1.3 provides these
305   /// features, for use in future versions of LLVM.
306   bool hasNoDependentLibraries;
307
308   /// LLVM 1.3 and earlier caused blocks and other fields to start on 32-bit
309   /// aligned boundaries. This can lead to as much as 30% bytecode size overhead
310   /// in various corner cases (lots of long instructions). In LLVM 1.4,
311   /// alignment of bytecode fields was done away with completely.
312   bool hasAlignment;
313
314   // In version 4 and earlier, the bytecode format did not support the 'undef'
315   // constant.
316   bool hasNoUndefValue;
317
318   // In version 4 and earlier, the bytecode format did not save space for flags
319   // in the global info block for functions.
320   bool hasNoFlagsForFunctions;
321
322   // In version 4 and earlier, there was no opcode space reserved for the
323   // unreachable instruction.
324   bool hasNoUnreachableInst;
325
326   // In version 5, basic blocks have a minimum index of 0 whereas all the 
327   // other primitives have a minimum index of 1 (because 0 is the "null" 
328   // value. In version 5, we made this consistent.
329   bool hasInconsistentBBSlotNums;
330
331   // In version 5, the types SByte and UByte were encoded as vbr_uint so that
332   // signed values > 63 and unsigned values >127 would be encoded as two
333   // bytes. In version 5, they are encoded directly in a single byte.
334   bool hasVBRByteTypes;
335
336   // In version 5, modules begin with a "Module Block" which encodes a 4-byte
337   // integer value 0x01 to identify the module block. This is unnecessary and
338   // removed in version 5.
339   bool hasUnnecessaryModuleBlockId;
340
341   /// CompactionTypes - If a compaction table is active in the current function,
342   /// this is the mapping that it contains.  We keep track of what resolved type
343   /// it is as well as what global type entry it is.
344   std::vector<std::pair<const Type*, unsigned> > CompactionTypes;
345
346   /// @brief If a compaction table is active in the current function,
347   /// this is the mapping that it contains.
348   std::vector<std::vector<Value*> > CompactionValues;
349
350   /// @brief This vector is used to deal with forward references to types in
351   /// a module.
352   TypeListTy ModuleTypes;
353
354   /// @brief This vector is used to deal with forward references to types in
355   /// a function.
356   TypeListTy FunctionTypes;
357
358   /// When the ModuleGlobalInfo section is read, we create a Function object
359   /// for each function in the module. When the function is loaded, after the
360   /// module global info is read, this Function is populated. Until then, the
361   /// functions in this vector just hold the function signature.
362   std::vector<Function*> FunctionSignatureList;
363
364   /// @brief This is the table of values belonging to the current function
365   ValueTable FunctionValues;
366
367   /// @brief This is the table of values belonging to the module (global)
368   ValueTable ModuleValues;
369
370   /// @brief This keeps track of function level forward references.
371   ForwardReferenceMap ForwardReferences;
372
373   /// @brief The basic blocks we've parsed, while parsing a function.
374   std::vector<BasicBlock*> ParsedBasicBlocks;
375
376   /// This maintains a mapping between <Type, Slot #>'s and forward references
377   /// to constants.  Such values may be referenced before they are defined, and
378   /// if so, the temporary object that they represent is held here.  @brief
379   /// Temporary place for forward references to constants.
380   ConstantRefsType ConstantFwdRefs;
381
382   /// Constant values are read in after global variables.  Because of this, we
383   /// must defer setting the initializers on global variables until after module
384   /// level constants have been read.  In the mean time, this list keeps track
385   /// of what we must do.
386   GlobalInitsList GlobalInits;
387
388   // For lazy reading-in of functions, we need to save away several pieces of
389   // information about each function: its begin and end pointer in the buffer
390   // and its FunctionSlot.
391   LazyFunctionMap LazyFunctionLoadMap;
392
393   /// This stores the parser's handler which is used for handling tasks other 
394   /// just than reading bytecode into the IR. If this is non-null, calls on 
395   /// the (polymorphic) BytecodeHandler interface (see llvm/Bytecode/Handler.h) 
396   /// will be made to report the logical structure of the bytecode file. What 
397   /// the handler does with the events it receives is completely orthogonal to 
398   /// the business of parsing the bytecode and building the IR.  This is used,
399   /// for example, by the llvm-abcd tool for analysis of byte code.
400   /// @brief Handler for parsing events.
401   BytecodeHandler* Handler;
402
403 /// @}
404 /// @name Implementation Details
405 /// @{
406 private:
407   /// @brief Determines if this module has a function or not.
408   bool hasFunctions() { return ! FunctionSignatureList.empty(); }
409
410   /// @brief Determines if the type id has an implicit null value.
411   bool hasImplicitNull(unsigned TyID );
412
413   /// @brief Converts a type slot number to its Type*
414   const Type *getType(unsigned ID);
415
416   /// @brief Converts a pre-sanitized type slot number to its Type* and
417   /// sanitizes the type id.
418   inline const Type* getSanitizedType(unsigned& ID );
419
420   /// @brief Read in and get a sanitized type id
421   inline const Type* BytecodeReader::readSanitizedType();
422
423   /// @brief Converts a Type* to its type slot number
424   unsigned getTypeSlot(const Type *Ty);
425
426   /// @brief Converts a normal type slot number to a compacted type slot num.
427   unsigned getCompactionTypeSlot(unsigned type);
428
429   /// @brief Gets the global type corresponding to the TypeId
430   const Type *getGlobalTableType(unsigned TypeId);
431
432   /// This is just like getTypeSlot, but when a compaction table is in use,
433   /// it is ignored. 
434   unsigned getGlobalTableTypeSlot(const Type *Ty);
435   
436   /// @brief Get a value from its typeid and slot number
437   Value* getValue(unsigned TypeID, unsigned num, bool Create = true);
438
439   /// @brief Get a value from its type and slot number, ignoring compaction
440   /// tables.
441   Value *getGlobalTableValue(unsigned TyID, unsigned SlotNo);
442
443   /// @brief Get a basic block for current function
444   BasicBlock *getBasicBlock(unsigned ID);
445
446   /// @brief Get a constant value from its typeid and value slot.
447   Constant* getConstantValue(unsigned typeSlot, unsigned valSlot);
448
449   /// @brief Convenience function for getting a constant value when
450   /// the Type has already been resolved.
451   Constant* getConstantValue(const Type *Ty, unsigned valSlot) {
452     return getConstantValue(getTypeSlot(Ty), valSlot);
453   }
454
455   /// @brief Insert a newly created value
456   unsigned insertValue(Value *V, unsigned Type, ValueTable &Table);
457
458   /// @brief Insert the arguments of a function.
459   void insertArguments(Function* F );
460
461   /// @brief Resolve all references to the placeholder (if any) for the 
462   /// given constant.
463   void ResolveReferencesToConstant(Constant *C, unsigned Slot);
464
465   /// @brief Release our memory.
466   void freeState() {
467     freeTable(FunctionValues);
468     freeTable(ModuleValues);
469   }
470
471   /// @brief Free a table, making sure to free the ValueList in the table.
472   void freeTable(ValueTable &Tab) {
473     while (!Tab.empty()) {
474       delete Tab.back();
475       Tab.pop_back();
476     }
477   }
478
479   inline void error(std::string errmsg);
480
481   BytecodeReader(const BytecodeReader &);  // DO NOT IMPLEMENT
482   void operator=(const BytecodeReader &);  // DO NOT IMPLEMENT
483
484 /// @}
485 /// @name Reader Primitives
486 /// @{
487 private:
488
489   /// @brief Is there more to parse in the current block?
490   inline bool moreInBlock();
491
492   /// @brief Have we read past the end of the block
493   inline void checkPastBlockEnd(const char * block_name);
494
495   /// @brief Align to 32 bits
496   inline void align32();
497
498   /// @brief Read an unsigned integer as 32-bits
499   inline unsigned read_uint();
500
501   /// @brief Read an unsigned integer with variable bit rate encoding
502   inline unsigned read_vbr_uint();
503
504   /// @brief Read an unsigned integer of no more than 24-bits with variable
505   /// bit rate encoding.
506   inline unsigned read_vbr_uint24();
507
508   /// @brief Read an unsigned 64-bit integer with variable bit rate encoding.
509   inline uint64_t read_vbr_uint64();
510
511   /// @brief Read a signed 64-bit integer with variable bit rate encoding.
512   inline int64_t read_vbr_int64();
513
514   /// @brief Read a string
515   inline std::string read_str();
516
517   /// @brief Read a float value
518   inline void read_float(float& FloatVal);
519
520   /// @brief Read a double value
521   inline void read_double(double& DoubleVal);
522
523   /// @brief Read an arbitrary data chunk of fixed length
524   inline void read_data(void *Ptr, void *End);
525
526   /// @brief Read a bytecode block header
527   inline void read_block(unsigned &Type, unsigned &Size);
528
529   /// @brief Read a type identifier and sanitize it.
530   inline bool read_typeid(unsigned &TypeId);
531
532   /// @brief Recalculate type ID for pre 1.3 bytecode files.
533   inline bool sanitizeTypeId(unsigned &TypeId );
534 /// @}
535 };
536
537 /// @brief A function for creating a BytecodeAnalzer as a handler
538 /// for the Bytecode reader.
539 BytecodeHandler* createBytecodeAnalyzerHandler(BytecodeAnalysis& bca, 
540                                                std::ostream* output );
541
542
543 } // End llvm namespace
544
545 // vim: sw=2
546 #endif