we aren't at the end of stream until we've consumed all the bytes AND all
[oota-llvm.git] / include / llvm / Bitcode / BitstreamReader.h
1 //===- BitstreamReader.h - Low-level bitstream reader interface -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License.  See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This header defines the BitstreamReader class.  This class can be used to
11 // read an arbitrary bitstream, regardless of its contents.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef BITSTREAM_READER_H
16 #define BITSTREAM_READER_H
17
18 #include "llvm/Bitcode/BitCodes.h"
19 #include <vector>
20
21 namespace llvm {
22   
23 class BitstreamReader {
24   const unsigned char *NextChar;
25   const unsigned char *LastChar;
26   
27   /// CurWord - This is the current data we have pulled from the stream but have
28   /// not returned to the client.
29   uint32_t CurWord;
30   
31   /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
32   /// is always from [0...31] inclusive.
33   unsigned BitsInCurWord;
34   
35   // CurCodeSize - This is the declared size of code values used for the current
36   // block, in bits.
37   unsigned CurCodeSize;
38
39   /// CurAbbrevs - Abbrevs installed at in this block.
40   std::vector<BitCodeAbbrev*> CurAbbrevs;
41   
42   struct Block {
43     unsigned PrevCodeSize;
44     std::vector<BitCodeAbbrev*> PrevAbbrevs;
45     explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
46   };
47   
48   /// BlockScope - This tracks the codesize of parent blocks.
49   SmallVector<Block, 8> BlockScope;
50
51   /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
52   /// These describe abbreviations that all blocks of the specified ID inherit.
53   struct BlockInfo {
54     unsigned BlockID;
55     std::vector<BitCodeAbbrev*> Abbrevs;
56   };
57   std::vector<BlockInfo> BlockInfoRecords;
58   
59   /// FirstChar - This remembers the first byte of the stream.
60   const unsigned char *FirstChar;
61 public:
62   BitstreamReader() {
63     NextChar = FirstChar = LastChar = 0;
64     CurWord = 0;
65     BitsInCurWord = 0;
66     CurCodeSize = 0;
67   }
68
69   BitstreamReader(const unsigned char *Start, const unsigned char *End) {
70     init(Start, End);
71   }
72   
73   void init(const unsigned char *Start, const unsigned char *End) {
74     NextChar = FirstChar = Start;
75     LastChar = End;
76     assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
77     CurWord = 0;
78     BitsInCurWord = 0;
79     CurCodeSize = 2;
80   }
81   
82   ~BitstreamReader() {
83     // Abbrevs could still exist if the stream was broken.  If so, don't leak
84     // them.
85     for (unsigned i = 0, e = CurAbbrevs.size(); i != e; ++i)
86       CurAbbrevs[i]->dropRef();
87
88     for (unsigned S = 0, e = BlockScope.size(); S != e; ++S) {
89       std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
90       for (unsigned i = 0, e = Abbrevs.size(); i != e; ++i)
91         Abbrevs[i]->dropRef();
92     }
93     
94     // Free the BlockInfoRecords.
95     while (!BlockInfoRecords.empty()) {
96       BlockInfo &Info = BlockInfoRecords.back();
97       // Free blockinfo abbrev info.
98       for (unsigned i = 0, e = Info.Abbrevs.size(); i != e; ++i)
99         Info.Abbrevs[i]->dropRef();
100       BlockInfoRecords.pop_back();
101     }
102   }
103   
104   bool AtEndOfStream() const {
105     return NextChar == LastChar && BitsInCurWord == 0;
106   }
107   
108   /// GetCurrentBitNo - Return the bit # of the bit we are reading.
109   uint64_t GetCurrentBitNo() const {
110     return (NextChar-FirstChar)*8 + ((32-BitsInCurWord) & 31);
111   }
112   
113   /// JumpToBit - Reset the stream to the specified bit number.
114   void JumpToBit(uint64_t BitNo) {
115     uintptr_t ByteNo = uintptr_t(BitNo/8) & ~3;
116     uintptr_t WordBitNo = uintptr_t(BitNo) & 31;
117     assert(ByteNo < (uintptr_t)(LastChar-FirstChar) && "Invalid location");
118     
119     // Move the cursor to the right word.
120     NextChar = FirstChar+ByteNo;
121     BitsInCurWord = 0;
122     
123     // Skip over any bits that are already consumed.
124     if (WordBitNo) {
125       NextChar -= 4;
126       Read(WordBitNo);
127     }
128   }
129   
130   /// GetAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
131   unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
132   
133   uint32_t Read(unsigned NumBits) {
134     // If the field is fully contained by CurWord, return it quickly.
135     if (BitsInCurWord >= NumBits) {
136       uint32_t R = CurWord & ((1U << NumBits)-1);
137       CurWord >>= NumBits;
138       BitsInCurWord -= NumBits;
139       return R;
140     }
141
142     // If we run out of data, stop at the end of the stream.
143     if (LastChar == NextChar) {
144       CurWord = 0;
145       BitsInCurWord = 0;
146       return 0;
147     }
148     
149     unsigned R = CurWord;
150
151     // Read the next word from the stream.
152     CurWord = (NextChar[0] <<  0) | (NextChar[1] << 8) |
153               (NextChar[2] << 16) | (NextChar[3] << 24);
154     NextChar += 4;
155     
156     // Extract NumBits-BitsInCurWord from what we just read.
157     unsigned BitsLeft = NumBits-BitsInCurWord;
158     
159     // Be careful here, BitsLeft is in the range [1..32] inclusive.
160     R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
161     
162     // BitsLeft bits have just been used up from CurWord.
163     if (BitsLeft != 32)
164       CurWord >>= BitsLeft;
165     else
166       CurWord = 0;
167     BitsInCurWord = 32-BitsLeft;
168     return R;
169   }
170   
171   uint64_t Read64(unsigned NumBits) {
172     if (NumBits <= 32) return Read(NumBits);
173     
174     uint64_t V = Read(32);
175     return V | (uint64_t)Read(NumBits-32) << 32;
176   }
177   
178   uint32_t ReadVBR(unsigned NumBits) {
179     uint32_t Piece = Read(NumBits);
180     if ((Piece & (1U << (NumBits-1))) == 0)
181       return Piece;
182
183     uint32_t Result = 0;
184     unsigned NextBit = 0;
185     while (1) {
186       Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
187
188       if ((Piece & (1U << (NumBits-1))) == 0)
189         return Result;
190       
191       NextBit += NumBits-1;
192       Piece = Read(NumBits);
193     }
194   }
195   
196   uint64_t ReadVBR64(unsigned NumBits) {
197     uint64_t Piece = Read(NumBits);
198     if ((Piece & (1U << (NumBits-1))) == 0)
199       return Piece;
200     
201     uint64_t Result = 0;
202     unsigned NextBit = 0;
203     while (1) {
204       Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
205       
206       if ((Piece & (1U << (NumBits-1))) == 0)
207         return Result;
208       
209       NextBit += NumBits-1;
210       Piece = Read(NumBits);
211     }
212   }
213
214   void SkipToWord() {
215     BitsInCurWord = 0;
216     CurWord = 0;
217   }
218
219   
220   unsigned ReadCode() {
221     return Read(CurCodeSize);
222   }
223
224   //===--------------------------------------------------------------------===//
225   // Block Manipulation
226   //===--------------------------------------------------------------------===//
227   
228 private:
229   /// getBlockInfo - If there is block info for the specified ID, return it,
230   /// otherwise return null.
231   BlockInfo *getBlockInfo(unsigned BlockID) {
232     // Common case, the most recent entry matches BlockID.
233     if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
234       return &BlockInfoRecords.back();
235     
236     for (unsigned i = 0, e = BlockInfoRecords.size(); i != e; ++i)
237       if (BlockInfoRecords[i].BlockID == BlockID)
238         return &BlockInfoRecords[i];
239     return 0;
240   }
241 public:
242   
243   
244   // Block header:
245   //    [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
246
247   /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
248   /// the block.
249   unsigned ReadSubBlockID() {
250     return ReadVBR(bitc::BlockIDWidth);
251   }
252   
253   /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
254   /// over the body of this block.  If the block record is malformed, return
255   /// true.
256   bool SkipBlock() {
257     // Read and ignore the codelen value.  Since we are skipping this block, we
258     // don't care what code widths are used inside of it.
259     ReadVBR(bitc::CodeLenWidth);
260     SkipToWord();
261     unsigned NumWords = Read(bitc::BlockSizeWidth);
262     
263     // Check that the block wasn't partially defined, and that the offset isn't
264     // bogus.
265     if (AtEndOfStream() || NextChar+NumWords*4 > LastChar)
266       return true;
267     
268     NextChar += NumWords*4;
269     return false;
270   }
271   
272   /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, read and enter
273   /// the block, returning the BlockID of the block we just entered.
274   bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = 0) {
275     // Save the current block's state on BlockScope.
276     BlockScope.push_back(Block(CurCodeSize));
277     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
278     
279     // Add the abbrevs specific to this block to the CurAbbrevs list.
280     if (BlockInfo *Info = getBlockInfo(BlockID)) {
281       for (unsigned i = 0, e = Info->Abbrevs.size(); i != e; ++i) {
282         CurAbbrevs.push_back(Info->Abbrevs[i]);
283         CurAbbrevs.back()->addRef();
284       }
285     }
286     
287     // Get the codesize of this block.
288     CurCodeSize = ReadVBR(bitc::CodeLenWidth);
289     SkipToWord();
290     unsigned NumWords = Read(bitc::BlockSizeWidth);
291     if (NumWordsP) *NumWordsP = NumWords;
292     
293     // Validate that this block is sane.
294     if (CurCodeSize == 0 || AtEndOfStream() || NextChar+NumWords*4 > LastChar)
295       return true;
296     
297     return false;
298   }
299   
300   bool ReadBlockEnd() {
301     if (BlockScope.empty()) return true;
302     
303     // Block tail:
304     //    [END_BLOCK, <align4bytes>]
305     SkipToWord();
306     CurCodeSize = BlockScope.back().PrevCodeSize;
307     
308     // Delete abbrevs from popped scope.
309     for (unsigned i = 0, e = CurAbbrevs.size(); i != e; ++i)
310       CurAbbrevs[i]->dropRef();
311     
312     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
313     BlockScope.pop_back();
314     return false;
315   }
316   
317   //===--------------------------------------------------------------------===//
318   // Record Processing
319   //===--------------------------------------------------------------------===//
320   
321 private:
322   void ReadAbbreviatedField(const BitCodeAbbrevOp &Op, 
323                             SmallVectorImpl<uint64_t> &Vals) {
324     if (Op.isLiteral()) {
325       // If the abbrev specifies the literal value to use, use it.
326       Vals.push_back(Op.getLiteralValue());
327     } else {
328       // Decode the value as we are commanded.
329       switch (Op.getEncoding()) {
330       default: assert(0 && "Unknown encoding!");
331       case BitCodeAbbrevOp::Fixed:
332         Vals.push_back(Read((unsigned)Op.getEncodingData()));
333         break;
334       case BitCodeAbbrevOp::VBR:
335         Vals.push_back(ReadVBR64((unsigned)Op.getEncodingData()));
336         break;
337       case BitCodeAbbrevOp::Char6:
338         Vals.push_back(BitCodeAbbrevOp::DecodeChar6(Read(6)));
339         break;
340       }
341     }
342   }
343 public:
344   unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals) {
345     if (AbbrevID == bitc::UNABBREV_RECORD) {
346       unsigned Code = ReadVBR(6);
347       unsigned NumElts = ReadVBR(6);
348       for (unsigned i = 0; i != NumElts; ++i)
349         Vals.push_back(ReadVBR64(6));
350       return Code;
351     }
352     
353     unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
354     assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
355     BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
356
357     for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
358       const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
359       if (Op.isLiteral() || Op.getEncoding() != BitCodeAbbrevOp::Array) {
360         ReadAbbreviatedField(Op, Vals);
361       } else {
362         // Array case.  Read the number of elements as a vbr6.
363         unsigned NumElts = ReadVBR(6);
364
365         // Get the element encoding.
366         assert(i+2 == e && "array op not second to last?");
367         const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
368
369         // Read all the elements.
370         for (; NumElts; --NumElts)
371           ReadAbbreviatedField(EltEnc, Vals);
372       }
373     }
374     
375     unsigned Code = (unsigned)Vals[0];
376     Vals.erase(Vals.begin());
377     return Code;
378   }
379   
380   //===--------------------------------------------------------------------===//
381   // Abbrev Processing
382   //===--------------------------------------------------------------------===//
383   
384   void ReadAbbrevRecord() {
385     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
386     unsigned NumOpInfo = ReadVBR(5);
387     for (unsigned i = 0; i != NumOpInfo; ++i) {
388       bool IsLiteral = Read(1);
389       if (IsLiteral) {
390         Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
391         continue;
392       }
393
394       BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
395       if (BitCodeAbbrevOp::hasEncodingData(E))
396         Abbv->Add(BitCodeAbbrevOp(E, ReadVBR64(5)));
397       else
398         Abbv->Add(BitCodeAbbrevOp(E));
399     }
400     CurAbbrevs.push_back(Abbv);
401   }
402   
403   //===--------------------------------------------------------------------===//
404   // BlockInfo Block Reading
405   //===--------------------------------------------------------------------===//
406   
407 private:  
408   BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
409     if (BlockInfo *BI = getBlockInfo(BlockID))
410       return *BI;
411     
412     // Otherwise, add a new record.
413     BlockInfoRecords.push_back(BlockInfo());
414     BlockInfoRecords.back().BlockID = BlockID;
415     return BlockInfoRecords.back();
416   }
417   
418 public:
419     
420   bool ReadBlockInfoBlock() {
421     if (EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID)) return true;
422
423     SmallVector<uint64_t, 64> Record;
424     BlockInfo *CurBlockInfo = 0;
425     
426     // Read all the records for this module.
427     while (1) {
428       unsigned Code = ReadCode();
429       if (Code == bitc::END_BLOCK)
430         return ReadBlockEnd();
431       if (Code == bitc::ENTER_SUBBLOCK) {
432         ReadSubBlockID();
433         if (SkipBlock()) return true;
434         continue;
435       }
436
437       // Read abbrev records, associate them with CurBID.
438       if (Code == bitc::DEFINE_ABBREV) {
439         if (!CurBlockInfo) return true;
440         ReadAbbrevRecord();
441         
442         // ReadAbbrevRecord installs the abbrev in CurAbbrevs.  Move it to the
443         // appropriate BlockInfo.
444         BitCodeAbbrev *Abbv = CurAbbrevs.back();
445         CurAbbrevs.pop_back();
446         CurBlockInfo->Abbrevs.push_back(Abbv);
447         continue;
448       }
449
450       // Read a record.
451       Record.clear();
452       switch (ReadRecord(Code, Record)) {
453       default: break;  // Default behavior, ignore unknown content.
454       case bitc::BLOCKINFO_CODE_SETBID:
455         if (Record.size() < 1) return true;
456         CurBlockInfo = &getOrCreateBlockInfo((unsigned)Record[0]);
457         break;
458       }
459     }      
460   }
461 };
462
463 } // End llvm namespace
464
465 #endif