Make a major API change to BitstreamReader: split all the reading
[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 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 <climits>
20 #include <vector>
21
22 namespace llvm {
23
24   class Deserializer;
25
26 class BitstreamReader {
27 public:
28   /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
29   /// These describe abbreviations that all blocks of the specified ID inherit.
30   struct BlockInfo {
31     unsigned BlockID;
32     std::vector<BitCodeAbbrev*> Abbrevs;
33   };
34 private:
35   /// FirstChar/LastChar - This remembers the first and last bytes of the
36   /// stream.
37   const unsigned char *FirstChar, *LastChar;
38   
39   std::vector<BlockInfo> BlockInfoRecords;
40
41 public:
42   BitstreamReader() : FirstChar(0), LastChar(0) {
43   }
44
45   BitstreamReader(const unsigned char *Start, const unsigned char *End) {
46     init(Start, End);
47   }
48
49   void init(const unsigned char *Start, const unsigned char *End) {
50     FirstChar = Start;
51     LastChar = End;
52     assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
53   }
54
55   ~BitstreamReader() {
56     // Free the BlockInfoRecords.
57     while (!BlockInfoRecords.empty()) {
58       BlockInfo &Info = BlockInfoRecords.back();
59       // Free blockinfo abbrev info.
60       for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
61            i != e; ++i)
62         Info.Abbrevs[i]->dropRef();
63       BlockInfoRecords.pop_back();
64     }
65   }
66   
67   const unsigned char *getFirstChar() const { return FirstChar; }
68   const unsigned char *getLastChar() const { return LastChar; }
69
70   //===--------------------------------------------------------------------===//
71   // Block Manipulation
72   //===--------------------------------------------------------------------===//
73
74   /// getBlockInfo - If there is block info for the specified ID, return it,
75   /// otherwise return null.
76   BlockInfo *getBlockInfo(unsigned BlockID) {
77     // Common case, the most recent entry matches BlockID.
78     if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
79       return &BlockInfoRecords.back();
80
81     for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
82          i != e; ++i)
83       if (BlockInfoRecords[i].BlockID == BlockID)
84         return &BlockInfoRecords[i];
85     return 0;
86   }
87
88   BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
89     if (BlockInfo *BI = getBlockInfo(BlockID))
90       return *BI;
91
92     // Otherwise, add a new record.
93     BlockInfoRecords.push_back(BlockInfo());
94     BlockInfoRecords.back().BlockID = BlockID;
95     return BlockInfoRecords.back();
96   }
97
98 };
99
100 class BitstreamCursor {
101   friend class Deserializer;
102   BitstreamReader *BitStream;
103   const unsigned char *NextChar;
104   
105   /// CurWord - This is the current data we have pulled from the stream but have
106   /// not returned to the client.
107   uint32_t CurWord;
108   
109   /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
110   /// is always from [0...31] inclusive.
111   unsigned BitsInCurWord;
112   
113   // CurCodeSize - This is the declared size of code values used for the current
114   // block, in bits.
115   unsigned CurCodeSize;
116   
117   /// CurAbbrevs - Abbrevs installed at in this block.
118   std::vector<BitCodeAbbrev*> CurAbbrevs;
119   
120   struct Block {
121     unsigned PrevCodeSize;
122     std::vector<BitCodeAbbrev*> PrevAbbrevs;
123     explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
124   };
125   
126   /// BlockScope - This tracks the codesize of parent blocks.
127   SmallVector<Block, 8> BlockScope;
128   
129   BitstreamCursor(const BitstreamCursor&); // NOT YET IMPLEMENTED.
130   void operator=(const BitstreamCursor&);  // NOT YET IMPLEMENTED.
131 public:
132   BitstreamCursor() : BitStream(0), NextChar(0) {
133   }
134   explicit BitstreamCursor(BitstreamReader &R) : BitStream(&R) {
135     NextChar = R.getFirstChar();
136     assert(NextChar && "Bitstream not initialized yet");
137     CurWord = 0;
138     BitsInCurWord = 0;
139     CurCodeSize = 2;
140   }
141   
142   void init(BitstreamReader &R) {
143     freeState();
144     
145     BitStream = &R;
146     NextChar = R.getFirstChar();
147     assert(NextChar && "Bitstream not initialized yet");
148     CurWord = 0;
149     BitsInCurWord = 0;
150     CurCodeSize = 2;
151   }
152   
153   ~BitstreamCursor() {
154     freeState();
155   }
156   
157   void freeState() {
158     // Free all the Abbrevs.
159     for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
160          i != e; ++i)
161       CurAbbrevs[i]->dropRef();
162     CurAbbrevs.clear();
163     
164     // Free all the Abbrevs in the block scope.
165     for (unsigned S = 0, e = static_cast<unsigned>(BlockScope.size());
166          S != e; ++S) {
167       std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
168       for (unsigned i = 0, e = static_cast<unsigned>(Abbrevs.size());
169            i != e; ++i)
170         Abbrevs[i]->dropRef();
171     }
172     BlockScope.clear();
173   }
174   
175   /// GetAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
176   unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
177   
178   bool AtEndOfStream() const {
179     return NextChar == BitStream->getLastChar() && BitsInCurWord == 0;
180   }
181   
182   /// GetCurrentBitNo - Return the bit # of the bit we are reading.
183   uint64_t GetCurrentBitNo() const {
184     return (NextChar-BitStream->getFirstChar())*CHAR_BIT - BitsInCurWord;
185   }
186   
187   
188   /// JumpToBit - Reset the stream to the specified bit number.
189   void JumpToBit(uint64_t BitNo) {
190     uintptr_t ByteNo = uintptr_t(BitNo/8) & ~3;
191     uintptr_t WordBitNo = uintptr_t(BitNo) & 31;
192     assert(ByteNo <= (uintptr_t)(BitStream->getLastChar()-
193                                  BitStream->getFirstChar()) &&
194            "Invalid location");
195     
196     // Move the cursor to the right word.
197     NextChar = BitStream->getFirstChar()+ByteNo;
198     BitsInCurWord = 0;
199     CurWord = 0;
200     
201     // Skip over any bits that are already consumed.
202     if (WordBitNo)
203       Read(static_cast<unsigned>(WordBitNo));
204   }
205   
206   
207   uint32_t Read(unsigned NumBits) {
208     // If the field is fully contained by CurWord, return it quickly.
209     if (BitsInCurWord >= NumBits) {
210       uint32_t R = CurWord & ((1U << NumBits)-1);
211       CurWord >>= NumBits;
212       BitsInCurWord -= NumBits;
213       return R;
214     }
215
216     // If we run out of data, stop at the end of the stream.
217     if (NextChar == BitStream->getLastChar()) {
218       CurWord = 0;
219       BitsInCurWord = 0;
220       return 0;
221     }
222
223     unsigned R = CurWord;
224
225     // Read the next word from the stream.
226     CurWord = (NextChar[0] <<  0) | (NextChar[1] << 8) |
227               (NextChar[2] << 16) | (NextChar[3] << 24);
228     NextChar += 4;
229
230     // Extract NumBits-BitsInCurWord from what we just read.
231     unsigned BitsLeft = NumBits-BitsInCurWord;
232
233     // Be careful here, BitsLeft is in the range [1..32] inclusive.
234     R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
235
236     // BitsLeft bits have just been used up from CurWord.
237     if (BitsLeft != 32)
238       CurWord >>= BitsLeft;
239     else
240       CurWord = 0;
241     BitsInCurWord = 32-BitsLeft;
242     return R;
243   }
244
245   uint64_t Read64(unsigned NumBits) {
246     if (NumBits <= 32) return Read(NumBits);
247
248     uint64_t V = Read(32);
249     return V | (uint64_t)Read(NumBits-32) << 32;
250   }
251
252   uint32_t ReadVBR(unsigned NumBits) {
253     uint32_t Piece = Read(NumBits);
254     if ((Piece & (1U << (NumBits-1))) == 0)
255       return Piece;
256
257     uint32_t Result = 0;
258     unsigned NextBit = 0;
259     while (1) {
260       Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
261
262       if ((Piece & (1U << (NumBits-1))) == 0)
263         return Result;
264
265       NextBit += NumBits-1;
266       Piece = Read(NumBits);
267     }
268   }
269
270   uint64_t ReadVBR64(unsigned NumBits) {
271     uint64_t Piece = Read(NumBits);
272     if ((Piece & (1U << (NumBits-1))) == 0)
273       return Piece;
274
275     uint64_t Result = 0;
276     unsigned NextBit = 0;
277     while (1) {
278       Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
279
280       if ((Piece & (1U << (NumBits-1))) == 0)
281         return Result;
282
283       NextBit += NumBits-1;
284       Piece = Read(NumBits);
285     }
286   }
287
288   void SkipToWord() {
289     BitsInCurWord = 0;
290     CurWord = 0;
291   }
292
293   unsigned ReadCode() {
294     return Read(CurCodeSize);
295   }
296
297
298   // Block header:
299   //    [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
300
301   /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
302   /// the block.
303   unsigned ReadSubBlockID() {
304     return ReadVBR(bitc::BlockIDWidth);
305   }
306
307   /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
308   /// over the body of this block.  If the block record is malformed, return
309   /// true.
310   bool SkipBlock() {
311     // Read and ignore the codelen value.  Since we are skipping this block, we
312     // don't care what code widths are used inside of it.
313     ReadVBR(bitc::CodeLenWidth);
314     SkipToWord();
315     unsigned NumWords = Read(bitc::BlockSizeWidth);
316
317     // Check that the block wasn't partially defined, and that the offset isn't
318     // bogus.
319     if (AtEndOfStream() || NextChar+NumWords*4 > BitStream->getLastChar())
320       return true;
321
322     NextChar += NumWords*4;
323     return false;
324   }
325
326   /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, enter
327   /// the block, and return true if the block is valid.
328   bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = 0) {
329     // Save the current block's state on BlockScope.
330     BlockScope.push_back(Block(CurCodeSize));
331     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
332
333     // Add the abbrevs specific to this block to the CurAbbrevs list.
334     if (BitstreamReader::BlockInfo *Info = BitStream->getBlockInfo(BlockID)) {
335       for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
336            i != e; ++i) {
337         CurAbbrevs.push_back(Info->Abbrevs[i]);
338         CurAbbrevs.back()->addRef();
339       }
340     }
341
342     // Get the codesize of this block.
343     CurCodeSize = ReadVBR(bitc::CodeLenWidth);
344     SkipToWord();
345     unsigned NumWords = Read(bitc::BlockSizeWidth);
346     if (NumWordsP) *NumWordsP = NumWords;
347
348     // Validate that this block is sane.
349     if (CurCodeSize == 0 || AtEndOfStream() ||
350         NextChar+NumWords*4 > BitStream->getLastChar())
351       return true;
352
353     return false;
354   }
355
356   bool ReadBlockEnd() {
357     if (BlockScope.empty()) return true;
358
359     // Block tail:
360     //    [END_BLOCK, <align4bytes>]
361     SkipToWord();
362
363     PopBlockScope();
364     return false;
365   }
366
367 private:
368   void PopBlockScope() {
369     CurCodeSize = BlockScope.back().PrevCodeSize;
370
371     // Delete abbrevs from popped scope.
372     for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
373          i != e; ++i)
374       CurAbbrevs[i]->dropRef();
375
376     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
377     BlockScope.pop_back();
378   }
379
380  //===--------------------------------------------------------------------===//
381   // Record Processing
382   //===--------------------------------------------------------------------===//
383
384 private:
385   void ReadAbbreviatedLiteral(const BitCodeAbbrevOp &Op,
386                               SmallVectorImpl<uint64_t> &Vals) {
387     assert(Op.isLiteral() && "Not a literal");
388     // If the abbrev specifies the literal value to use, use it.
389     Vals.push_back(Op.getLiteralValue());
390   }
391   
392   void ReadAbbreviatedField(const BitCodeAbbrevOp &Op,
393                             SmallVectorImpl<uint64_t> &Vals) {
394     assert(!Op.isLiteral() && "Use ReadAbbreviatedLiteral for literals!");
395     
396     // Decode the value as we are commanded.
397     switch (Op.getEncoding()) {
398     default: assert(0 && "Unknown encoding!");
399     case BitCodeAbbrevOp::Fixed:
400       Vals.push_back(Read((unsigned)Op.getEncodingData()));
401       break;
402     case BitCodeAbbrevOp::VBR:
403       Vals.push_back(ReadVBR64((unsigned)Op.getEncodingData()));
404       break;
405     case BitCodeAbbrevOp::Char6:
406       Vals.push_back(BitCodeAbbrevOp::DecodeChar6(Read(6)));
407       break;
408     }
409   }
410 public:
411
412   /// getAbbrev - Return the abbreviation for the specified AbbrevId. 
413   const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
414     unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
415     assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
416     return CurAbbrevs[AbbrevNo];
417   }
418   
419   unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
420                       const char **BlobStart = 0, unsigned *BlobLen = 0) {
421     if (AbbrevID == bitc::UNABBREV_RECORD) {
422       unsigned Code = ReadVBR(6);
423       unsigned NumElts = ReadVBR(6);
424       for (unsigned i = 0; i != NumElts; ++i)
425         Vals.push_back(ReadVBR64(6));
426       return Code;
427     }
428
429     const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
430
431     for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
432       const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
433       if (Op.isLiteral()) {
434         ReadAbbreviatedLiteral(Op, Vals); 
435       } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
436         // Array case.  Read the number of elements as a vbr6.
437         unsigned NumElts = ReadVBR(6);
438
439         // Get the element encoding.
440         assert(i+2 == e && "array op not second to last?");
441         const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
442
443         // Read all the elements.
444         for (; NumElts; --NumElts)
445           ReadAbbreviatedField(EltEnc, Vals);
446       } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
447         // Blob case.  Read the number of bytes as a vbr6.
448         unsigned NumElts = ReadVBR(6);
449         SkipToWord();  // 32-bit alignment
450
451         // Figure out where the end of this blob will be including tail padding.
452         const unsigned char *NewEnd = NextChar+((NumElts+3)&~3);
453         
454         // If this would read off the end of the bitcode file, just set the
455         // record to empty and return.
456         if (NewEnd > BitStream->getLastChar()) {
457           Vals.append(NumElts, 0);
458           NextChar = BitStream->getLastChar();
459           break;
460         }
461         
462         // Otherwise, read the number of bytes.  If we can return a reference to
463         // the data, do so to avoid copying it.
464         if (BlobStart) {
465           *BlobStart = (const char*)NextChar;
466           *BlobLen = NumElts;
467         } else {
468           for (; NumElts; ++NextChar, --NumElts)
469             Vals.push_back(*NextChar);
470         }
471         // Skip over tail padding.
472         NextChar = NewEnd;
473       } else {
474         ReadAbbreviatedField(Op, Vals);
475       }
476     }
477
478     unsigned Code = (unsigned)Vals[0];
479     Vals.erase(Vals.begin());
480     return Code;
481   }
482
483   unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
484                       const char *&BlobStart, unsigned &BlobLen) {
485     return ReadRecord(AbbrevID, Vals, &BlobStart, &BlobLen);
486   }
487
488   
489   //===--------------------------------------------------------------------===//
490   // Abbrev Processing
491   //===--------------------------------------------------------------------===//
492
493   void ReadAbbrevRecord() {
494     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
495     unsigned NumOpInfo = ReadVBR(5);
496     for (unsigned i = 0; i != NumOpInfo; ++i) {
497       bool IsLiteral = Read(1) ? true : false;
498       if (IsLiteral) {
499         Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
500         continue;
501       }
502
503       BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
504       if (BitCodeAbbrevOp::hasEncodingData(E))
505         Abbv->Add(BitCodeAbbrevOp(E, ReadVBR64(5)));
506       else
507         Abbv->Add(BitCodeAbbrevOp(E));
508     }
509     CurAbbrevs.push_back(Abbv);
510   }
511   
512 public:
513
514   bool ReadBlockInfoBlock() {
515     if (EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID)) return true;
516
517     SmallVector<uint64_t, 64> Record;
518     BitstreamReader::BlockInfo *CurBlockInfo = 0;
519
520     // Read all the records for this module.
521     while (1) {
522       unsigned Code = ReadCode();
523       if (Code == bitc::END_BLOCK)
524         return ReadBlockEnd();
525       if (Code == bitc::ENTER_SUBBLOCK) {
526         ReadSubBlockID();
527         if (SkipBlock()) return true;
528         continue;
529       }
530
531       // Read abbrev records, associate them with CurBID.
532       if (Code == bitc::DEFINE_ABBREV) {
533         if (!CurBlockInfo) return true;
534         ReadAbbrevRecord();
535
536         // ReadAbbrevRecord installs the abbrev in CurAbbrevs.  Move it to the
537         // appropriate BlockInfo.
538         BitCodeAbbrev *Abbv = CurAbbrevs.back();
539         CurAbbrevs.pop_back();
540         CurBlockInfo->Abbrevs.push_back(Abbv);
541         continue;
542       }
543
544       // Read a record.
545       Record.clear();
546       switch (ReadRecord(Code, Record)) {
547       default: break;  // Default behavior, ignore unknown content.
548       case bitc::BLOCKINFO_CODE_SETBID:
549         if (Record.size() < 1) return true;
550         CurBlockInfo = &BitStream->getOrCreateBlockInfo((unsigned)Record[0]);
551         break;
552       }
553     }
554   }
555 };
556   
557 } // End llvm namespace
558
559 #endif