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"
25 class BitstreamReader {
26 const unsigned char *NextChar;
27 const unsigned char *LastChar;
28 friend class Deserializer;
30 /// CurWord - This is the current data we have pulled from the stream but have
31 /// not returned to the client.
34 /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
35 /// is always from [0...31] inclusive.
36 unsigned BitsInCurWord;
38 // CurCodeSize - This is the declared size of code values used for the current
42 /// CurAbbrevs - Abbrevs installed at in this block.
43 std::vector<BitCodeAbbrev*> CurAbbrevs;
46 unsigned PrevCodeSize;
47 std::vector<BitCodeAbbrev*> PrevAbbrevs;
48 explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
51 /// BlockScope - This tracks the codesize of parent blocks.
52 SmallVector<Block, 8> BlockScope;
54 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
55 /// These describe abbreviations that all blocks of the specified ID inherit.
58 std::vector<BitCodeAbbrev*> Abbrevs;
60 std::vector<BlockInfo> BlockInfoRecords;
62 /// FirstChar - This remembers the first byte of the stream.
63 const unsigned char *FirstChar;
66 NextChar = FirstChar = LastChar = 0;
72 BitstreamReader(const unsigned char *Start, const unsigned char *End) {
76 void init(const unsigned char *Start, const unsigned char *End) {
77 NextChar = FirstChar = Start;
79 assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
86 // Abbrevs could still exist if the stream was broken. If so, don't leak
88 for (unsigned i = 0, e = CurAbbrevs.size(); i != e; ++i)
89 CurAbbrevs[i]->dropRef();
91 for (unsigned S = 0, e = BlockScope.size(); S != e; ++S) {
92 std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
93 for (unsigned i = 0, e = Abbrevs.size(); i != e; ++i)
94 Abbrevs[i]->dropRef();
97 // Free the BlockInfoRecords.
98 while (!BlockInfoRecords.empty()) {
99 BlockInfo &Info = BlockInfoRecords.back();
100 // Free blockinfo abbrev info.
101 for (unsigned i = 0, e = Info.Abbrevs.size(); i != e; ++i)
102 Info.Abbrevs[i]->dropRef();
103 BlockInfoRecords.pop_back();
107 bool AtEndOfStream() const {
108 return NextChar == LastChar && BitsInCurWord == 0;
111 /// GetCurrentBitNo - Return the bit # of the bit we are reading.
112 uint64_t GetCurrentBitNo() const {
113 return (NextChar-FirstChar)*8 + ((32-BitsInCurWord) & 31);
116 /// JumpToBit - Reset the stream to the specified bit number.
117 void JumpToBit(uint64_t BitNo) {
118 uintptr_t ByteNo = uintptr_t(BitNo/8) & ~3;
119 uintptr_t WordBitNo = uintptr_t(BitNo) & 31;
120 assert(ByteNo < (uintptr_t)(LastChar-FirstChar) && "Invalid location");
122 // Move the cursor to the right word.
123 NextChar = FirstChar+ByteNo;
127 // Skip over any bits that are already consumed.
134 /// GetAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
135 unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
137 uint32_t Read(unsigned NumBits) {
138 // If the field is fully contained by CurWord, return it quickly.
139 if (BitsInCurWord >= NumBits) {
140 uint32_t R = CurWord & ((1U << NumBits)-1);
142 BitsInCurWord -= NumBits;
146 // If we run out of data, stop at the end of the stream.
147 if (LastChar == NextChar) {
153 unsigned R = CurWord;
155 // Read the next word from the stream.
156 CurWord = (NextChar[0] << 0) | (NextChar[1] << 8) |
157 (NextChar[2] << 16) | (NextChar[3] << 24);
160 // Extract NumBits-BitsInCurWord from what we just read.
161 unsigned BitsLeft = NumBits-BitsInCurWord;
163 // Be careful here, BitsLeft is in the range [1..32] inclusive.
164 R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
166 // BitsLeft bits have just been used up from CurWord.
168 CurWord >>= BitsLeft;
171 BitsInCurWord = 32-BitsLeft;
175 uint64_t Read64(unsigned NumBits) {
176 if (NumBits <= 32) return Read(NumBits);
178 uint64_t V = Read(32);
179 return V | (uint64_t)Read(NumBits-32) << 32;
182 uint32_t ReadVBR(unsigned NumBits) {
183 uint32_t Piece = Read(NumBits);
184 if ((Piece & (1U << (NumBits-1))) == 0)
188 unsigned NextBit = 0;
190 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
192 if ((Piece & (1U << (NumBits-1))) == 0)
195 NextBit += NumBits-1;
196 Piece = Read(NumBits);
200 uint64_t ReadVBR64(unsigned NumBits) {
201 uint64_t Piece = Read(NumBits);
202 if ((Piece & (1U << (NumBits-1))) == 0)
206 unsigned NextBit = 0;
208 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
210 if ((Piece & (1U << (NumBits-1))) == 0)
213 NextBit += NumBits-1;
214 Piece = Read(NumBits);
224 unsigned ReadCode() {
225 return Read(CurCodeSize);
228 //===--------------------------------------------------------------------===//
229 // Block Manipulation
230 //===--------------------------------------------------------------------===//
233 /// getBlockInfo - If there is block info for the specified ID, return it,
234 /// otherwise return null.
235 BlockInfo *getBlockInfo(unsigned BlockID) {
236 // Common case, the most recent entry matches BlockID.
237 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
238 return &BlockInfoRecords.back();
240 for (unsigned i = 0, e = BlockInfoRecords.size(); i != e; ++i)
241 if (BlockInfoRecords[i].BlockID == BlockID)
242 return &BlockInfoRecords[i];
249 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
251 /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
253 unsigned ReadSubBlockID() {
254 return ReadVBR(bitc::BlockIDWidth);
257 /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
258 /// over the body of this block. If the block record is malformed, return
261 // Read and ignore the codelen value. Since we are skipping this block, we
262 // don't care what code widths are used inside of it.
263 ReadVBR(bitc::CodeLenWidth);
265 unsigned NumWords = Read(bitc::BlockSizeWidth);
267 // Check that the block wasn't partially defined, and that the offset isn't
269 if (AtEndOfStream() || NextChar+NumWords*4 > LastChar)
272 NextChar += NumWords*4;
276 /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, enter
277 /// the block, and return true if the block is valid.
278 bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = 0) {
279 // Save the current block's state on BlockScope.
280 BlockScope.push_back(Block(CurCodeSize));
281 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
283 // Add the abbrevs specific to this block to the CurAbbrevs list.
284 if (BlockInfo *Info = getBlockInfo(BlockID)) {
285 for (unsigned i = 0, e = Info->Abbrevs.size(); i != e; ++i) {
286 CurAbbrevs.push_back(Info->Abbrevs[i]);
287 CurAbbrevs.back()->addRef();
291 // Get the codesize of this block.
292 CurCodeSize = ReadVBR(bitc::CodeLenWidth);
294 unsigned NumWords = Read(bitc::BlockSizeWidth);
295 if (NumWordsP) *NumWordsP = NumWords;
297 // Validate that this block is sane.
298 if (CurCodeSize == 0 || AtEndOfStream() || NextChar+NumWords*4 > LastChar)
304 bool ReadBlockEnd() {
305 if (BlockScope.empty()) return true;
308 // [END_BLOCK, <align4bytes>]
316 void PopBlockScope() {
317 CurCodeSize = BlockScope.back().PrevCodeSize;
319 // Delete abbrevs from popped scope.
320 for (unsigned i = 0, e = CurAbbrevs.size(); i != e; ++i)
321 CurAbbrevs[i]->dropRef();
323 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
324 BlockScope.pop_back();
327 //===--------------------------------------------------------------------===//
329 //===--------------------------------------------------------------------===//
332 void ReadAbbreviatedField(const BitCodeAbbrevOp &Op,
333 SmallVectorImpl<uint64_t> &Vals) {
334 if (Op.isLiteral()) {
335 // If the abbrev specifies the literal value to use, use it.
336 Vals.push_back(Op.getLiteralValue());
338 // Decode the value as we are commanded.
339 switch (Op.getEncoding()) {
340 default: assert(0 && "Unknown encoding!");
341 case BitCodeAbbrevOp::Fixed:
342 Vals.push_back(Read((unsigned)Op.getEncodingData()));
344 case BitCodeAbbrevOp::VBR:
345 Vals.push_back(ReadVBR64((unsigned)Op.getEncodingData()));
347 case BitCodeAbbrevOp::Char6:
348 Vals.push_back(BitCodeAbbrevOp::DecodeChar6(Read(6)));
354 unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals) {
355 if (AbbrevID == bitc::UNABBREV_RECORD) {
356 unsigned Code = ReadVBR(6);
357 unsigned NumElts = ReadVBR(6);
358 for (unsigned i = 0; i != NumElts; ++i)
359 Vals.push_back(ReadVBR64(6));
363 unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
364 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
365 BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
367 for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
368 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
369 if (Op.isLiteral() || Op.getEncoding() != BitCodeAbbrevOp::Array) {
370 ReadAbbreviatedField(Op, Vals);
372 // Array case. Read the number of elements as a vbr6.
373 unsigned NumElts = ReadVBR(6);
375 // Get the element encoding.
376 assert(i+2 == e && "array op not second to last?");
377 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
379 // Read all the elements.
380 for (; NumElts; --NumElts)
381 ReadAbbreviatedField(EltEnc, Vals);
385 unsigned Code = (unsigned)Vals[0];
386 Vals.erase(Vals.begin());
390 //===--------------------------------------------------------------------===//
392 //===--------------------------------------------------------------------===//
394 void ReadAbbrevRecord() {
395 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
396 unsigned NumOpInfo = ReadVBR(5);
397 for (unsigned i = 0; i != NumOpInfo; ++i) {
398 bool IsLiteral = Read(1) ? true : false;
400 Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
404 BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
405 if (BitCodeAbbrevOp::hasEncodingData(E))
406 Abbv->Add(BitCodeAbbrevOp(E, ReadVBR64(5)));
408 Abbv->Add(BitCodeAbbrevOp(E));
410 CurAbbrevs.push_back(Abbv);
413 //===--------------------------------------------------------------------===//
414 // BlockInfo Block Reading
415 //===--------------------------------------------------------------------===//
418 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
419 if (BlockInfo *BI = getBlockInfo(BlockID))
422 // Otherwise, add a new record.
423 BlockInfoRecords.push_back(BlockInfo());
424 BlockInfoRecords.back().BlockID = BlockID;
425 return BlockInfoRecords.back();
430 bool ReadBlockInfoBlock() {
431 if (EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID)) return true;
433 SmallVector<uint64_t, 64> Record;
434 BlockInfo *CurBlockInfo = 0;
436 // Read all the records for this module.
438 unsigned Code = ReadCode();
439 if (Code == bitc::END_BLOCK)
440 return ReadBlockEnd();
441 if (Code == bitc::ENTER_SUBBLOCK) {
443 if (SkipBlock()) return true;
447 // Read abbrev records, associate them with CurBID.
448 if (Code == bitc::DEFINE_ABBREV) {
449 if (!CurBlockInfo) return true;
452 // ReadAbbrevRecord installs the abbrev in CurAbbrevs. Move it to the
453 // appropriate BlockInfo.
454 BitCodeAbbrev *Abbv = CurAbbrevs.back();
455 CurAbbrevs.pop_back();
456 CurBlockInfo->Abbrevs.push_back(Abbv);
462 switch (ReadRecord(Code, Record)) {
463 default: break; // Default behavior, ignore unknown content.
464 case bitc::BLOCKINFO_CODE_SETBID:
465 if (Record.size() < 1) return true;
466 CurBlockInfo = &getOrCreateBlockInfo((unsigned)Record[0]);
473 } // End llvm namespace