6d7b17400585402c93e2e45663c54500a5c90dba
[oota-llvm.git] / 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
20 namespace llvm {
21   
22 class BitstreamReader {
23   const unsigned char *NextChar;
24   const unsigned char *LastChar;
25   
26   /// CurWord - This is the current data we have pulled from the stream but have
27   /// not returned to the client.
28   uint32_t CurWord;
29   
30   /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
31   /// is always from [0...31] inclusive.
32   unsigned BitsInCurWord;
33   
34   // CurCodeSize - This is the declared size of code values used for the current
35   // block, in bits.
36   unsigned CurCodeSize;
37
38   /// CurAbbrevs - Abbrevs installed at in this block.
39   std::vector<BitCodeAbbrev*> CurAbbrevs;
40   
41   struct Block {
42     unsigned PrevCodeSize;
43     std::vector<BitCodeAbbrev*> PrevAbbrevs;
44     explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
45   };
46   
47   /// BlockScope - This tracks the codesize of parent blocks.
48   SmallVector<Block, 8> BlockScope;
49
50 public:
51   BitstreamReader(const unsigned char *Start, const unsigned char *End)
52     : NextChar(Start), LastChar(End) {
53     assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
54     CurWord = 0;
55     BitsInCurWord = 0;
56     CurCodeSize = 2;
57   }
58   
59   ~BitstreamReader() {
60     // Abbrevs could still exist if the stream was broken.  If so, don't leak
61     // them.
62     for (unsigned i = 0, e = CurAbbrevs.size(); i != e; ++i)
63       delete CurAbbrevs[i];
64
65     for (unsigned S = 0, e = BlockScope.size(); S != e; ++S) {
66       std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
67       for (unsigned i = 0, e = Abbrevs.size(); i != e; ++i)
68         delete Abbrevs[i];
69     }
70   }
71   
72   bool AtEndOfStream() const { return NextChar == LastChar; }
73   
74   uint32_t Read(unsigned NumBits) {
75     // If the field is fully contained by CurWord, return it quickly.
76     if (BitsInCurWord >= NumBits) {
77       uint32_t R = CurWord & ((1U << NumBits)-1);
78       CurWord >>= NumBits;
79       BitsInCurWord -= NumBits;
80       return R;
81     }
82
83     // If we run out of data, stop at the end of the stream.
84     if (LastChar == NextChar) {
85       CurWord = 0;
86       BitsInCurWord = 0;
87       return 0;
88     }
89     
90     unsigned R = CurWord;
91
92     // Read the next word from the stream.
93     CurWord = (NextChar[0] <<  0) | (NextChar[1] << 8) |
94               (NextChar[2] << 16) | (NextChar[3] << 24);
95     NextChar += 4;
96     
97     // Extract NumBits-BitsInCurWord from what we just read.
98     unsigned BitsLeft = NumBits-BitsInCurWord;
99     
100     // Be careful here, BitsLeft is in the range [1..32] inclusive.
101     R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
102     
103     // BitsLeft bits have just been used up from CurWord.
104     if (BitsLeft != 32)
105       CurWord >>= BitsLeft;
106     else
107       CurWord = 0;
108     BitsInCurWord = 32-BitsLeft;
109     return R;
110   }
111   
112   uint64_t Read64(unsigned NumBits) {
113     if (NumBits <= 32) return Read(NumBits);
114     
115     uint64_t V = Read(32);
116     return V | (uint64_t)Read(NumBits-32) << 32;
117   }
118   
119   uint32_t ReadVBR(unsigned NumBits) {
120     uint32_t Piece = Read(NumBits);
121     if ((Piece & (1U << (NumBits-1))) == 0)
122       return Piece;
123
124     uint32_t Result = 0;
125     unsigned NextBit = 0;
126     while (1) {
127       Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
128
129       if ((Piece & (1U << (NumBits-1))) == 0)
130         return Result;
131       
132       NextBit += NumBits-1;
133       Piece = Read(NumBits);
134     }
135   }
136   
137   uint64_t ReadVBR64(unsigned NumBits) {
138     uint64_t Piece = Read(NumBits);
139     if ((Piece & (1U << (NumBits-1))) == 0)
140       return Piece;
141     
142     uint64_t Result = 0;
143     unsigned NextBit = 0;
144     while (1) {
145       Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
146       
147       if ((Piece & (1U << (NumBits-1))) == 0)
148         return Result;
149       
150       NextBit += NumBits-1;
151       Piece = Read(NumBits);
152     }
153   }
154
155   void SkipToWord() {
156     BitsInCurWord = 0;
157     CurWord = 0;
158   }
159
160   
161   unsigned ReadCode() {
162     return Read(CurCodeSize);
163   }
164
165   //===--------------------------------------------------------------------===//
166   // Block Manipulation
167   //===--------------------------------------------------------------------===//
168   
169   // Block header:
170   //    [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
171
172   /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
173   /// the block.
174   unsigned ReadSubBlockID() {
175     return ReadVBR(bitc::BlockIDWidth);
176   }
177   
178   /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
179   /// over the body of this block.  If the block record is malformed, return
180   /// true.
181   bool SkipBlock() {
182     // Read and ignore the codelen value.  Since we are skipping this block, we
183     // don't care what code widths are used inside of it.
184     ReadVBR(bitc::CodeLenWidth);
185     SkipToWord();
186     unsigned NumWords = Read(bitc::BlockSizeWidth);
187     
188     // Check that the block wasn't partially defined, and that the offset isn't
189     // bogus.
190     if (AtEndOfStream() || NextChar+NumWords*4 > LastChar)
191       return true;
192     
193     NextChar += NumWords*4;
194     return false;
195   }
196   
197   /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, read and enter
198   /// the block, returning the BlockID of the block we just entered.
199   bool EnterSubBlock() {
200     BlockScope.push_back(Block(CurCodeSize));
201     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
202     
203     // Get the codesize of this block.
204     CurCodeSize = ReadVBR(bitc::CodeLenWidth);
205     SkipToWord();
206     unsigned NumWords = Read(bitc::BlockSizeWidth);
207     
208     // Validate that this block is sane.
209     if (CurCodeSize == 0 || AtEndOfStream() || NextChar+NumWords*4 > LastChar)
210       return true;
211     
212     return false;
213   }
214   
215   bool ReadBlockEnd() {
216     if (BlockScope.empty()) return true;
217     
218     // Block tail:
219     //    [END_BLOCK, <align4bytes>]
220     SkipToWord();
221     CurCodeSize = BlockScope.back().PrevCodeSize;
222     
223     // Delete abbrevs from popped scope.
224     for (unsigned i = 0, e = CurAbbrevs.size(); i != e; ++i)
225       delete CurAbbrevs[i];
226     
227     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
228     BlockScope.pop_back();
229     return false;
230   }
231   
232   //===--------------------------------------------------------------------===//
233   // Record Processing
234   //===--------------------------------------------------------------------===//
235   
236   unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals) {
237     if (AbbrevID == bitc::UNABBREV_RECORD) {
238       unsigned Code = ReadVBR(6);
239       unsigned NumElts = ReadVBR(6);
240       for (unsigned i = 0; i != NumElts; ++i)
241         Vals.push_back(ReadVBR64(6));
242       return Code;
243     }
244     
245     unsigned AbbrevNo = AbbrevID-bitc::FIRST_ABBREV;
246     assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
247     BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
248
249     for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
250       const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
251       if (Op.isLiteral()) {
252         // If the abbrev specifies the literal value to use, use it.
253         Vals.push_back(Op.getLiteralValue());
254       } else {
255         // Decode the value as we are commanded.
256         switch (Op.getEncoding()) {
257         default: assert(0 && "Unknown encoding!");
258         case BitCodeAbbrevOp::FixedWidth:
259           Vals.push_back(Read(Op.getEncodingData()));
260           break;
261         case BitCodeAbbrevOp::VBR:
262           Vals.push_back(ReadVBR64(Op.getEncodingData()));
263           break;
264         }
265       }
266     }
267     
268     unsigned Code = Vals[0];
269     Vals.erase(Vals.begin());
270     return Code;
271   }
272   
273   //===--------------------------------------------------------------------===//
274   // Abbrev Processing
275   //===--------------------------------------------------------------------===//
276   
277   void ReadAbbrevRecord() {
278     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
279     unsigned NumOpInfo = ReadVBR(5);
280     for (unsigned i = 0; i != NumOpInfo; ++i) {
281       bool IsLiteral = Read(1);
282       if (IsLiteral) {
283         Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
284         continue;
285       }
286
287       BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
288       if (BitCodeAbbrevOp::hasEncodingData(E)) {
289         Abbv->Add(BitCodeAbbrevOp(E, ReadVBR64(5)));
290       } else {
291         assert(0 && "unimp");
292       }
293     }
294     CurAbbrevs.push_back(Abbv);
295   }
296 };
297
298 } // End llvm namespace
299
300 #endif