OSDN Git Service

Don't attribute in file headers anymore. See llvmdev for the
[android-x86/external-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 is distributed under the University of Illinois Open Source
6 // 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 Deserializer;
24   
25 class BitstreamReader {
26   const unsigned char *NextChar;
27   const unsigned char *LastChar;
28   friend class Deserializer;
29   
30   /// CurWord - This is the current data we have pulled from the stream but have
31   /// not returned to the client.
32   uint32_t CurWord;
33   
34   /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
35   /// is always from [0...31] inclusive.
36   unsigned BitsInCurWord;
37   
38   // CurCodeSize - This is the declared size of code values used for the current
39   // block, in bits.
40   unsigned CurCodeSize;
41
42   /// CurAbbrevs - Abbrevs installed at in this block.
43   std::vector<BitCodeAbbrev*> CurAbbrevs;
44   
45   struct Block {
46     unsigned PrevCodeSize;
47     std::vector<BitCodeAbbrev*> PrevAbbrevs;
48     explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
49   };
50   
51   /// BlockScope - This tracks the codesize of parent blocks.
52   SmallVector<Block, 8> BlockScope;
53
54   /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
55   /// These describe abbreviations that all blocks of the specified ID inherit.
56   struct BlockInfo {
57     unsigned BlockID;
58     std::vector<BitCodeAbbrev*> Abbrevs;
59   };
60   std::vector<BlockInfo> BlockInfoRecords;
61   
62   /// FirstChar - This remembers the first byte of the stream.
63   const unsigned char *FirstChar;
64 public:
65   BitstreamReader() {
66     NextChar = FirstChar = LastChar = 0;
67     CurWord = 0;
68     BitsInCurWord = 0;
69     CurCodeSize = 0;
70   }
71
72   BitstreamReader(const unsigned char *Start, const unsigned char *End) {
73     init(Start, End);
74   }
75   
76   void init(const unsigned char *Start, const unsigned char *End) {
77     NextChar = FirstChar = Start;
78     LastChar = End;
79     assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
80     CurWord = 0;
81     BitsInCurWord = 0;
82     CurCodeSize = 2;
83   }
84   
85   ~BitstreamReader() {
86     // Abbrevs could still exist if the stream was broken.  If so, don't leak
87     // them.
88     for (unsigned i = 0, e = CurAbbrevs.size(); i != e; ++i)
89       CurAbbrevs[i]->dropRef();
90
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();
95     }
96     
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();
104     }
105   }
106   
107   bool AtEndOfStream() const {
108     return NextChar == LastChar && BitsInCurWord == 0;
109   }
110   
111   /// GetCurrentBitNo - Return the bit # of the bit we are reading.
112   uint64_t GetCurrentBitNo() const {
113     return (NextChar-FirstChar)*8 + ((32-BitsInCurWord) & 31);
114   }
115   
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");
121     
122     // Move the cursor to the right word.
123     NextChar = FirstChar+ByteNo;
124     BitsInCurWord = 0;
125     CurWord = 0;
126     
127     // Skip over any bits that are already consumed.
128     if (WordBitNo) {
129       NextChar -= 4;
130       Read(WordBitNo);
131     }
132   }
133   
134   /// GetAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
135   unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
136   
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);
141       CurWord >>= NumBits;
142       BitsInCurWord -= NumBits;
143       return R;
144     }
145
146     // If we run out of data, stop at the end of the stream.
147     if (LastChar == NextChar) {
148       CurWord = 0;
149       BitsInCurWord = 0;
150       return 0;
151     }
152     
153     unsigned R = CurWord;
154
155     // Read the next word from the stream.
156     CurWord = (NextChar[0] <<  0) | (NextChar[1] << 8) |
157               (NextChar[2] << 16) | (NextChar[3] << 24);
158     NextChar += 4;
159     
160     // Extract NumBits-BitsInCurWord from what we just read.
161     unsigned BitsLeft = NumBits-BitsInCurWord;
162     
163     // Be careful here, BitsLeft is in the range [1..32] inclusive.
164     R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
165     
166     // BitsLeft bits have just been used up from CurWord.
167     if (BitsLeft != 32)
168       CurWord >>= BitsLeft;
169     else
170       CurWord = 0;
171     BitsInCurWord = 32-BitsLeft;
172     return R;
173   }
174   
175   uint64_t Read64(unsigned NumBits) {
176     if (NumBits <= 32) return Read(NumBits);
177     
178     uint64_t V = Read(32);
179     return V | (uint64_t)Read(NumBits-32) << 32;
180   }
181   
182   uint32_t ReadVBR(unsigned NumBits) {
183     uint32_t Piece = Read(NumBits);
184     if ((Piece & (1U << (NumBits-1))) == 0)
185       return Piece;
186
187     uint32_t Result = 0;
188     unsigned NextBit = 0;
189     while (1) {
190       Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
191
192       if ((Piece & (1U << (NumBits-1))) == 0)
193         return Result;
194       
195       NextBit += NumBits-1;
196       Piece = Read(NumBits);
197     }
198   }
199   
200   uint64_t ReadVBR64(unsigned NumBits) {
201     uint64_t Piece = Read(NumBits);
202     if ((Piece & (1U << (NumBits-1))) == 0)
203       return Piece;
204     
205     uint64_t Result = 0;
206     unsigned NextBit = 0;
207     while (1) {
208       Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
209       
210       if ((Piece & (1U << (NumBits-1))) == 0)
211         return Result;
212       
213       NextBit += NumBits-1;
214       Piece = Read(NumBits);
215     }
216   }
217
218   void SkipToWord() {
219     BitsInCurWord = 0;
220     CurWord = 0;
221   }
222
223   
224   unsigned ReadCode() {
225     return Read(CurCodeSize);
226   }
227
228   //===--------------------------------------------------------------------===//
229   // Block Manipulation
230   //===--------------------------------------------------------------------===//
231   
232 private:
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();
239     
240     for (unsigned i = 0, e = BlockInfoRecords.size(); i != e; ++i)
241       if (BlockInfoRecords[i].BlockID == BlockID)
242         return &BlockInfoRecords[i];
243     return 0;
244   }
245 public:
246   
247   
248   // Block header:
249   //    [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
250
251   /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
252   /// the block.
253   unsigned ReadSubBlockID() {
254     return ReadVBR(bitc::BlockIDWidth);
255   }
256   
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
259   /// true.
260   bool SkipBlock() {
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);
264     SkipToWord();
265     unsigned NumWords = Read(bitc::BlockSizeWidth);
266     
267     // Check that the block wasn't partially defined, and that the offset isn't
268     // bogus.
269     if (AtEndOfStream() || NextChar+NumWords*4 > LastChar)
270       return true;
271     
272     NextChar += NumWords*4;
273     return false;
274   }
275   
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);
282     
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();
288       }
289     }
290     
291     // Get the codesize of this block.
292     CurCodeSize = ReadVBR(bitc::CodeLenWidth);
293     SkipToWord();
294     unsigned NumWords = Read(bitc::BlockSizeWidth);
295     if (NumWordsP) *NumWordsP = NumWords;
296     
297     // Validate that this block is sane.
298     if (CurCodeSize == 0 || AtEndOfStream() || NextChar+NumWords*4 > LastChar)
299       return true;
300     
301     return false;
302   }
303   
304   bool ReadBlockEnd() {
305     if (BlockScope.empty()) return true;
306     
307     // Block tail:
308     //    [END_BLOCK, <align4bytes>]
309     SkipToWord();
310     
311     PopBlockScope();
312     return false;
313   }
314   
315 private:
316   void PopBlockScope() {
317     CurCodeSize = BlockScope.back().PrevCodeSize;
318     
319     // Delete abbrevs from popped scope.
320     for (unsigned i = 0, e = CurAbbrevs.size(); i != e; ++i)
321       CurAbbrevs[i]->dropRef();
322     
323     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
324     BlockScope.pop_back();
325   }  
326     
327   //===--------------------------------------------------------------------===//
328   // Record Processing
329   //===--------------------------------------------------------------------===//
330   
331 private:
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());
337     } else {
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()));
343         break;
344       case BitCodeAbbrevOp::VBR:
345         Vals.push_back(ReadVBR64((unsigned)Op.getEncodingData()));
346         break;
347       case BitCodeAbbrevOp::Char6:
348         Vals.push_back(BitCodeAbbrevOp::DecodeChar6(Read(6)));
349         break;
350       }
351     }
352   }
353 public:
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));
360       return Code;
361     }
362     
363     unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
364     assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
365     BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
366
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);
371       } else {
372         // Array case.  Read the number of elements as a vbr6.
373         unsigned NumElts = ReadVBR(6);
374
375         // Get the element encoding.
376         assert(i+2 == e && "array op not second to last?");
377         const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
378
379         // Read all the elements.
380         for (; NumElts; --NumElts)
381           ReadAbbreviatedField(EltEnc, Vals);
382       }
383     }
384     
385     unsigned Code = (unsigned)Vals[0];
386     Vals.erase(Vals.begin());
387     return Code;
388   }
389   
390   //===--------------------------------------------------------------------===//
391   // Abbrev Processing
392   //===--------------------------------------------------------------------===//
393   
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;
399       if (IsLiteral) {
400         Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
401         continue;
402       }
403
404       BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
405       if (BitCodeAbbrevOp::hasEncodingData(E))
406         Abbv->Add(BitCodeAbbrevOp(E, ReadVBR64(5)));
407       else
408         Abbv->Add(BitCodeAbbrevOp(E));
409     }
410     CurAbbrevs.push_back(Abbv);
411   }
412   
413   //===--------------------------------------------------------------------===//
414   // BlockInfo Block Reading
415   //===--------------------------------------------------------------------===//
416   
417 private:  
418   BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
419     if (BlockInfo *BI = getBlockInfo(BlockID))
420       return *BI;
421     
422     // Otherwise, add a new record.
423     BlockInfoRecords.push_back(BlockInfo());
424     BlockInfoRecords.back().BlockID = BlockID;
425     return BlockInfoRecords.back();
426   }
427   
428 public:
429     
430   bool ReadBlockInfoBlock() {
431     if (EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID)) return true;
432
433     SmallVector<uint64_t, 64> Record;
434     BlockInfo *CurBlockInfo = 0;
435     
436     // Read all the records for this module.
437     while (1) {
438       unsigned Code = ReadCode();
439       if (Code == bitc::END_BLOCK)
440         return ReadBlockEnd();
441       if (Code == bitc::ENTER_SUBBLOCK) {
442         ReadSubBlockID();
443         if (SkipBlock()) return true;
444         continue;
445       }
446
447       // Read abbrev records, associate them with CurBID.
448       if (Code == bitc::DEFINE_ABBREV) {
449         if (!CurBlockInfo) return true;
450         ReadAbbrevRecord();
451         
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);
457         continue;
458       }
459
460       // Read a record.
461       Record.clear();
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]);
467         break;
468       }
469     }      
470   }
471 };
472
473 } // End llvm namespace
474
475 #endif