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 BITSTREAM_READER_H
16 #define BITSTREAM_READER_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 class BitstreamReader {
32 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
33 /// These describe abbreviations that all blocks of the specified ID inherit.
36 std::vector<BitCodeAbbrev*> Abbrevs;
39 std::vector<std::pair<unsigned, std::string> > RecordNames;
42 OwningPtr<StreamableMemoryObject> BitcodeBytes;
44 std::vector<BlockInfo> BlockInfoRecords;
46 /// IgnoreBlockInfoNames - This is set to true if we don't care about the
47 /// block/record name information in the BlockInfo block. Only llvm-bcanalyzer
49 bool IgnoreBlockInfoNames;
51 BitstreamReader(const BitstreamReader&) LLVM_DELETED_FUNCTION;
52 void operator=(const BitstreamReader&) LLVM_DELETED_FUNCTION;
54 BitstreamReader() : IgnoreBlockInfoNames(true) {
57 BitstreamReader(const unsigned char *Start, const unsigned char *End) {
58 IgnoreBlockInfoNames = true;
62 BitstreamReader(StreamableMemoryObject *bytes) {
63 BitcodeBytes.reset(bytes);
66 void init(const unsigned char *Start, const unsigned char *End) {
67 assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
68 BitcodeBytes.reset(getNonStreamedMemoryObject(Start, End));
71 StreamableMemoryObject &getBitcodeBytes() { return *BitcodeBytes; }
74 // Free the BlockInfoRecords.
75 while (!BlockInfoRecords.empty()) {
76 BlockInfo &Info = BlockInfoRecords.back();
77 // Free blockinfo abbrev info.
78 for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
80 Info.Abbrevs[i]->dropRef();
81 BlockInfoRecords.pop_back();
85 /// CollectBlockInfoNames - This is called by clients that want block/record
87 void CollectBlockInfoNames() { IgnoreBlockInfoNames = false; }
88 bool isIgnoringBlockInfoNames() { return IgnoreBlockInfoNames; }
90 //===--------------------------------------------------------------------===//
92 //===--------------------------------------------------------------------===//
94 /// hasBlockInfoRecords - Return true if we've already read and processed the
95 /// block info block for this Bitstream. We only process it for the first
96 /// cursor that walks over it.
97 bool hasBlockInfoRecords() const { return !BlockInfoRecords.empty(); }
99 /// getBlockInfo - If there is block info for the specified ID, return it,
100 /// otherwise return null.
101 const BlockInfo *getBlockInfo(unsigned BlockID) const {
102 // Common case, the most recent entry matches BlockID.
103 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
104 return &BlockInfoRecords.back();
106 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
108 if (BlockInfoRecords[i].BlockID == BlockID)
109 return &BlockInfoRecords[i];
113 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
114 if (const BlockInfo *BI = getBlockInfo(BlockID))
115 return *const_cast<BlockInfo*>(BI);
117 // Otherwise, add a new record.
118 BlockInfoRecords.push_back(BlockInfo());
119 BlockInfoRecords.back().BlockID = BlockID;
120 return BlockInfoRecords.back();
125 class BitstreamCursor {
126 friend class Deserializer;
127 BitstreamReader *BitStream;
130 /// CurWord - This is the current data we have pulled from the stream but have
131 /// not returned to the client.
134 /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
135 /// is always from [0...31] inclusive.
136 unsigned BitsInCurWord;
138 // CurCodeSize - This is the declared size of code values used for the current
140 unsigned CurCodeSize;
142 /// CurAbbrevs - Abbrevs installed at in this block.
143 std::vector<BitCodeAbbrev*> CurAbbrevs;
146 unsigned PrevCodeSize;
147 std::vector<BitCodeAbbrev*> PrevAbbrevs;
148 explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
151 /// BlockScope - This tracks the codesize of parent blocks.
152 SmallVector<Block, 8> BlockScope;
155 BitstreamCursor() : BitStream(0), NextChar(0) {
157 BitstreamCursor(const BitstreamCursor &RHS) : BitStream(0), NextChar(0) {
161 explicit BitstreamCursor(BitstreamReader &R) : BitStream(&R) {
168 void init(BitstreamReader &R) {
182 void operator=(const BitstreamCursor &RHS) {
185 BitStream = RHS.BitStream;
186 NextChar = RHS.NextChar;
187 CurWord = RHS.CurWord;
188 BitsInCurWord = RHS.BitsInCurWord;
189 CurCodeSize = RHS.CurCodeSize;
191 // Copy abbreviations, and bump ref counts.
192 CurAbbrevs = RHS.CurAbbrevs;
193 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
195 CurAbbrevs[i]->addRef();
197 // Copy block scope and bump ref counts.
198 BlockScope = RHS.BlockScope;
199 for (unsigned S = 0, e = static_cast<unsigned>(BlockScope.size());
201 std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
202 for (unsigned i = 0, e = static_cast<unsigned>(Abbrevs.size());
204 Abbrevs[i]->addRef();
209 // Free all the Abbrevs.
210 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
212 CurAbbrevs[i]->dropRef();
215 // Free all the Abbrevs in the block scope.
216 for (unsigned S = 0, e = static_cast<unsigned>(BlockScope.size());
218 std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
219 for (unsigned i = 0, e = static_cast<unsigned>(Abbrevs.size());
221 Abbrevs[i]->dropRef();
226 /// GetAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
227 unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
229 bool isEndPos(size_t pos) {
230 return BitStream->getBitcodeBytes().isObjectEnd(static_cast<uint64_t>(pos));
233 bool canSkipToPos(size_t pos) const {
234 // pos can be skipped to if it is a valid address or one byte past the end.
235 return pos == 0 || BitStream->getBitcodeBytes().isValidAddress(
236 static_cast<uint64_t>(pos - 1));
239 unsigned char getByte(size_t pos) {
241 BitStream->getBitcodeBytes().readByte(pos, &byte);
245 uint32_t getWord(size_t pos) {
246 uint8_t buf[sizeof(uint32_t)];
247 memset(buf, 0xFF, sizeof(buf));
248 BitStream->getBitcodeBytes().readBytes(pos,
252 return *reinterpret_cast<support::ulittle32_t *>(buf);
255 bool AtEndOfStream() {
256 return isEndPos(NextChar) && BitsInCurWord == 0;
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 {
272 /// JumpToBit - Reset the stream to the specified bit number.
273 void JumpToBit(uint64_t BitNo) {
274 uintptr_t ByteNo = uintptr_t(BitNo/8) & ~3;
275 uintptr_t WordBitNo = uintptr_t(BitNo) & 31;
276 assert(canSkipToPos(ByteNo) && "Invalid location");
278 // Move the cursor to the right word.
283 // Skip over any bits that are already consumed.
285 Read(static_cast<unsigned>(WordBitNo));
289 uint32_t Read(unsigned NumBits) {
290 assert(NumBits <= 32 && "Cannot return more than 32 bits!");
291 // If the field is fully contained by CurWord, return it quickly.
292 if (BitsInCurWord >= NumBits) {
293 uint32_t R = CurWord & ((1U << NumBits)-1);
295 BitsInCurWord -= NumBits;
299 // If we run out of data, stop at the end of the stream.
300 if (isEndPos(NextChar)) {
306 unsigned R = CurWord;
308 // Read the next word from the stream.
309 CurWord = getWord(NextChar);
312 // Extract NumBits-BitsInCurWord from what we just read.
313 unsigned BitsLeft = NumBits-BitsInCurWord;
315 // Be careful here, BitsLeft is in the range [1..32] inclusive.
316 R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
318 // BitsLeft bits have just been used up from CurWord.
320 CurWord >>= BitsLeft;
323 BitsInCurWord = 32-BitsLeft;
327 uint64_t Read64(unsigned NumBits) {
328 if (NumBits <= 32) return Read(NumBits);
330 uint64_t V = Read(32);
331 return V | (uint64_t)Read(NumBits-32) << 32;
334 uint32_t ReadVBR(unsigned NumBits) {
335 uint32_t Piece = Read(NumBits);
336 if ((Piece & (1U << (NumBits-1))) == 0)
340 unsigned NextBit = 0;
342 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
344 if ((Piece & (1U << (NumBits-1))) == 0)
347 NextBit += NumBits-1;
348 Piece = Read(NumBits);
352 // ReadVBR64 - Read a VBR that may have a value up to 64-bits in size. The
353 // chunk size of the VBR must still be <= 32 bits though.
354 uint64_t ReadVBR64(unsigned NumBits) {
355 uint32_t Piece = Read(NumBits);
356 if ((Piece & (1U << (NumBits-1))) == 0)
357 return uint64_t(Piece);
360 unsigned NextBit = 0;
362 Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
364 if ((Piece & (1U << (NumBits-1))) == 0)
367 NextBit += NumBits-1;
368 Piece = Read(NumBits);
377 unsigned ReadCode() {
378 return Read(CurCodeSize);
383 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
385 /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
387 unsigned ReadSubBlockID() {
388 return ReadVBR(bitc::BlockIDWidth);
391 /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
392 /// over the body of this block. If the block record is malformed, return
395 // Read and ignore the codelen value. Since we are skipping this block, we
396 // don't care what code widths are used inside of it.
397 ReadVBR(bitc::CodeLenWidth);
399 unsigned NumWords = Read(bitc::BlockSizeWidth);
401 // Check that the block wasn't partially defined, and that the offset isn't
403 size_t SkipTo = NextChar + NumWords*4;
404 if (AtEndOfStream() || !canSkipToPos(SkipTo))
411 /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, enter
412 /// the block, and return true if the block has an error.
413 bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = 0) {
414 // Save the current block's state on BlockScope.
415 BlockScope.push_back(Block(CurCodeSize));
416 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
418 // Add the abbrevs specific to this block to the CurAbbrevs list.
419 if (const BitstreamReader::BlockInfo *Info =
420 BitStream->getBlockInfo(BlockID)) {
421 for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
423 CurAbbrevs.push_back(Info->Abbrevs[i]);
424 CurAbbrevs.back()->addRef();
428 // Get the codesize of this block.
429 CurCodeSize = ReadVBR(bitc::CodeLenWidth);
431 unsigned NumWords = Read(bitc::BlockSizeWidth);
432 if (NumWordsP) *NumWordsP = NumWords;
434 // Validate that this block is sane.
435 if (CurCodeSize == 0 || AtEndOfStream())
441 bool ReadBlockEnd() {
442 if (BlockScope.empty()) return true;
445 // [END_BLOCK, <align4bytes>]
453 void PopBlockScope() {
454 CurCodeSize = BlockScope.back().PrevCodeSize;
456 // Delete abbrevs from popped scope.
457 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
459 CurAbbrevs[i]->dropRef();
461 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
462 BlockScope.pop_back();
465 //===--------------------------------------------------------------------===//
467 //===--------------------------------------------------------------------===//
470 void ReadAbbreviatedLiteral(const BitCodeAbbrevOp &Op,
471 SmallVectorImpl<uint64_t> &Vals) {
472 assert(Op.isLiteral() && "Not a literal");
473 // If the abbrev specifies the literal value to use, use it.
474 Vals.push_back(Op.getLiteralValue());
477 void ReadAbbreviatedField(const BitCodeAbbrevOp &Op,
478 SmallVectorImpl<uint64_t> &Vals) {
479 assert(!Op.isLiteral() && "Use ReadAbbreviatedLiteral for literals!");
481 // Decode the value as we are commanded.
482 switch (Op.getEncoding()) {
483 default: llvm_unreachable("Unknown encoding!");
484 case BitCodeAbbrevOp::Fixed:
485 Vals.push_back(Read((unsigned)Op.getEncodingData()));
487 case BitCodeAbbrevOp::VBR:
488 Vals.push_back(ReadVBR64((unsigned)Op.getEncodingData()));
490 case BitCodeAbbrevOp::Char6:
491 Vals.push_back(BitCodeAbbrevOp::DecodeChar6(Read(6)));
497 /// getAbbrev - Return the abbreviation for the specified AbbrevId.
498 const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
499 unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
500 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
501 return CurAbbrevs[AbbrevNo];
504 unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
505 const char **BlobStart = 0, unsigned *BlobLen = 0) {
506 if (AbbrevID == bitc::UNABBREV_RECORD) {
507 unsigned Code = ReadVBR(6);
508 unsigned NumElts = ReadVBR(6);
509 for (unsigned i = 0; i != NumElts; ++i)
510 Vals.push_back(ReadVBR64(6));
514 const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
516 for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
517 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
518 if (Op.isLiteral()) {
519 ReadAbbreviatedLiteral(Op, Vals);
520 } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
521 // Array case. Read the number of elements as a vbr6.
522 unsigned NumElts = ReadVBR(6);
524 // Get the element encoding.
525 assert(i+2 == e && "array op not second to last?");
526 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
528 // Read all the elements.
529 for (; NumElts; --NumElts)
530 ReadAbbreviatedField(EltEnc, Vals);
531 } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
532 // Blob case. Read the number of bytes as a vbr6.
533 unsigned NumElts = ReadVBR(6);
534 SkipToWord(); // 32-bit alignment
536 // Figure out where the end of this blob will be including tail padding.
537 size_t NewEnd = NextChar+((NumElts+3)&~3);
539 // If this would read off the end of the bitcode file, just set the
540 // record to empty and return.
541 if (!canSkipToPos(NewEnd)) {
542 Vals.append(NumElts, 0);
543 NextChar = BitStream->getBitcodeBytes().getExtent();
547 // Otherwise, read the number of bytes. If we can return a reference to
548 // the data, do so to avoid copying it.
550 *BlobStart = (const char*)BitStream->getBitcodeBytes().getPointer(
554 for (; NumElts; ++NextChar, --NumElts)
555 Vals.push_back(getByte(NextChar));
557 // Skip over tail padding.
560 ReadAbbreviatedField(Op, Vals);
564 unsigned Code = (unsigned)Vals[0];
565 Vals.erase(Vals.begin());
569 unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
570 const char *&BlobStart, unsigned &BlobLen) {
571 return ReadRecord(AbbrevID, Vals, &BlobStart, &BlobLen);
575 //===--------------------------------------------------------------------===//
577 //===--------------------------------------------------------------------===//
579 void ReadAbbrevRecord() {
580 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
581 unsigned NumOpInfo = ReadVBR(5);
582 for (unsigned i = 0; i != NumOpInfo; ++i) {
583 bool IsLiteral = Read(1) ? true : false;
585 Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
589 BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
590 if (BitCodeAbbrevOp::hasEncodingData(E))
591 Abbv->Add(BitCodeAbbrevOp(E, ReadVBR64(5)));
593 Abbv->Add(BitCodeAbbrevOp(E));
595 CurAbbrevs.push_back(Abbv);
600 bool ReadBlockInfoBlock() {
601 // If this is the second stream to get to the block info block, skip it.
602 if (BitStream->hasBlockInfoRecords())
605 if (EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID)) return true;
607 SmallVector<uint64_t, 64> Record;
608 BitstreamReader::BlockInfo *CurBlockInfo = 0;
610 // Read all the records for this module.
612 unsigned Code = ReadCode();
613 if (Code == bitc::END_BLOCK)
614 return ReadBlockEnd();
615 if (Code == bitc::ENTER_SUBBLOCK) {
617 if (SkipBlock()) return true;
621 // Read abbrev records, associate them with CurBID.
622 if (Code == bitc::DEFINE_ABBREV) {
623 if (!CurBlockInfo) return true;
626 // ReadAbbrevRecord installs the abbrev in CurAbbrevs. Move it to the
627 // appropriate BlockInfo.
628 BitCodeAbbrev *Abbv = CurAbbrevs.back();
629 CurAbbrevs.pop_back();
630 CurBlockInfo->Abbrevs.push_back(Abbv);
636 switch (ReadRecord(Code, Record)) {
637 default: break; // Default behavior, ignore unknown content.
638 case bitc::BLOCKINFO_CODE_SETBID:
639 if (Record.size() < 1) return true;
640 CurBlockInfo = &BitStream->getOrCreateBlockInfo((unsigned)Record[0]);
642 case bitc::BLOCKINFO_CODE_BLOCKNAME: {
643 if (!CurBlockInfo) return true;
644 if (BitStream->isIgnoringBlockInfoNames()) break; // Ignore name.
646 for (unsigned i = 0, e = Record.size(); i != e; ++i)
647 Name += (char)Record[i];
648 CurBlockInfo->Name = Name;
651 case bitc::BLOCKINFO_CODE_SETRECORDNAME: {
652 if (!CurBlockInfo) return true;
653 if (BitStream->isIgnoringBlockInfoNames()) break; // Ignore name.
655 for (unsigned i = 1, e = Record.size(); i != e; ++i)
656 Name += (char)Record[i];
657 CurBlockInfo->RecordNames.push_back(std::make_pair((unsigned)Record[0],
666 } // End llvm namespace