1 //===-- Reader.h - Interface To Bytecode Reading ----------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
16 #ifndef BYTECODE_PARSER_H
17 #define BYTECODE_PARSER_H
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"
30 class BytecodeHandler; ///< Forward declare the handler interface
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 {
43 /// @name Constructors
46 /// @brief Default constructor. By default, no handler is used.
48 BytecodeHandler* h = 0
53 ~BytecodeReader() { freeState(); }
59 /// @brief A convenience type for the buffer pointer
60 typedef const unsigned char* BufPtr;
62 /// @brief The type used for a vector of potentially abstract types
63 typedef std::vector<PATypeHolder> TypeListTy;
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
73 /// @brief A list of values as a User of those Values.
74 struct ValueList : public User {
75 ValueList() : User(Type::VoidTy, Value::FunctionVal) {}
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(); }
84 virtual void print(std::ostream& os) const {
85 for ( unsigned i = 0; i < size(); i++ ) {
87 getOperand(i)->print(os);
93 /// @brief A 2 dimensional table of values
94 typedef std::vector<ValueList*> ValueTable;
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;
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) {}
112 /// @brief A mapping of functions to their LazyFunctionInfo for lazy reading.
113 typedef std::map<Function*, LazyFunctionInfo> LazyFunctionMap;
115 /// @brief A list of global variables and the slot number that initializes
117 typedef std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitsList;
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;
128 /// @brief Main interface to parsing a bytecode buffer.
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.
136 /// @brief Parse all function bodies
137 void ParseAllFunctionBodies();
139 /// @brief Parse the next function of specific type
140 void ParseFunction(Function* Func) ;
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;
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();
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
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();
173 /// @name Parsing Units For Subclasses
176 /// @brief Parse whole module scope
179 /// @brief Parse the version information block
180 void ParseVersionInfo();
182 /// @brief Parse the ModuleGlobalInfo block
183 void ParseModuleGlobalInfo();
185 /// @brief Parse a symbol table
186 void ParseSymbolTable( Function* Func, SymbolTable *ST);
188 /// @brief Parse functions lazily.
189 void ParseFunctionLazily();
191 /// @brief Parse a function body
192 void ParseFunctionBody(Function* Func);
194 /// @brief Parse the type list portion of a compaction table
195 void BytecodeReader::ParseCompactionTypes( unsigned NumEntries );
197 /// @brief Parse a compaction table
198 void ParseCompactionTable();
200 /// @brief Parse global types
201 void ParseGlobalTypes();
203 /// @brief Parse a basic block (for LLVM 1.0 basic block blocks)
204 BasicBlock* ParseBasicBlock(unsigned BlockNo);
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
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
218 /// @brief Parse the whole constant pool
219 void ParseConstantPool(ValueTable& Values, TypeListTy& Types,
222 /// @brief Parse a single constant value
223 Constant* ParseConstantValue(unsigned TypeID);
225 /// @brief Parse a block of types constants
226 void ParseTypes(TypeListTy &Tab, unsigned NumEntries);
228 /// @brief Parse a single type constant
229 const Type *ParseType();
231 /// @brief Parse a string constants block
232 void ParseStringConstants(unsigned NumEntries, ValueTable &Tab);
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
244 /// Information about the module, extracted from the bytecode revision number.
245 unsigned char RevisionNum; // The rev # itself
247 /// Flags to distinguish LLVM 1.0 & 1.1 bytecode formats (revision #0)
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;
253 /// Revision #0 also explicitly encoded zero values for primitive types like
255 bool hasExplicitPrimitiveZeros;
257 // Flags to control features specific the LLVM 1.2 and before (revision #1)
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;
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;
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;
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;
279 /// @brief This vector is used to deal with forward references to types in
281 TypeListTy ModuleTypes;
283 /// @brief This vector is used to deal with forward references to types in
285 TypeListTy FunctionTypes;
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;
293 /// @brief This is the table of values belonging to the current function
294 ValueTable FunctionValues;
296 /// @brief This is the table of values belonging to the module (global)
297 ValueTable ModuleValues;
299 /// @brief This keeps track of function level forward references.
300 ForwardReferenceMap ForwardReferences;
302 /// @brief The basic blocks we've parsed, while parsing a function.
303 std::vector<BasicBlock*> ParsedBasicBlocks;
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
309 /// @brief Temporary place for forward references to constants.
310 ConstantRefsType ConstantFwdRefs;
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
316 GlobalInitsList GlobalInits;
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;
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;
334 /// @name Implementation Details
337 /// @brief Determines if this module has a function or not.
338 bool hasFunctions() { return ! FunctionSignatureList.empty(); }
340 /// @brief Determines if the type id has an implicit null value.
341 bool hasImplicitNull(unsigned TyID );
343 /// @brief Converts a type slot number to its Type*
344 const Type *getType(unsigned ID);
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 );
350 /// @brief Read in and get a sanitized type id
351 inline const Type* BytecodeReader::readSanitizedType();
353 /// @brief Converts a Type* to its type slot number
354 unsigned getTypeSlot(const Type *Ty);
356 /// @brief Converts a normal type slot number to a compacted type slot num.
357 unsigned getCompactionTypeSlot(unsigned type);
359 /// @brief Gets the global type corresponding to the TypeId
360 const Type *getGlobalTableType(unsigned TypeId);
362 /// This is just like getTypeSlot, but when a compaction table is in use,
364 unsigned getGlobalTableTypeSlot(const Type *Ty);
366 /// @brief Get a value from its typeid and slot number
367 Value* getValue(unsigned TypeID, unsigned num, bool Create = true);
369 /// @brief Get a value from its type and slot number, ignoring compaction tables.
370 Value *getGlobalTableValue(const Type *Ty, unsigned SlotNo);
372 /// @brief Get a basic block for current function
373 BasicBlock *getBasicBlock(unsigned ID);
375 /// @brief Get a constant value from its typeid and value slot.
376 Constant* getConstantValue(unsigned typeSlot, unsigned valSlot);
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);
384 /// @brief Insert a newly created value
385 unsigned insertValue(Value *V, unsigned Type, ValueTable &Table);
387 /// @brief Insert the arguments of a function.
388 void insertArguments(Function* F );
390 /// @brief Resolve all references to the placeholder (if any) for the
392 void ResolveReferencesToConstant(Constant *C, unsigned Slot);
394 /// @brief Release our memory.
396 freeTable(FunctionValues);
397 freeTable(ModuleValues);
400 /// @brief Free a table, making sure to free the ValueList in the table.
401 void freeTable(ValueTable &Tab) {
402 while (!Tab.empty()) {
408 inline void error(std::string errmsg);
410 BytecodeReader(const BytecodeReader &); // DO NOT IMPLEMENT
411 void operator=(const BytecodeReader &); // DO NOT IMPLEMENT
414 /// @name Reader Primitives
418 /// @brief Is there more to parse in the current block?
419 inline bool moreInBlock();
421 /// @brief Have we read past the end of the block
422 inline void checkPastBlockEnd(const char * block_name);
424 /// @brief Align to 32 bits
425 inline void align32();
427 /// @brief Read an unsigned integer as 32-bits
428 inline unsigned read_uint();
430 /// @brief Read an unsigned integer with variable bit rate encoding
431 inline unsigned read_vbr_uint();
433 /// @brief Read an unsigned 64-bit integer with variable bit rate encoding.
434 inline uint64_t read_vbr_uint64();
436 /// @brief Read a signed 64-bit integer with variable bit rate encoding.
437 inline int64_t read_vbr_int64();
439 /// @brief Read a string
440 inline std::string read_str();
442 /// @brief Read a float value
443 inline void read_float(float& FloatVal);
445 /// @brief Read a double value
446 inline void read_double(double& DoubleVal);
448 /// @brief Read an arbitrary data chunk of fixed length
449 inline void read_data(void *Ptr, void *End);
451 /// @brief Read a bytecode block header
452 inline void read_block(unsigned &Type, unsigned &Size);
454 /// @brief Read a type identifier and sanitize it.
455 inline bool read_typeid(unsigned &TypeId);
457 /// @brief Recalculate type ID for pre 1.3 bytecode files.
458 inline bool sanitizeTypeId(unsigned &TypeId );
462 /// @brief A function for creating a BytecodeAnalzer as a handler
463 /// for the Bytecode reader.
464 BytecodeHandler* createBytecodeAnalyzerHandler(BytecodeAnalysis& bca );
467 } // End llvm namespace