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