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"
31 class BytecodeHandler; ///< Forward declare the handler interface
33 /// This class defines the interface for parsing a buffer of bytecode. The
34 /// parser itself takes no action except to call the various functions of
35 /// the handler interface. The parser's sole responsibility is the correct
36 /// interpretation of the bytecode buffer. The handler is responsible for
37 /// instantiating and keeping track of all values. As a convenience, the parser
38 /// is responsible for materializing types and will pass them through the
39 /// handler interface as necessary.
40 /// @see BytecodeHandler
41 /// @brief Bytecode Reader interface
42 class BytecodeReader : public ModuleProvider {
44 /// @name Constructors
47 /// @brief Default constructor. By default, no handler is used.
48 BytecodeReader(BytecodeHandler* h = 0) {
49 decompressedBlock = 0;
55 if (decompressedBlock) {
56 ::free(decompressedBlock);
57 decompressedBlock = 0;
66 /// @brief A convenience type for the buffer pointer
67 typedef const unsigned char* BufPtr;
69 /// @brief The type used for a vector of potentially abstract types
70 typedef std::vector<PATypeHolder> TypeListTy;
72 /// This type provides a vector of Value* via the User class for
73 /// storage of Values that have been constructed when reading the
74 /// bytecode. Because of forward referencing, constant replacement
75 /// can occur so we ensure that our list of Value* is updated
76 /// properly through those transitions. This ensures that the
77 /// correct Value* is in our list when it comes time to associate
78 /// constants with global variables at the end of reading the
80 /// @brief A list of values as a User of those Values.
81 class ValueList : public User {
82 std::vector<Use> Uses;
84 ValueList() : User(Type::VoidTy, Value::ArgumentVal, 0, 0) {}
86 // vector compatibility methods
87 unsigned size() const { return getNumOperands(); }
88 void push_back(Value *V) {
89 Uses.push_back(Use(V, this));
90 OperandList = &Uses[0];
93 Value *back() const { return Uses.back(); }
94 void pop_back() { Uses.pop_back(); --NumOperands; }
95 bool empty() const { return NumOperands == 0; }
96 virtual void print(std::ostream& os) const {
97 for (unsigned i = 0; i < size(); ++i) {
99 getOperand(i)->print(os);
105 /// @brief A 2 dimensional table of values
106 typedef std::vector<ValueList*> ValueTable;
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<unsigned,unsigned>, Constant*> ConstantRefsType;
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) {}
124 /// @brief A mapping of functions to their LazyFunctionInfo for lazy reading.
125 typedef std::map<Function*, LazyFunctionInfo> LazyFunctionMap;
127 /// @brief A list of global variables and the slot number that initializes
129 typedef std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitsList;
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;
140 /// @returns true if an error occurred
141 /// @brief Main interface to parsing a bytecode buffer.
143 volatile BufPtr Buf, ///< Beginning of the bytecode buffer
144 unsigned Length, ///< Length of the bytecode buffer
145 const std::string &ModuleID, ///< An identifier for the module constructed.
146 std::string* ErrMsg = 0 ///< Optional place for error message
149 /// @brief Parse all function bodies
150 bool ParseAllFunctionBodies(std::string* ErrMsg);
152 /// @brief Parse the next function of specific type
153 bool ParseFunction(Function* Func, std::string* ErrMsg) ;
155 /// This method is abstract in the parent ModuleProvider class. Its
156 /// implementation is identical to the ParseFunction method.
157 /// @see ParseFunction
158 /// @brief Make a specific function materialize.
159 virtual bool materializeFunction(Function *F, std::string *ErrMsg = 0) {
160 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(F);
161 if (Fi == LazyFunctionLoadMap.end())
163 if (ParseFunction(F,ErrMsg))
168 /// This method is abstract in the parent ModuleProvider class. Its
169 /// implementation is identical to ParseAllFunctionBodies.
170 /// @see ParseAllFunctionBodies
171 /// @brief Make the whole module materialize
172 virtual Module* materializeModule(std::string *ErrMsg = 0) {
173 if (ParseAllFunctionBodies(ErrMsg))
178 /// This method is provided by the parent ModuleProvde class and overriden
179 /// here. It simply releases the module from its provided and frees up our
181 /// @brief Release our hold on the generated module
182 Module* releaseModule(std::string *ErrInfo = 0) {
183 // Since we're losing control of this Module, we must hand it back complete
184 Module *M = ModuleProvider::releaseModule();
190 /// @name Parsing Units For Subclasses
193 /// @brief Parse whole module scope
196 /// @brief Parse the version information block
197 void ParseVersionInfo();
199 /// @brief Parse the ModuleGlobalInfo block
200 void ParseModuleGlobalInfo();
202 /// @brief Parse a symbol table
203 void ParseSymbolTable( Function* Func, SymbolTable *ST);
205 /// @brief Parse functions lazily.
206 void ParseFunctionLazily();
208 /// @brief Parse a function body
209 void ParseFunctionBody(Function* Func);
211 /// @brief Parse the type list portion of a compaction table
212 void ParseCompactionTypes(unsigned NumEntries);
214 /// @brief Parse a compaction table
215 void ParseCompactionTable();
217 /// @brief Parse global types
218 void ParseGlobalTypes();
220 /// @brief Parse a basic block (for LLVM 1.0 basic block blocks)
221 BasicBlock* ParseBasicBlock(unsigned BlockNo);
223 /// @brief parse an instruction list (for post LLVM 1.0 instruction lists
224 /// with blocks differentiated by terminating instructions.
225 unsigned ParseInstructionList(
226 Function* F ///< The function into which BBs will be inserted
229 /// @brief Parse a single instruction.
230 void ParseInstruction(
231 std::vector<unsigned>& Args, ///< The arguments to be filled in
232 BasicBlock* BB ///< The BB the instruction goes in
235 /// @brief Parse the whole constant pool
236 void ParseConstantPool(ValueTable& Values, TypeListTy& Types,
239 /// @brief Parse a single constant pool value
240 Value *ParseConstantPoolValue(unsigned TypeID);
242 /// @brief Parse a block of types constants
243 void ParseTypes(TypeListTy &Tab, unsigned NumEntries);
245 /// @brief Parse a single type constant
246 const Type *ParseType();
248 /// @brief Parse a string constants block
249 void ParseStringConstants(unsigned NumEntries, ValueTable &Tab);
255 std::string ErrorMsg; ///< A place to hold an error message through longjmp
256 jmp_buf context; ///< Where to return to if an error occurs.
257 char* decompressedBlock; ///< Result of decompression
258 BufPtr MemStart; ///< Start of the memory buffer
259 BufPtr MemEnd; ///< End of the memory buffer
260 BufPtr BlockStart; ///< Start of current block being parsed
261 BufPtr BlockEnd; ///< End of current block being parsed
262 BufPtr At; ///< Where we're currently parsing at
264 /// Information about the module, extracted from the bytecode revision number.
266 unsigned char RevisionNum; // The rev # itself
268 /// Flags to distinguish LLVM 1.0 & 1.1 bytecode formats (revision #0)
270 /// Revision #0 had an explicit alignment of data only for the
271 /// ModuleGlobalInfo block. This was fixed to be like all other blocks in 1.2
272 bool hasInconsistentModuleGlobalInfo;
274 /// Revision #0 also explicitly encoded zero values for primitive types like
276 bool hasExplicitPrimitiveZeros;
278 // Flags to control features specific the LLVM 1.2 and before (revision #1)
280 /// LLVM 1.2 and earlier required that getelementptr structure indices were
281 /// ubyte constants and that sequential type indices were longs.
282 bool hasRestrictedGEPTypes;
284 /// LLVM 1.2 and earlier had class Type deriving from Value and the Type
285 /// objects were located in the "Type Type" plane of various lists in read
286 /// by the bytecode reader. In LLVM 1.3 this is no longer the case. Types are
287 /// completely distinct from Values. Consequently, Types are written in fixed
288 /// locations in LLVM 1.3. This flag indicates that the older Type derived
289 /// from Value style of bytecode file is being read.
290 bool hasTypeDerivedFromValue;
292 /// LLVM 1.2 and earlier encoded block headers as two uint (8 bytes), one for
293 /// the size and one for the type. This is a bit wasteful, especially for
294 /// small files where the 8 bytes per block is a large fraction of the total
295 /// block size. In LLVM 1.3, the block type and length are encoded into a
296 /// single uint32 by restricting the number of block types (limit 31) and the
297 /// maximum size of a block (limit 2^27-1=134,217,727). Note that the module
298 /// block still uses the 8-byte format so the maximum size of a file can be
299 /// 2^32-1 bytes long.
300 bool hasLongBlockHeaders;
302 /// LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
303 /// this has been reduced to vbr_uint24. It shouldn't make much difference
304 /// since we haven't run into a module with > 24 million types, but for safety
305 /// the 24-bit restriction has been enforced in 1.3 to free some bits in
306 /// various places and to ensure consistency. In particular, global vars are
307 /// restricted to 24-bits.
310 /// LLVM 1.2 and earlier did not provide a target triple nor a list of
311 /// libraries on which the bytecode is dependent. LLVM 1.3 provides these
312 /// features, for use in future versions of LLVM.
313 bool hasNoDependentLibraries;
315 /// LLVM 1.3 and earlier caused blocks and other fields to start on 32-bit
316 /// aligned boundaries. This can lead to as much as 30% bytecode size overhead
317 /// in various corner cases (lots of long instructions). In LLVM 1.4,
318 /// alignment of bytecode fields was done away with completely.
321 // In version 4 and earlier, the bytecode format did not support the 'undef'
323 bool hasNoUndefValue;
325 // In version 4 and earlier, the bytecode format did not save space for flags
326 // in the global info block for functions.
327 bool hasNoFlagsForFunctions;
329 // In version 4 and earlier, there was no opcode space reserved for the
330 // unreachable instruction.
331 bool hasNoUnreachableInst;
333 /// In release 1.7 we changed intrinsic functions to not be overloaded. There
334 /// is no bytecode change for this, but to optimize the auto-upgrade of calls
335 /// to intrinsic functions, we save a mapping of old function definitions to
336 /// the new ones so call instructions can be upgraded efficiently.
337 std::map<Function*,Function*> upgradedFunctions;
339 /// CompactionTypes - If a compaction table is active in the current function,
340 /// this is the mapping that it contains. We keep track of what resolved type
341 /// it is as well as what global type entry it is.
342 std::vector<std::pair<const Type*, unsigned> > CompactionTypes;
344 /// @brief If a compaction table is active in the current function,
345 /// this is the mapping that it contains.
346 std::vector<std::vector<Value*> > CompactionValues;
348 /// @brief This vector is used to deal with forward references to types in
350 TypeListTy ModuleTypes;
352 /// @brief This is an inverse mapping of ModuleTypes from the type to an
353 /// index. Because refining types causes the index of this map to be
354 /// invalidated, any time we refine a type, we clear this cache and recompute
355 /// it next time we need it. These entries are ordered by the pointer value.
356 std::vector<std::pair<const Type*, unsigned> > ModuleTypeIDCache;
358 /// @brief This vector is used to deal with forward references to types in
360 TypeListTy FunctionTypes;
362 /// When the ModuleGlobalInfo section is read, we create a Function object
363 /// for each function in the module. When the function is loaded, after the
364 /// module global info is read, this Function is populated. Until then, the
365 /// functions in this vector just hold the function signature.
366 std::vector<Function*> FunctionSignatureList;
368 /// @brief This is the table of values belonging to the current function
369 ValueTable FunctionValues;
371 /// @brief This is the table of values belonging to the module (global)
372 ValueTable ModuleValues;
374 /// @brief This keeps track of function level forward references.
375 ForwardReferenceMap ForwardReferences;
377 /// @brief The basic blocks we've parsed, while parsing a function.
378 std::vector<BasicBlock*> ParsedBasicBlocks;
380 /// This maintains a mapping between <Type, Slot #>'s and forward references
381 /// to constants. Such values may be referenced before they are defined, and
382 /// if so, the temporary object that they represent is held here. @brief
383 /// Temporary place for forward references to constants.
384 ConstantRefsType ConstantFwdRefs;
386 /// Constant values are read in after global variables. Because of this, we
387 /// must defer setting the initializers on global variables until after module
388 /// level constants have been read. In the mean time, this list keeps track
389 /// of what we must do.
390 GlobalInitsList GlobalInits;
392 // For lazy reading-in of functions, we need to save away several pieces of
393 // information about each function: its begin and end pointer in the buffer
394 // and its FunctionSlot.
395 LazyFunctionMap LazyFunctionLoadMap;
397 /// This stores the parser's handler which is used for handling tasks other
398 /// just than reading bytecode into the IR. If this is non-null, calls on
399 /// the (polymorphic) BytecodeHandler interface (see llvm/Bytecode/Handler.h)
400 /// will be made to report the logical structure of the bytecode file. What
401 /// the handler does with the events it receives is completely orthogonal to
402 /// the business of parsing the bytecode and building the IR. This is used,
403 /// for example, by the llvm-abcd tool for analysis of byte code.
404 /// @brief Handler for parsing events.
405 BytecodeHandler* Handler;
409 /// @name Implementation Details
412 /// @brief Determines if this module has a function or not.
413 bool hasFunctions() { return ! FunctionSignatureList.empty(); }
415 /// @brief Determines if the type id has an implicit null value.
416 bool hasImplicitNull(unsigned TyID );
418 /// @brief Converts a type slot number to its Type*
419 const Type *getType(unsigned ID);
421 /// @brief Converts a pre-sanitized type slot number to its Type* and
422 /// sanitizes the type id.
423 inline const Type* getSanitizedType(unsigned& ID );
425 /// @brief Read in and get a sanitized type id
426 inline const Type* readSanitizedType();
428 /// @brief Converts a Type* to its type slot number
429 unsigned getTypeSlot(const Type *Ty);
431 /// @brief Converts a normal type slot number to a compacted type slot num.
432 unsigned getCompactionTypeSlot(unsigned type);
434 /// @brief Gets the global type corresponding to the TypeId
435 const Type *getGlobalTableType(unsigned TypeId);
437 /// This is just like getTypeSlot, but when a compaction table is in use,
439 unsigned getGlobalTableTypeSlot(const Type *Ty);
441 /// @brief Get a value from its typeid and slot number
442 Value* getValue(unsigned TypeID, unsigned num, bool Create = true);
444 /// @brief Get a value from its type and slot number, ignoring compaction
446 Value *getGlobalTableValue(unsigned TyID, unsigned SlotNo);
448 /// @brief Get a basic block for current function
449 BasicBlock *getBasicBlock(unsigned ID);
451 /// @brief Get a constant value from its typeid and value slot.
452 Constant* getConstantValue(unsigned typeSlot, unsigned valSlot);
454 /// @brief Convenience function for getting a constant value when
455 /// the Type has already been resolved.
456 Constant* getConstantValue(const Type *Ty, unsigned valSlot) {
457 return getConstantValue(getTypeSlot(Ty), valSlot);
460 /// @brief Insert a newly created value
461 unsigned insertValue(Value *V, unsigned Type, ValueTable &Table);
463 /// @brief Insert the arguments of a function.
464 void insertArguments(Function* F );
466 /// @brief Resolve all references to the placeholder (if any) for the
468 void ResolveReferencesToConstant(Constant *C, unsigned Typ, unsigned Slot);
470 /// @brief Release our memory.
472 freeTable(FunctionValues);
473 freeTable(ModuleValues);
476 /// @brief Free a table, making sure to free the ValueList in the table.
477 void freeTable(ValueTable &Tab) {
478 while (!Tab.empty()) {
484 inline void error(const std::string& errmsg);
486 BytecodeReader(const BytecodeReader &); // DO NOT IMPLEMENT
487 void operator=(const BytecodeReader &); // DO NOT IMPLEMENT
490 /// @name Reader Primitives
494 /// @brief Is there more to parse in the current block?
495 inline bool moreInBlock();
497 /// @brief Have we read past the end of the block
498 inline void checkPastBlockEnd(const char * block_name);
500 /// @brief Align to 32 bits
501 inline void align32();
503 /// @brief Read an unsigned integer as 32-bits
504 inline unsigned read_uint();
506 /// @brief Read an unsigned integer with variable bit rate encoding
507 inline unsigned read_vbr_uint();
509 /// @brief Read an unsigned integer of no more than 24-bits with variable
510 /// bit rate encoding.
511 inline unsigned read_vbr_uint24();
513 /// @brief Read an unsigned 64-bit integer with variable bit rate encoding.
514 inline uint64_t read_vbr_uint64();
516 /// @brief Read a signed 64-bit integer with variable bit rate encoding.
517 inline int64_t read_vbr_int64();
519 /// @brief Read a string
520 inline std::string read_str();
522 /// @brief Read a float value
523 inline void read_float(float& FloatVal);
525 /// @brief Read a double value
526 inline void read_double(double& DoubleVal);
528 /// @brief Read an arbitrary data chunk of fixed length
529 inline void read_data(void *Ptr, void *End);
531 /// @brief Read a bytecode block header
532 inline void read_block(unsigned &Type, unsigned &Size);
534 /// @brief Read a type identifier and sanitize it.
535 inline bool read_typeid(unsigned &TypeId);
537 /// @brief Recalculate type ID for pre 1.3 bytecode files.
538 inline bool sanitizeTypeId(unsigned &TypeId );
542 /// @brief A function for creating a BytecodeAnalzer as a handler
543 /// for the Bytecode reader.
544 BytecodeHandler* createBytecodeAnalyzerHandler(BytecodeAnalysis& bca,
545 std::ostream* output );
548 } // End llvm namespace