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/Bitcode/BitCodes.h"
26 class BitstreamReader {
27 const unsigned char *NextChar;
28 const unsigned char *LastChar;
29 friend class Deserializer;
31 /// CurWord - This is the current data we have pulled from the stream but have
32 /// not returned to the client.
35 /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
36 /// is always from [0...31] inclusive.
37 unsigned BitsInCurWord;
39 // CurCodeSize - This is the declared size of code values used for the current
43 /// CurAbbrevs - Abbrevs installed at in this block.
44 std::vector<BitCodeAbbrev*> CurAbbrevs;
47 unsigned PrevCodeSize;
48 std::vector<BitCodeAbbrev*> PrevAbbrevs;
49 explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
52 /// BlockScope - This tracks the codesize of parent blocks.
53 SmallVector<Block, 8> BlockScope;
55 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
56 /// These describe abbreviations that all blocks of the specified ID inherit.
59 std::vector<BitCodeAbbrev*> Abbrevs;
61 std::vector<BlockInfo> BlockInfoRecords;
63 /// FirstChar - This remembers the first byte of the stream.
64 const unsigned char *FirstChar;
67 NextChar = FirstChar = LastChar = 0;
73 BitstreamReader(const unsigned char *Start, const unsigned char *End) {
77 void init(const unsigned char *Start, const unsigned char *End) {
78 NextChar = FirstChar = Start;
80 assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
87 // Abbrevs could still exist if the stream was broken. If so, don't leak
89 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
91 CurAbbrevs[i]->dropRef();
93 for (unsigned S = 0, e = static_cast<unsigned>(BlockScope.size());
95 std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
96 for (unsigned i = 0, e = static_cast<unsigned>(Abbrevs.size());
98 Abbrevs[i]->dropRef();
101 // Free the BlockInfoRecords.
102 while (!BlockInfoRecords.empty()) {
103 BlockInfo &Info = BlockInfoRecords.back();
104 // Free blockinfo abbrev info.
105 for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
107 Info.Abbrevs[i]->dropRef();
108 BlockInfoRecords.pop_back();
112 bool AtEndOfStream() const {
113 return NextChar == LastChar && BitsInCurWord == 0;
116 /// GetCurrentBitNo - Return the bit # of the bit we are reading.
117 uint64_t GetCurrentBitNo() const {
118 return (NextChar-FirstChar)*CHAR_BIT + ((32-BitsInCurWord) & 31);
121 /// JumpToBit - Reset the stream to the specified bit number.
122 void JumpToBit(uint64_t BitNo) {
123 uintptr_t ByteNo = uintptr_t(BitNo/8) & ~3;
124 uintptr_t WordBitNo = uintptr_t(BitNo) & 31;
125 assert(ByteNo < (uintptr_t)(LastChar-FirstChar) && "Invalid location");
127 // Move the cursor to the right word.
128 NextChar = FirstChar+ByteNo;
132 // Skip over any bits that are already consumed.
135 Read(static_cast<unsigned>(WordBitNo));
139 /// GetAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
140 unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
142 uint32_t Read(unsigned NumBits) {
143 // If the field is fully contained by CurWord, return it quickly.
144 if (BitsInCurWord >= NumBits) {
145 uint32_t R = CurWord & ((1U << NumBits)-1);
147 BitsInCurWord -= NumBits;
151 // If we run out of data, stop at the end of the stream.
152 if (NextChar == LastChar) {
158 unsigned R = CurWord;
160 // Read the next word from the stream.
161 CurWord = (NextChar[0] << 0) | (NextChar[1] << 8) |
162 (NextChar[2] << 16) | (NextChar[3] << 24);
165 // Extract NumBits-BitsInCurWord from what we just read.
166 unsigned BitsLeft = NumBits-BitsInCurWord;
168 // Be careful here, BitsLeft is in the range [1..32] inclusive.
169 R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
171 // BitsLeft bits have just been used up from CurWord.
173 CurWord >>= BitsLeft;
176 BitsInCurWord = 32-BitsLeft;
180 uint64_t Read64(unsigned NumBits) {
181 if (NumBits <= 32) return Read(NumBits);
183 uint64_t V = Read(32);
184 return V | (uint64_t)Read(NumBits-32) << 32;
187 uint32_t ReadVBR(unsigned NumBits) {
188 uint32_t Piece = Read(NumBits);
189 if ((Piece & (1U << (NumBits-1))) == 0)
193 unsigned NextBit = 0;
195 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
197 if ((Piece & (1U << (NumBits-1))) == 0)
200 NextBit += NumBits-1;
201 Piece = Read(NumBits);
205 uint64_t ReadVBR64(unsigned NumBits) {
206 uint64_t Piece = Read(NumBits);
207 if ((Piece & (1U << (NumBits-1))) == 0)
211 unsigned NextBit = 0;
213 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
215 if ((Piece & (1U << (NumBits-1))) == 0)
218 NextBit += NumBits-1;
219 Piece = Read(NumBits);
229 unsigned ReadCode() {
230 return Read(CurCodeSize);
233 //===--------------------------------------------------------------------===//
234 // Block Manipulation
235 //===--------------------------------------------------------------------===//
238 /// getBlockInfo - If there is block info for the specified ID, return it,
239 /// otherwise return null.
240 BlockInfo *getBlockInfo(unsigned BlockID) {
241 // Common case, the most recent entry matches BlockID.
242 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
243 return &BlockInfoRecords.back();
245 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
247 if (BlockInfoRecords[i].BlockID == BlockID)
248 return &BlockInfoRecords[i];
255 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
257 /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
259 unsigned ReadSubBlockID() {
260 return ReadVBR(bitc::BlockIDWidth);
263 /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
264 /// over the body of this block. If the block record is malformed, return
267 // Read and ignore the codelen value. Since we are skipping this block, we
268 // don't care what code widths are used inside of it.
269 ReadVBR(bitc::CodeLenWidth);
271 unsigned NumWords = Read(bitc::BlockSizeWidth);
273 // Check that the block wasn't partially defined, and that the offset isn't
275 if (AtEndOfStream() || NextChar+NumWords*4 > LastChar)
278 NextChar += NumWords*4;
282 /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, enter
283 /// the block, and return true if the block is valid.
284 bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = 0) {
285 // Save the current block's state on BlockScope.
286 BlockScope.push_back(Block(CurCodeSize));
287 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
289 // Add the abbrevs specific to this block to the CurAbbrevs list.
290 if (BlockInfo *Info = getBlockInfo(BlockID)) {
291 for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
293 CurAbbrevs.push_back(Info->Abbrevs[i]);
294 CurAbbrevs.back()->addRef();
298 // Get the codesize of this block.
299 CurCodeSize = ReadVBR(bitc::CodeLenWidth);
301 unsigned NumWords = Read(bitc::BlockSizeWidth);
302 if (NumWordsP) *NumWordsP = NumWords;
304 // Validate that this block is sane.
305 if (CurCodeSize == 0 || AtEndOfStream() || NextChar+NumWords*4 > LastChar)
311 bool ReadBlockEnd() {
312 if (BlockScope.empty()) return true;
315 // [END_BLOCK, <align4bytes>]
323 void PopBlockScope() {
324 CurCodeSize = BlockScope.back().PrevCodeSize;
326 // Delete abbrevs from popped scope.
327 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
329 CurAbbrevs[i]->dropRef();
331 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
332 BlockScope.pop_back();
335 //===--------------------------------------------------------------------===//
337 //===--------------------------------------------------------------------===//
340 void ReadAbbreviatedLiteral(const BitCodeAbbrevOp &Op,
341 SmallVectorImpl<uint64_t> &Vals) {
342 assert(Op.isLiteral() && "Not a literal");
343 // If the abbrev specifies the literal value to use, use it.
344 Vals.push_back(Op.getLiteralValue());
347 void ReadAbbreviatedField(const BitCodeAbbrevOp &Op,
348 SmallVectorImpl<uint64_t> &Vals) {
349 assert(!Op.isLiteral() && "Use ReadAbbreviatedLiteral for literals!");
351 // Decode the value as we are commanded.
352 switch (Op.getEncoding()) {
353 default: assert(0 && "Unknown encoding!");
354 case BitCodeAbbrevOp::Fixed:
355 Vals.push_back(Read((unsigned)Op.getEncodingData()));
357 case BitCodeAbbrevOp::VBR:
358 Vals.push_back(ReadVBR64((unsigned)Op.getEncodingData()));
360 case BitCodeAbbrevOp::Char6:
361 Vals.push_back(BitCodeAbbrevOp::DecodeChar6(Read(6)));
367 /// getAbbrev - Return the abbreviation for the specified AbbrevId.
368 const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
369 unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
370 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
371 return CurAbbrevs[AbbrevNo];
374 unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals) {
375 if (AbbrevID == bitc::UNABBREV_RECORD) {
376 unsigned Code = ReadVBR(6);
377 unsigned NumElts = ReadVBR(6);
378 for (unsigned i = 0; i != NumElts; ++i)
379 Vals.push_back(ReadVBR64(6));
383 const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
385 for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
386 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
387 if (Op.isLiteral()) {
388 ReadAbbreviatedLiteral(Op, Vals);
389 } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
390 // Array case. Read the number of elements as a vbr6.
391 unsigned NumElts = ReadVBR(6);
393 // Get the element encoding.
394 assert(i+2 == e && "array op not second to last?");
395 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
397 // Read all the elements.
398 for (; NumElts; --NumElts)
399 ReadAbbreviatedField(EltEnc, Vals);
400 } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
401 // Blob case. Read the number of bytes as a vbr6.
402 unsigned NumElts = ReadVBR(6);
403 SkipToWord(); // 32-bit alignment
405 // Figure out where the end of this blob will be including tail padding.
406 const unsigned char *NewEnd = NextChar+((NumElts+3)&~3);
408 // If this would read off the end of the bitcode file, just set the
409 // record to empty and return.
410 if (NewEnd > LastChar) {
411 Vals.append(NumElts, 0);
416 // Otherwise, read the number of bytes.
417 for (; NumElts; ++NextChar, --NumElts)
418 Vals.push_back(*NextChar);
419 // Skip over tail padding.
422 ReadAbbreviatedField(Op, Vals);
426 unsigned Code = (unsigned)Vals[0];
427 Vals.erase(Vals.begin());
431 //===--------------------------------------------------------------------===//
433 //===--------------------------------------------------------------------===//
435 void ReadAbbrevRecord() {
436 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
437 unsigned NumOpInfo = ReadVBR(5);
438 for (unsigned i = 0; i != NumOpInfo; ++i) {
439 bool IsLiteral = Read(1) ? true : false;
441 Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
445 BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
446 if (BitCodeAbbrevOp::hasEncodingData(E))
447 Abbv->Add(BitCodeAbbrevOp(E, ReadVBR64(5)));
449 Abbv->Add(BitCodeAbbrevOp(E));
451 CurAbbrevs.push_back(Abbv);
454 //===--------------------------------------------------------------------===//
455 // BlockInfo Block Reading
456 //===--------------------------------------------------------------------===//
459 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
460 if (BlockInfo *BI = getBlockInfo(BlockID))
463 // Otherwise, add a new record.
464 BlockInfoRecords.push_back(BlockInfo());
465 BlockInfoRecords.back().BlockID = BlockID;
466 return BlockInfoRecords.back();
471 bool ReadBlockInfoBlock() {
472 if (EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID)) return true;
474 SmallVector<uint64_t, 64> Record;
475 BlockInfo *CurBlockInfo = 0;
477 // Read all the records for this module.
479 unsigned Code = ReadCode();
480 if (Code == bitc::END_BLOCK)
481 return ReadBlockEnd();
482 if (Code == bitc::ENTER_SUBBLOCK) {
484 if (SkipBlock()) return true;
488 // Read abbrev records, associate them with CurBID.
489 if (Code == bitc::DEFINE_ABBREV) {
490 if (!CurBlockInfo) return true;
493 // ReadAbbrevRecord installs the abbrev in CurAbbrevs. Move it to the
494 // appropriate BlockInfo.
495 BitCodeAbbrev *Abbv = CurAbbrevs.back();
496 CurAbbrevs.pop_back();
497 CurBlockInfo->Abbrevs.push_back(Abbv);
503 switch (ReadRecord(Code, Record)) {
504 default: break; // Default behavior, ignore unknown content.
505 case bitc::BLOCKINFO_CODE_SETBID:
506 if (Record.size() < 1) return true;
507 CurBlockInfo = &getOrCreateBlockInfo((unsigned)Record[0]);
514 } // End llvm namespace