1 //===- BitstreamReader.h - Low-level bitstream reader interface -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This header defines the BitstreamReader class. This class can be used to
11 // read an arbitrary bitstream, regardless of its contents.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_BITCODE_BITSTREAMREADER_H
16 #define LLVM_BITCODE_BITSTREAMREADER_H
18 #include "llvm/ADT/OwningPtr.h"
19 #include "llvm/Bitcode/BitCodes.h"
20 #include "llvm/Support/Endian.h"
21 #include "llvm/Support/StreamableMemoryObject.h"
30 /// BitstreamReader - This class is used to read from an LLVM bitcode stream,
31 /// maintaining information that is global to decoding the entire file. While
32 /// a file is being read, multiple cursors can be independently advanced or
33 /// skipped around within the file. These are represented by the
34 /// BitstreamCursor class.
35 class BitstreamReader {
37 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
38 /// These describe abbreviations that all blocks of the specified ID inherit.
41 std::vector<BitCodeAbbrev*> Abbrevs;
44 std::vector<std::pair<unsigned, std::string> > RecordNames;
47 OwningPtr<StreamableMemoryObject> BitcodeBytes;
49 std::vector<BlockInfo> BlockInfoRecords;
51 /// IgnoreBlockInfoNames - This is set to true if we don't care about the
52 /// block/record name information in the BlockInfo block. Only llvm-bcanalyzer
54 bool IgnoreBlockInfoNames;
56 BitstreamReader(const BitstreamReader&) LLVM_DELETED_FUNCTION;
57 void operator=(const BitstreamReader&) LLVM_DELETED_FUNCTION;
59 BitstreamReader() : IgnoreBlockInfoNames(true) {
62 BitstreamReader(const unsigned char *Start, const unsigned char *End) {
63 IgnoreBlockInfoNames = true;
67 BitstreamReader(StreamableMemoryObject *bytes) {
68 BitcodeBytes.reset(bytes);
71 void init(const unsigned char *Start, const unsigned char *End) {
72 assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
73 BitcodeBytes.reset(getNonStreamedMemoryObject(Start, End));
76 StreamableMemoryObject &getBitcodeBytes() { return *BitcodeBytes; }
79 // Free the BlockInfoRecords.
80 while (!BlockInfoRecords.empty()) {
81 BlockInfo &Info = BlockInfoRecords.back();
82 // Free blockinfo abbrev info.
83 for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
85 Info.Abbrevs[i]->dropRef();
86 BlockInfoRecords.pop_back();
90 /// CollectBlockInfoNames - This is called by clients that want block/record
92 void CollectBlockInfoNames() { IgnoreBlockInfoNames = false; }
93 bool isIgnoringBlockInfoNames() { return IgnoreBlockInfoNames; }
95 //===--------------------------------------------------------------------===//
97 //===--------------------------------------------------------------------===//
99 /// hasBlockInfoRecords - Return true if we've already read and processed the
100 /// block info block for this Bitstream. We only process it for the first
101 /// cursor that walks over it.
102 bool hasBlockInfoRecords() const { return !BlockInfoRecords.empty(); }
104 /// getBlockInfo - If there is block info for the specified ID, return it,
105 /// otherwise return null.
106 const BlockInfo *getBlockInfo(unsigned BlockID) const {
107 // Common case, the most recent entry matches BlockID.
108 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
109 return &BlockInfoRecords.back();
111 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
113 if (BlockInfoRecords[i].BlockID == BlockID)
114 return &BlockInfoRecords[i];
118 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
119 if (const BlockInfo *BI = getBlockInfo(BlockID))
120 return *const_cast<BlockInfo*>(BI);
122 // Otherwise, add a new record.
123 BlockInfoRecords.push_back(BlockInfo());
124 BlockInfoRecords.back().BlockID = BlockID;
125 return BlockInfoRecords.back();
130 /// BitstreamEntry - When advancing through a bitstream cursor, each advance can
131 /// discover a few different kinds of entries:
132 /// Error - Malformed bitcode was found.
133 /// EndBlock - We've reached the end of the current block, (or the end of the
134 /// file, which is treated like a series of EndBlock records.
135 /// SubBlock - This is the start of a new subblock of a specific ID.
136 /// Record - This is a record with a specific AbbrevID.
138 struct BitstreamEntry {
148 static BitstreamEntry getError() {
149 BitstreamEntry E; E.Kind = Error; return E;
151 static BitstreamEntry getEndBlock() {
152 BitstreamEntry E; E.Kind = EndBlock; return E;
154 static BitstreamEntry getSubBlock(unsigned ID) {
155 BitstreamEntry E; E.Kind = SubBlock; E.ID = ID; return E;
157 static BitstreamEntry getRecord(unsigned AbbrevID) {
158 BitstreamEntry E; E.Kind = Record; E.ID = AbbrevID; return E;
162 /// BitstreamCursor - This represents a position within a bitcode file. There
163 /// may be multiple independent cursors reading within one bitstream, each
164 /// maintaining their own local state.
166 /// Unlike iterators, BitstreamCursors are heavy-weight objects that should not
167 /// be passed by value.
168 class BitstreamCursor {
169 friend class Deserializer;
170 BitstreamReader *BitStream;
173 /// CurWord - This is the current data we have pulled from the stream but have
174 /// not returned to the client.
177 /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
178 /// is always from [0...31] inclusive.
179 unsigned BitsInCurWord;
181 // CurCodeSize - This is the declared size of code values used for the current
183 unsigned CurCodeSize;
185 /// CurAbbrevs - Abbrevs installed at in this block.
186 std::vector<BitCodeAbbrev*> CurAbbrevs;
189 unsigned PrevCodeSize;
190 std::vector<BitCodeAbbrev*> PrevAbbrevs;
191 explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
194 /// BlockScope - This tracks the codesize of parent blocks.
195 SmallVector<Block, 8> BlockScope;
199 BitstreamCursor() : BitStream(0), NextChar(0) {
201 BitstreamCursor(const BitstreamCursor &RHS) : BitStream(0), NextChar(0) {
205 explicit BitstreamCursor(BitstreamReader &R) : BitStream(&R) {
212 void init(BitstreamReader &R) {
226 void operator=(const BitstreamCursor &RHS);
230 bool isEndPos(size_t pos) {
231 return BitStream->getBitcodeBytes().isObjectEnd(static_cast<uint64_t>(pos));
234 bool canSkipToPos(size_t pos) const {
235 // pos can be skipped to if it is a valid address or one byte past the end.
236 return pos == 0 || BitStream->getBitcodeBytes().isValidAddress(
237 static_cast<uint64_t>(pos - 1));
240 unsigned char getByte(size_t pos) {
242 BitStream->getBitcodeBytes().readByte(pos, &byte);
246 uint32_t getWord(size_t pos) {
247 uint8_t buf[4] = { 0xFF, 0xFF, 0xFF, 0xFF };
248 BitStream->getBitcodeBytes().readBytes(pos, sizeof(buf), buf, NULL);
249 return *reinterpret_cast<support::ulittle32_t *>(buf);
252 bool AtEndOfStream() {
253 return isEndPos(NextChar) && BitsInCurWord == 0;
256 /// getAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
257 unsigned getAbbrevIDWidth() const { return CurCodeSize; }
259 /// GetCurrentBitNo - Return the bit # of the bit we are reading.
260 uint64_t GetCurrentBitNo() const {
261 return NextChar*CHAR_BIT - BitsInCurWord;
264 BitstreamReader *getBitStreamReader() {
267 const BitstreamReader *getBitStreamReader() const {
271 /// Flags that modify the behavior of advance().
273 /// AF_DontPopBlockAtEnd - If this flag is used, the advance() method does
274 /// not automatically pop the block scope when the end of a block is
276 AF_DontPopBlockAtEnd = 1,
278 /// AF_DontAutoprocessAbbrevs - If this flag is used, abbrev entries are
279 /// returned just like normal records.
280 AF_DontAutoprocessAbbrevs = 2
283 /// advance - Advance the current bitstream, returning the next entry in the
285 BitstreamEntry advance(unsigned Flags = 0) {
287 unsigned Code = ReadCode();
288 if (Code == bitc::END_BLOCK) {
289 // Pop the end of the block unless Flags tells us not to.
290 if (!(Flags & AF_DontPopBlockAtEnd) && ReadBlockEnd())
291 return BitstreamEntry::getError();
292 return BitstreamEntry::getEndBlock();
295 if (Code == bitc::ENTER_SUBBLOCK)
296 return BitstreamEntry::getSubBlock(ReadSubBlockID());
298 if (Code == bitc::DEFINE_ABBREV &&
299 !(Flags & AF_DontAutoprocessAbbrevs)) {
300 // We read and accumulate abbrev's, the client can't do anything with
306 return BitstreamEntry::getRecord(Code);
310 /// advanceSkippingSubblocks - This is a convenience function for clients that
311 /// don't expect any subblocks. This just skips over them automatically.
312 BitstreamEntry advanceSkippingSubblocks(unsigned Flags = 0) {
314 // If we found a normal entry, return it.
315 BitstreamEntry Entry = advance(Flags);
316 if (Entry.Kind != BitstreamEntry::SubBlock)
319 // If we found a sub-block, just skip over it and check the next entry.
321 return BitstreamEntry::getError();
325 /// JumpToBit - Reset the stream to the specified bit number.
326 void JumpToBit(uint64_t BitNo) {
327 uintptr_t ByteNo = uintptr_t(BitNo/8) & ~3;
328 uintptr_t WordBitNo = uintptr_t(BitNo) & 31;
329 assert(canSkipToPos(ByteNo) && "Invalid location");
331 // Move the cursor to the right word.
336 // Skip over any bits that are already consumed.
338 Read(static_cast<unsigned>(WordBitNo));
342 uint32_t Read(unsigned NumBits) {
343 assert(NumBits <= 32 && "Cannot return more than 32 bits!");
344 // If the field is fully contained by CurWord, return it quickly.
345 if (BitsInCurWord >= NumBits) {
346 uint32_t R = CurWord & ((1U << NumBits)-1);
348 BitsInCurWord -= NumBits;
352 // If we run out of data, stop at the end of the stream.
353 if (isEndPos(NextChar)) {
359 unsigned R = CurWord;
361 // Read the next word from the stream.
362 CurWord = getWord(NextChar);
365 // Extract NumBits-BitsInCurWord from what we just read.
366 unsigned BitsLeft = NumBits-BitsInCurWord;
368 // Be careful here, BitsLeft is in the range [1..32] inclusive.
369 R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
371 // BitsLeft bits have just been used up from CurWord.
373 CurWord >>= BitsLeft;
376 BitsInCurWord = 32-BitsLeft;
380 uint64_t Read64(unsigned NumBits) {
381 if (NumBits <= 32) return Read(NumBits);
383 uint64_t V = Read(32);
384 return V | (uint64_t)Read(NumBits-32) << 32;
387 uint32_t ReadVBR(unsigned NumBits) {
388 uint32_t Piece = Read(NumBits);
389 if ((Piece & (1U << (NumBits-1))) == 0)
393 unsigned NextBit = 0;
395 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
397 if ((Piece & (1U << (NumBits-1))) == 0)
400 NextBit += NumBits-1;
401 Piece = Read(NumBits);
405 // ReadVBR64 - Read a VBR that may have a value up to 64-bits in size. The
406 // chunk size of the VBR must still be <= 32 bits though.
407 uint64_t ReadVBR64(unsigned NumBits) {
408 uint32_t Piece = Read(NumBits);
409 if ((Piece & (1U << (NumBits-1))) == 0)
410 return uint64_t(Piece);
413 unsigned NextBit = 0;
415 Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
417 if ((Piece & (1U << (NumBits-1))) == 0)
420 NextBit += NumBits-1;
421 Piece = Read(NumBits);
430 unsigned ReadCode() {
431 return Read(CurCodeSize);
436 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
438 /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
440 unsigned ReadSubBlockID() {
441 return ReadVBR(bitc::BlockIDWidth);
444 /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
445 /// over the body of this block. If the block record is malformed, return
448 // Read and ignore the codelen value. Since we are skipping this block, we
449 // don't care what code widths are used inside of it.
450 ReadVBR(bitc::CodeLenWidth);
452 unsigned NumWords = Read(bitc::BlockSizeWidth);
454 // Check that the block wasn't partially defined, and that the offset isn't
456 size_t SkipTo = NextChar + NumWords*4;
457 if (AtEndOfStream() || !canSkipToPos(SkipTo))
464 /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, enter
465 /// the block, and return true if the block has an error.
466 bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = 0);
468 bool ReadBlockEnd() {
469 if (BlockScope.empty()) return true;
472 // [END_BLOCK, <align4bytes>]
481 void popBlockScope() {
482 CurCodeSize = BlockScope.back().PrevCodeSize;
484 // Delete abbrevs from popped scope.
485 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
487 CurAbbrevs[i]->dropRef();
489 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
490 BlockScope.pop_back();
493 //===--------------------------------------------------------------------===//
495 //===--------------------------------------------------------------------===//
498 void readAbbreviatedLiteral(const BitCodeAbbrevOp &Op,
499 SmallVectorImpl<uint64_t> &Vals);
500 void readAbbreviatedField(const BitCodeAbbrevOp &Op,
501 SmallVectorImpl<uint64_t> &Vals);
502 void skipAbbreviatedField(const BitCodeAbbrevOp &Op);
506 /// getAbbrev - Return the abbreviation for the specified AbbrevId.
507 const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
508 unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
509 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
510 return CurAbbrevs[AbbrevNo];
513 /// skipRecord - Read the current record and discard it.
514 void skipRecord(unsigned AbbrevID);
516 unsigned readRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
517 StringRef *Blob = 0);
519 unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
520 const char **BlobStart = 0, unsigned *BlobLen = 0) {
522 return readRecord(AbbrevID, Vals);
524 unsigned X = readRecord(AbbrevID, Vals, &S);
525 *BlobStart = S.data();
530 unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
531 const char *&BlobStart, unsigned &BlobLen) {
532 return ReadRecord(AbbrevID, Vals, &BlobStart, &BlobLen);
535 //===--------------------------------------------------------------------===//
537 //===--------------------------------------------------------------------===//
538 void ReadAbbrevRecord();
540 bool ReadBlockInfoBlock();
543 } // End llvm namespace