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/Bitcode/BitCodes.h"
19 #include "llvm/Support/Endian.h"
20 #include "llvm/Support/StreamableMemoryObject.h"
29 /// BitstreamReader - This class is used to read from an LLVM bitcode stream,
30 /// maintaining information that is global to decoding the entire file. While
31 /// a file is being read, multiple cursors can be independently advanced or
32 /// skipped around within the file. These are represented by the
33 /// BitstreamCursor class.
34 class BitstreamReader {
36 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
37 /// These describe abbreviations that all blocks of the specified ID inherit.
40 std::vector<BitCodeAbbrev*> Abbrevs;
43 std::vector<std::pair<unsigned, std::string> > RecordNames;
46 std::unique_ptr<StreamableMemoryObject> BitcodeBytes;
48 std::vector<BlockInfo> BlockInfoRecords;
50 /// IgnoreBlockInfoNames - This is set to true if we don't care about the
51 /// block/record name information in the BlockInfo block. Only llvm-bcanalyzer
53 bool IgnoreBlockInfoNames;
55 BitstreamReader(const BitstreamReader&) LLVM_DELETED_FUNCTION;
56 void operator=(const BitstreamReader&) LLVM_DELETED_FUNCTION;
58 BitstreamReader() : IgnoreBlockInfoNames(true) {
61 BitstreamReader(const unsigned char *Start, const unsigned char *End)
62 : IgnoreBlockInfoNames(true) {
66 BitstreamReader(StreamableMemoryObject *bytes) : IgnoreBlockInfoNames(true) {
67 BitcodeBytes.reset(bytes);
70 BitstreamReader(BitstreamReader &&Other) {
71 *this = std::move(Other);
74 BitstreamReader &operator=(BitstreamReader &&Other) {
75 BitcodeBytes = std::move(Other.BitcodeBytes);
76 // Explicitly swap block info, so that nothing gets destroyed twice.
77 std::swap(BlockInfoRecords, Other.BlockInfoRecords);
78 IgnoreBlockInfoNames = Other.IgnoreBlockInfoNames;
82 void init(const unsigned char *Start, const unsigned char *End) {
83 assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
84 BitcodeBytes.reset(getNonStreamedMemoryObject(Start, End));
87 StreamableMemoryObject &getBitcodeBytes() { return *BitcodeBytes; }
90 // Free the BlockInfoRecords.
91 while (!BlockInfoRecords.empty()) {
92 BlockInfo &Info = BlockInfoRecords.back();
93 // Free blockinfo abbrev info.
94 for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
96 Info.Abbrevs[i]->dropRef();
97 BlockInfoRecords.pop_back();
101 /// CollectBlockInfoNames - This is called by clients that want block/record
102 /// name information.
103 void CollectBlockInfoNames() { IgnoreBlockInfoNames = false; }
104 bool isIgnoringBlockInfoNames() { return IgnoreBlockInfoNames; }
106 //===--------------------------------------------------------------------===//
107 // Block Manipulation
108 //===--------------------------------------------------------------------===//
110 /// hasBlockInfoRecords - Return true if we've already read and processed the
111 /// block info block for this Bitstream. We only process it for the first
112 /// cursor that walks over it.
113 bool hasBlockInfoRecords() const { return !BlockInfoRecords.empty(); }
115 /// getBlockInfo - If there is block info for the specified ID, return it,
116 /// otherwise return null.
117 const BlockInfo *getBlockInfo(unsigned BlockID) const {
118 // Common case, the most recent entry matches BlockID.
119 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
120 return &BlockInfoRecords.back();
122 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
124 if (BlockInfoRecords[i].BlockID == BlockID)
125 return &BlockInfoRecords[i];
129 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
130 if (const BlockInfo *BI = getBlockInfo(BlockID))
131 return *const_cast<BlockInfo*>(BI);
133 // Otherwise, add a new record.
134 BlockInfoRecords.push_back(BlockInfo());
135 BlockInfoRecords.back().BlockID = BlockID;
136 return BlockInfoRecords.back();
139 /// Takes block info from the other bitstream reader.
141 /// This is a "take" operation because BlockInfo records are non-trivial, and
142 /// indeed rather expensive.
143 void takeBlockInfo(BitstreamReader &&Other) {
144 assert(!hasBlockInfoRecords());
145 BlockInfoRecords = std::move(Other.BlockInfoRecords);
150 /// BitstreamEntry - When advancing through a bitstream cursor, each advance can
151 /// discover a few different kinds of entries:
152 /// Error - Malformed bitcode was found.
153 /// EndBlock - We've reached the end of the current block, (or the end of the
154 /// file, which is treated like a series of EndBlock records.
155 /// SubBlock - This is the start of a new subblock of a specific ID.
156 /// Record - This is a record with a specific AbbrevID.
158 struct BitstreamEntry {
168 static BitstreamEntry getError() {
169 BitstreamEntry E; E.Kind = Error; return E;
171 static BitstreamEntry getEndBlock() {
172 BitstreamEntry E; E.Kind = EndBlock; return E;
174 static BitstreamEntry getSubBlock(unsigned ID) {
175 BitstreamEntry E; E.Kind = SubBlock; E.ID = ID; return E;
177 static BitstreamEntry getRecord(unsigned AbbrevID) {
178 BitstreamEntry E; E.Kind = Record; E.ID = AbbrevID; return E;
182 /// BitstreamCursor - This represents a position within a bitcode file. There
183 /// may be multiple independent cursors reading within one bitstream, each
184 /// maintaining their own local state.
186 /// Unlike iterators, BitstreamCursors are heavy-weight objects that should not
187 /// be passed by value.
188 class BitstreamCursor {
189 friend class Deserializer;
190 BitstreamReader *BitStream;
194 /// CurWord/word_t - This is the current data we have pulled from the stream
195 /// but have not returned to the client. This is specifically and
196 /// intentionally defined to follow the word size of the host machine for
197 /// efficiency. We use word_t in places that are aware of this to make it
198 /// perfectly explicit what is going on.
199 typedef uint32_t word_t;
202 /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
203 /// is always from [0...31/63] inclusive (depending on word size).
204 unsigned BitsInCurWord;
206 // CurCodeSize - This is the declared size of code values used for the current
208 unsigned CurCodeSize;
210 /// CurAbbrevs - Abbrevs installed at in this block.
211 std::vector<BitCodeAbbrev*> CurAbbrevs;
214 unsigned PrevCodeSize;
215 std::vector<BitCodeAbbrev*> PrevAbbrevs;
216 explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
219 /// BlockScope - This tracks the codesize of parent blocks.
220 SmallVector<Block, 8> BlockScope;
224 BitstreamCursor() : BitStream(nullptr), NextChar(0) {}
225 BitstreamCursor(const BitstreamCursor &RHS)
226 : BitStream(nullptr), NextChar(0) {
230 explicit BitstreamCursor(BitstreamReader &R) : BitStream(&R) {
237 void init(BitstreamReader &R) {
251 void operator=(const BitstreamCursor &RHS);
255 bool isEndPos(size_t pos) {
256 return BitStream->getBitcodeBytes().isObjectEnd(static_cast<uint64_t>(pos));
259 bool canSkipToPos(size_t pos) const {
260 // pos can be skipped to if it is a valid address or one byte past the end.
261 return pos == 0 || BitStream->getBitcodeBytes().isValidAddress(
262 static_cast<uint64_t>(pos - 1));
265 uint32_t getWord(size_t pos) {
266 uint8_t buf[4] = { 0xFF, 0xFF, 0xFF, 0xFF };
267 BitStream->getBitcodeBytes().readBytes(pos, sizeof(buf), buf);
268 return *reinterpret_cast<support::ulittle32_t *>(buf);
271 bool AtEndOfStream() {
272 return BitsInCurWord == 0 && isEndPos(NextChar);
275 /// getAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
276 unsigned getAbbrevIDWidth() const { return CurCodeSize; }
278 /// GetCurrentBitNo - Return the bit # of the bit we are reading.
279 uint64_t GetCurrentBitNo() const {
280 return NextChar*CHAR_BIT - BitsInCurWord;
283 BitstreamReader *getBitStreamReader() {
286 const BitstreamReader *getBitStreamReader() const {
290 /// Flags that modify the behavior of advance().
292 /// AF_DontPopBlockAtEnd - If this flag is used, the advance() method does
293 /// not automatically pop the block scope when the end of a block is
295 AF_DontPopBlockAtEnd = 1,
297 /// AF_DontAutoprocessAbbrevs - If this flag is used, abbrev entries are
298 /// returned just like normal records.
299 AF_DontAutoprocessAbbrevs = 2
302 /// advance - Advance the current bitstream, returning the next entry in the
304 BitstreamEntry advance(unsigned Flags = 0) {
306 unsigned Code = ReadCode();
307 if (Code == bitc::END_BLOCK) {
308 // Pop the end of the block unless Flags tells us not to.
309 if (!(Flags & AF_DontPopBlockAtEnd) && ReadBlockEnd())
310 return BitstreamEntry::getError();
311 return BitstreamEntry::getEndBlock();
314 if (Code == bitc::ENTER_SUBBLOCK)
315 return BitstreamEntry::getSubBlock(ReadSubBlockID());
317 if (Code == bitc::DEFINE_ABBREV &&
318 !(Flags & AF_DontAutoprocessAbbrevs)) {
319 // We read and accumulate abbrev's, the client can't do anything with
325 return BitstreamEntry::getRecord(Code);
329 /// advanceSkippingSubblocks - This is a convenience function for clients that
330 /// don't expect any subblocks. This just skips over them automatically.
331 BitstreamEntry advanceSkippingSubblocks(unsigned Flags = 0) {
333 // If we found a normal entry, return it.
334 BitstreamEntry Entry = advance(Flags);
335 if (Entry.Kind != BitstreamEntry::SubBlock)
338 // If we found a sub-block, just skip over it and check the next entry.
340 return BitstreamEntry::getError();
344 /// JumpToBit - Reset the stream to the specified bit number.
345 void JumpToBit(uint64_t BitNo) {
346 uintptr_t ByteNo = uintptr_t(BitNo/8) & ~(sizeof(word_t)-1);
347 unsigned WordBitNo = unsigned(BitNo & (sizeof(word_t)*8-1));
348 assert(canSkipToPos(ByteNo) && "Invalid location");
350 // Move the cursor to the right word.
355 // Skip over any bits that are already consumed.
357 if (sizeof(word_t) > 4)
365 uint32_t Read(unsigned NumBits) {
366 assert(NumBits && NumBits <= 32 &&
367 "Cannot return zero or more than 32 bits!");
369 // If the field is fully contained by CurWord, return it quickly.
370 if (BitsInCurWord >= NumBits) {
371 uint32_t R = uint32_t(CurWord) & (~0U >> (32-NumBits));
373 BitsInCurWord -= NumBits;
377 // If we run out of data, stop at the end of the stream.
378 if (isEndPos(NextChar)) {
384 uint32_t R = uint32_t(CurWord);
386 // Read the next word from the stream.
387 uint8_t Array[sizeof(word_t)] = {0};
389 BitStream->getBitcodeBytes().readBytes(NextChar, sizeof(Array), Array);
391 // Handle big-endian byte-swapping if necessary.
392 support::detail::packed_endian_specific_integral
393 <word_t, support::little, support::unaligned> EndianValue;
394 memcpy(&EndianValue, Array, sizeof(Array));
396 CurWord = EndianValue;
398 NextChar += sizeof(word_t);
400 // Extract NumBits-BitsInCurWord from what we just read.
401 unsigned BitsLeft = NumBits-BitsInCurWord;
403 // Be careful here, BitsLeft is in the range [1..32]/[1..64] inclusive.
404 R |= uint32_t((CurWord & (word_t(~0ULL) >> (sizeof(word_t)*8-BitsLeft)))
407 // BitsLeft bits have just been used up from CurWord. BitsLeft is in the
408 // range [1..32]/[1..64] so be careful how we shift.
409 if (BitsLeft != sizeof(word_t)*8)
410 CurWord >>= BitsLeft;
413 BitsInCurWord = sizeof(word_t)*8-BitsLeft;
417 uint64_t Read64(unsigned NumBits) {
418 if (NumBits <= 32) return Read(NumBits);
420 uint64_t V = Read(32);
421 return V | (uint64_t)Read(NumBits-32) << 32;
424 uint32_t ReadVBR(unsigned NumBits) {
425 uint32_t Piece = Read(NumBits);
426 if ((Piece & (1U << (NumBits-1))) == 0)
430 unsigned NextBit = 0;
432 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
434 if ((Piece & (1U << (NumBits-1))) == 0)
437 NextBit += NumBits-1;
438 Piece = Read(NumBits);
442 // ReadVBR64 - Read a VBR that may have a value up to 64-bits in size. The
443 // chunk size of the VBR must still be <= 32 bits though.
444 uint64_t ReadVBR64(unsigned NumBits) {
445 uint32_t Piece = Read(NumBits);
446 if ((Piece & (1U << (NumBits-1))) == 0)
447 return uint64_t(Piece);
450 unsigned NextBit = 0;
452 Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
454 if ((Piece & (1U << (NumBits-1))) == 0)
457 NextBit += NumBits-1;
458 Piece = Read(NumBits);
463 void SkipToFourByteBoundary() {
464 // If word_t is 64-bits and if we've read less than 32 bits, just dump
465 // the bits we have up to the next 32-bit boundary.
466 if (sizeof(word_t) > 4 &&
467 BitsInCurWord >= 32) {
468 CurWord >>= BitsInCurWord-32;
478 unsigned ReadCode() {
479 return Read(CurCodeSize);
484 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
486 /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
488 unsigned ReadSubBlockID() {
489 return ReadVBR(bitc::BlockIDWidth);
492 /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
493 /// over the body of this block. If the block record is malformed, return
496 // Read and ignore the codelen value. Since we are skipping this block, we
497 // don't care what code widths are used inside of it.
498 ReadVBR(bitc::CodeLenWidth);
499 SkipToFourByteBoundary();
500 unsigned NumFourBytes = Read(bitc::BlockSizeWidth);
502 // Check that the block wasn't partially defined, and that the offset isn't
504 size_t SkipTo = GetCurrentBitNo() + NumFourBytes*4*8;
505 if (AtEndOfStream() || !canSkipToPos(SkipTo/8))
512 /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, enter
513 /// the block, and return true if the block has an error.
514 bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = nullptr);
516 bool ReadBlockEnd() {
517 if (BlockScope.empty()) return true;
520 // [END_BLOCK, <align4bytes>]
521 SkipToFourByteBoundary();
529 void popBlockScope() {
530 CurCodeSize = BlockScope.back().PrevCodeSize;
532 // Delete abbrevs from popped scope.
533 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
535 CurAbbrevs[i]->dropRef();
537 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
538 BlockScope.pop_back();
541 //===--------------------------------------------------------------------===//
543 //===--------------------------------------------------------------------===//
546 void readAbbreviatedLiteral(const BitCodeAbbrevOp &Op,
547 SmallVectorImpl<uint64_t> &Vals);
548 void readAbbreviatedField(const BitCodeAbbrevOp &Op,
549 SmallVectorImpl<uint64_t> &Vals);
550 void skipAbbreviatedField(const BitCodeAbbrevOp &Op);
554 /// getAbbrev - Return the abbreviation for the specified AbbrevId.
555 const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
556 unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
557 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
558 return CurAbbrevs[AbbrevNo];
561 /// skipRecord - Read the current record and discard it.
562 void skipRecord(unsigned AbbrevID);
564 unsigned readRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
565 StringRef *Blob = nullptr);
567 //===--------------------------------------------------------------------===//
569 //===--------------------------------------------------------------------===//
570 void ReadAbbrevRecord();
572 bool ReadBlockInfoBlock();
575 } // End llvm namespace