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