blob: ad8b2655b720bcb0bc53cef97a2f174b14cc744c [file] [log] [blame]
Reid Spencerf89143c2004-06-29 23:31:01 +00001//===-- 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"
Reid Spencera86159c2004-07-04 11:04:56 +000024#include "llvm/Bytecode/Analyzer.h"
Reid Spencerf89143c2004-06-29 23:31:01 +000025#include <utility>
26#include <map>
27
28namespace llvm {
29
30class 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
41class BytecodeReader : public ModuleProvider {
42
43/// @name Constructors
44/// @{
45public:
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/// @{
58public:
Reid Spencerad89bd62004-07-25 18:07:36 +000059
Reid Spencerf89143c2004-06-29 23:31:01 +000060 /// @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 {
Reid Spencer89fc0e32004-07-18 00:13:12 +000076 ValueList() : User(Type::VoidTy, Value::ValueListVal) {}
Reid Spencerf89143c2004-06-29 23:31:01 +000077
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++ ) {
Reid Spencera86159c2004-07-04 11:04:56 +000087 os << i << " ";
88 getOperand(i)->print(os);
89 os << "\n";
Reid Spencerf89143c2004-06-29 23:31:01 +000090 }
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/// @{
128public:
Reid Spencerf89143c2004-06-29 23:31:01 +0000129 /// @brief Main interface to parsing a bytecode buffer.
130 void ParseBytecode(
Reid Spencer5c15fe52004-07-05 00:57:50 +0000131 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 bool processFunctions=false ///< Process all function bodies fully.
Reid Spencerf89143c2004-06-29 23:31:01 +0000135 );
136
Reid Spencerf89143c2004-06-29 23:31:01 +0000137 /// @brief Parse all function bodies
Reid Spencera86159c2004-07-04 11:04:56 +0000138 void ParseAllFunctionBodies();
Reid Spencerf89143c2004-06-29 23:31:01 +0000139
Reid Spencerf89143c2004-06-29 23:31:01 +0000140 /// @brief Parse the next function of specific type
Reid Spencera86159c2004-07-04 11:04:56 +0000141 void ParseFunction(Function* Func) ;
Reid Spencerf89143c2004-06-29 23:31:01 +0000142
143 /// This method is abstract in the parent ModuleProvider class. Its
144 /// implementation is identical to the ParseFunction method.
145 /// @see ParseFunction
146 /// @brief Make a specific function materialize.
147 virtual void materializeFunction(Function *F) {
148 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(F);
149 if (Fi == LazyFunctionLoadMap.end()) return;
150 ParseFunction(F);
151 }
152
153 /// This method is abstract in the parent ModuleProvider class. Its
154 /// implementation is identical to ParseAllFunctionBodies.
155 /// @see ParseAllFunctionBodies
156 /// @brief Make the whole module materialize
157 virtual Module* materializeModule() {
158 ParseAllFunctionBodies();
159 return TheModule;
160 }
161
162 /// This method is provided by the parent ModuleProvde class and overriden
163 /// here. It simply releases the module from its provided and frees up our
164 /// state.
165 /// @brief Release our hold on the generated module
166 Module* releaseModule() {
167 // Since we're losing control of this Module, we must hand it back complete
168 Module *M = ModuleProvider::releaseModule();
169 freeState();
170 return M;
171 }
172
173/// @}
174/// @name Parsing Units For Subclasses
175/// @{
176protected:
177 /// @brief Parse whole module scope
178 void ParseModule();
179
180 /// @brief Parse the version information block
181 void ParseVersionInfo();
182
183 /// @brief Parse the ModuleGlobalInfo block
184 void ParseModuleGlobalInfo();
185
186 /// @brief Parse a symbol table
187 void ParseSymbolTable( Function* Func, SymbolTable *ST);
188
Reid Spencerf89143c2004-06-29 23:31:01 +0000189 /// @brief Parse functions lazily.
190 void ParseFunctionLazily();
191
192 /// @brief Parse a function body
193 void ParseFunctionBody(Function* Func);
194
Reid Spencera86159c2004-07-04 11:04:56 +0000195 /// @brief Parse the type list portion of a compaction table
Chris Lattner45b5dd22004-08-03 23:41:28 +0000196 void ParseCompactionTypes(unsigned NumEntries);
Reid Spencera86159c2004-07-04 11:04:56 +0000197
Reid Spencerf89143c2004-06-29 23:31:01 +0000198 /// @brief Parse a compaction table
199 void ParseCompactionTable();
200
201 /// @brief Parse global types
202 void ParseGlobalTypes();
203
Reid Spencerf89143c2004-06-29 23:31:01 +0000204 /// @brief Parse a basic block (for LLVM 1.0 basic block blocks)
205 BasicBlock* ParseBasicBlock(unsigned BlockNo);
206
Reid Spencerf89143c2004-06-29 23:31:01 +0000207 /// @brief parse an instruction list (for post LLVM 1.0 instruction lists
208 /// with blocks differentiated by terminating instructions.
209 unsigned ParseInstructionList(
210 Function* F ///< The function into which BBs will be inserted
211 );
212
Reid Spencerf89143c2004-06-29 23:31:01 +0000213 /// @brief Parse a single instruction.
214 void ParseInstruction(
215 std::vector<unsigned>& Args, ///< The arguments to be filled in
216 BasicBlock* BB ///< The BB the instruction goes in
217 );
218
219 /// @brief Parse the whole constant pool
Reid Spencera86159c2004-07-04 11:04:56 +0000220 void ParseConstantPool(ValueTable& Values, TypeListTy& Types,
221 bool isFunction);
Reid Spencerf89143c2004-06-29 23:31:01 +0000222
223 /// @brief Parse a single constant value
224 Constant* ParseConstantValue(unsigned TypeID);
225
226 /// @brief Parse a block of types constants
Reid Spencer66906512004-07-11 17:24:05 +0000227 void ParseTypes(TypeListTy &Tab, unsigned NumEntries);
Reid Spencerf89143c2004-06-29 23:31:01 +0000228
229 /// @brief Parse a single type constant
Reid Spencer66906512004-07-11 17:24:05 +0000230 const Type *ParseType();
Reid Spencerf89143c2004-06-29 23:31:01 +0000231
232 /// @brief Parse a string constants block
233 void ParseStringConstants(unsigned NumEntries, ValueTable &Tab);
234
235/// @}
236/// @name Data
237/// @{
238private:
239 BufPtr MemStart; ///< Start of the memory buffer
240 BufPtr MemEnd; ///< End of the memory buffer
241 BufPtr BlockStart; ///< Start of current block being parsed
242 BufPtr BlockEnd; ///< End of current block being parsed
243 BufPtr At; ///< Where we're currently parsing at
244
Reid Spencera86159c2004-07-04 11:04:56 +0000245 /// Information about the module, extracted from the bytecode revision number.
Chris Lattner45b5dd22004-08-03 23:41:28 +0000246 ///
Reid Spencerf89143c2004-06-29 23:31:01 +0000247 unsigned char RevisionNum; // The rev # itself
248
Reid Spencera86159c2004-07-04 11:04:56 +0000249 /// Flags to distinguish LLVM 1.0 & 1.1 bytecode formats (revision #0)
Reid Spencerf89143c2004-06-29 23:31:01 +0000250
Chris Lattner45b5dd22004-08-03 23:41:28 +0000251 /// Revision #0 had an explicit alignment of data only for the
252 /// ModuleGlobalInfo block. This was fixed to be like all other blocks in 1.2
Reid Spencerf89143c2004-06-29 23:31:01 +0000253 bool hasInconsistentModuleGlobalInfo;
254
Reid Spencera86159c2004-07-04 11:04:56 +0000255 /// Revision #0 also explicitly encoded zero values for primitive types like
256 /// int/sbyte/etc.
Reid Spencerf89143c2004-06-29 23:31:01 +0000257 bool hasExplicitPrimitiveZeros;
258
259 // Flags to control features specific the LLVM 1.2 and before (revision #1)
260
Reid Spencera86159c2004-07-04 11:04:56 +0000261 /// LLVM 1.2 and earlier required that getelementptr structure indices were
262 /// ubyte constants and that sequential type indices were longs.
Reid Spencerf89143c2004-06-29 23:31:01 +0000263 bool hasRestrictedGEPTypes;
264
Reid Spencera86159c2004-07-04 11:04:56 +0000265 /// LLVM 1.2 and earlier had class Type deriving from Value and the Type
266 /// objects were located in the "Type Type" plane of various lists in read
267 /// by the bytecode reader. In LLVM 1.3 this is no longer the case. Types are
268 /// completely distinct from Values. Consequently, Types are written in fixed
269 /// locations in LLVM 1.3. This flag indicates that the older Type derived
270 /// from Value style of bytecode file is being read.
271 bool hasTypeDerivedFromValue;
272
Reid Spencerad89bd62004-07-25 18:07:36 +0000273 /// LLVM 1.2 and earlier encoded block headers as two uint (8 bytes), one for
Chris Lattner45b5dd22004-08-03 23:41:28 +0000274 /// the size and one for the type. This is a bit wasteful, especially for
275 /// small files where the 8 bytes per block is a large fraction of the total
276 /// block size. In LLVM 1.3, the block type and length are encoded into a
277 /// single uint32 by restricting the number of block types (limit 31) and the
278 /// maximum size of a block (limit 2^27-1=134,217,727). Note that the module
279 /// block still uses the 8-byte format so the maximum size of a file can be
Reid Spencerad89bd62004-07-25 18:07:36 +0000280 /// 2^32-1 bytes long.
281 bool hasLongBlockHeaders;
282
Reid Spencerad89bd62004-07-25 18:07:36 +0000283 /// LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
284 /// this has been reduced to vbr_uint24. It shouldn't make much difference
285 /// since we haven't run into a module with > 24 million types, but for safety
286 /// the 24-bit restriction has been enforced in 1.3 to free some bits in
287 /// various places and to ensure consistency. In particular, global vars are
288 /// restricted to 24-bits.
289 bool has32BitTypes;
290
291 /// LLVM 1.2 and earlier did not provide a target triple nor a list of
292 /// libraries on which the bytecode is dependent. LLVM 1.3 provides these
293 /// features, for use in future versions of LLVM.
294 bool hasNoDependentLibraries;
295
296 /// LLVM 1.2 and earlier encoded the file version as part of the module block
297 /// but this information may be needed to
298
Chris Lattner45b5dd22004-08-03 23:41:28 +0000299 /// CompactionTypes - If a compaction table is active in the current function,
300 /// this is the mapping that it contains. We keep track of what resolved type
301 /// it is as well as what global type entry it is.
302 std::vector<std::pair<const Type*, unsigned> > CompactionTypes;
Reid Spencerf89143c2004-06-29 23:31:01 +0000303
304 /// @brief If a compaction table is active in the current function,
305 /// this is the mapping that it contains.
306 std::vector<std::vector<Value*> > CompactionValues;
307
308 /// @brief This vector is used to deal with forward references to types in
309 /// a module.
310 TypeListTy ModuleTypes;
311
312 /// @brief This vector is used to deal with forward references to types in
313 /// a function.
314 TypeListTy FunctionTypes;
315
316 /// When the ModuleGlobalInfo section is read, we create a Function object
317 /// for each function in the module. When the function is loaded, after the
318 /// module global info is read, this Function is populated. Until then, the
319 /// functions in this vector just hold the function signature.
320 std::vector<Function*> FunctionSignatureList;
321
322 /// @brief This is the table of values belonging to the current function
323 ValueTable FunctionValues;
324
325 /// @brief This is the table of values belonging to the module (global)
326 ValueTable ModuleValues;
327
328 /// @brief This keeps track of function level forward references.
329 ForwardReferenceMap ForwardReferences;
330
331 /// @brief The basic blocks we've parsed, while parsing a function.
332 std::vector<BasicBlock*> ParsedBasicBlocks;
333
334 /// This maintains a mapping between <Type, Slot #>'s and
335 /// forward references to constants. Such values may be referenced before they
336 /// are defined, and if so, the temporary object that they represent is held
337 /// here.
338 /// @brief Temporary place for forward references to constants.
339 ConstantRefsType ConstantFwdRefs;
340
341 /// Constant values are read in after global variables. Because of this, we
342 /// must defer setting the initializers on global variables until after module
343 /// level constants have been read. In the mean time, this list keeps track of
344 /// what we must do.
345 GlobalInitsList GlobalInits;
346
347 // For lazy reading-in of functions, we need to save away several pieces of
348 // information about each function: its begin and end pointer in the buffer
349 // and its FunctionSlot.
350 LazyFunctionMap LazyFunctionLoadMap;
351
352 /// This stores the parser's handler which is used for handling tasks other
353 /// just than reading bytecode into the IR. If this is non-null, calls on
354 /// the (polymorphic) BytecodeHandler interface (see llvm/Bytecode/Handler.h)
355 /// will be made to report the logical structure of the bytecode file. What
356 /// the handler does with the events it receives is completely orthogonal to
357 /// the business of parsing the bytecode and building the IR. This is used,
358 /// for example, by the llvm-abcd tool for analysis of byte code.
359 /// @brief Handler for parsing events.
360 BytecodeHandler* Handler;
361
362/// @}
363/// @name Implementation Details
364/// @{
365private:
366 /// @brief Determines if this module has a function or not.
367 bool hasFunctions() { return ! FunctionSignatureList.empty(); }
368
369 /// @brief Determines if the type id has an implicit null value.
370 bool hasImplicitNull(unsigned TyID );
371
372 /// @brief Converts a type slot number to its Type*
373 const Type *getType(unsigned ID);
374
Reid Spencera86159c2004-07-04 11:04:56 +0000375 /// @brief Converts a pre-sanitized type slot number to its Type* and
376 /// sanitizes the type id.
377 inline const Type* getSanitizedType(unsigned& ID );
378
379 /// @brief Read in and get a sanitized type id
380 inline const Type* BytecodeReader::readSanitizedType();
381
Reid Spencerf89143c2004-06-29 23:31:01 +0000382 /// @brief Converts a Type* to its type slot number
383 unsigned getTypeSlot(const Type *Ty);
384
385 /// @brief Converts a normal type slot number to a compacted type slot num.
386 unsigned getCompactionTypeSlot(unsigned type);
387
Reid Spencera86159c2004-07-04 11:04:56 +0000388 /// @brief Gets the global type corresponding to the TypeId
389 const Type *getGlobalTableType(unsigned TypeId);
Reid Spencerf89143c2004-06-29 23:31:01 +0000390
391 /// This is just like getTypeSlot, but when a compaction table is in use,
392 /// it is ignored.
393 unsigned getGlobalTableTypeSlot(const Type *Ty);
394
Reid Spencera86159c2004-07-04 11:04:56 +0000395 /// @brief Get a value from its typeid and slot number
Reid Spencerf89143c2004-06-29 23:31:01 +0000396 Value* getValue(unsigned TypeID, unsigned num, bool Create = true);
397
Chris Lattner2c6c14d2004-08-04 00:19:23 +0000398 /// @brief Get a value from its type and slot number, ignoring compaction
399 /// tables.
400 Value *getGlobalTableValue(unsigned TyID, unsigned SlotNo);
Reid Spencerf89143c2004-06-29 23:31:01 +0000401
Reid Spencerf89143c2004-06-29 23:31:01 +0000402 /// @brief Get a basic block for current function
403 BasicBlock *getBasicBlock(unsigned ID);
404
Reid Spencera86159c2004-07-04 11:04:56 +0000405 /// @brief Get a constant value from its typeid and value slot.
Reid Spencerf89143c2004-06-29 23:31:01 +0000406 Constant* getConstantValue(unsigned typeSlot, unsigned valSlot);
407
408 /// @brief Convenience function for getting a constant value when
409 /// the Type has already been resolved.
410 Constant* getConstantValue(const Type *Ty, unsigned valSlot) {
411 return getConstantValue(getTypeSlot(Ty), valSlot);
412 }
413
Reid Spencerf89143c2004-06-29 23:31:01 +0000414 /// @brief Insert a newly created value
415 unsigned insertValue(Value *V, unsigned Type, ValueTable &Table);
416
417 /// @brief Insert the arguments of a function.
418 void insertArguments(Function* F );
419
420 /// @brief Resolve all references to the placeholder (if any) for the
421 /// given constant.
422 void ResolveReferencesToConstant(Constant *C, unsigned Slot);
423
424 /// @brief Release our memory.
425 void freeState() {
426 freeTable(FunctionValues);
427 freeTable(ModuleValues);
428 }
429
430 /// @brief Free a table, making sure to free the ValueList in the table.
431 void freeTable(ValueTable &Tab) {
432 while (!Tab.empty()) {
433 delete Tab.back();
434 Tab.pop_back();
435 }
436 }
437
Reid Spencer24399722004-07-09 22:21:33 +0000438 inline void error(std::string errmsg);
439
Reid Spencerf89143c2004-06-29 23:31:01 +0000440 BytecodeReader(const BytecodeReader &); // DO NOT IMPLEMENT
441 void operator=(const BytecodeReader &); // DO NOT IMPLEMENT
442
443/// @}
444/// @name Reader Primitives
445/// @{
446private:
447
448 /// @brief Is there more to parse in the current block?
449 inline bool moreInBlock();
450
451 /// @brief Have we read past the end of the block
452 inline void checkPastBlockEnd(const char * block_name);
453
454 /// @brief Align to 32 bits
455 inline void align32();
456
457 /// @brief Read an unsigned integer as 32-bits
458 inline unsigned read_uint();
459
460 /// @brief Read an unsigned integer with variable bit rate encoding
461 inline unsigned read_vbr_uint();
462
Reid Spencerad89bd62004-07-25 18:07:36 +0000463 /// @brief Read an unsigned integer of no more than 24-bits with variable
464 /// bit rate encoding.
465 inline unsigned read_vbr_uint24();
466
Reid Spencerf89143c2004-06-29 23:31:01 +0000467 /// @brief Read an unsigned 64-bit integer with variable bit rate encoding.
468 inline uint64_t read_vbr_uint64();
469
470 /// @brief Read a signed 64-bit integer with variable bit rate encoding.
471 inline int64_t read_vbr_int64();
472
473 /// @brief Read a string
474 inline std::string read_str();
475
Reid Spencer66906512004-07-11 17:24:05 +0000476 /// @brief Read a float value
477 inline void read_float(float& FloatVal);
478
479 /// @brief Read a double value
480 inline void read_double(double& DoubleVal);
481
Reid Spencerf89143c2004-06-29 23:31:01 +0000482 /// @brief Read an arbitrary data chunk of fixed length
483 inline void read_data(void *Ptr, void *End);
484
Reid Spencera86159c2004-07-04 11:04:56 +0000485 /// @brief Read a bytecode block header
Reid Spencerf89143c2004-06-29 23:31:01 +0000486 inline void read_block(unsigned &Type, unsigned &Size);
487
Reid Spencera86159c2004-07-04 11:04:56 +0000488 /// @brief Read a type identifier and sanitize it.
489 inline bool read_typeid(unsigned &TypeId);
490
491 /// @brief Recalculate type ID for pre 1.3 bytecode files.
492 inline bool sanitizeTypeId(unsigned &TypeId );
Reid Spencerf89143c2004-06-29 23:31:01 +0000493/// @}
494};
495
Reid Spencera86159c2004-07-04 11:04:56 +0000496/// @brief A function for creating a BytecodeAnalzer as a handler
497/// for the Bytecode reader.
498BytecodeHandler* createBytecodeAnalyzerHandler(BytecodeAnalysis& bca );
499
500
Reid Spencerf89143c2004-06-29 23:31:01 +0000501} // End llvm namespace
502
503// vim: sw=2
504#endif