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