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