Small optimization: once the size is know, we don't have to call fillCurWord.
[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 LLVM_BITCODE_BITSTREAMREADER_H
16 #define LLVM_BITCODE_BITSTREAMREADER_H
17
18 #include "llvm/Bitcode/BitCodes.h"
19 #include "llvm/Support/Endian.h"
20 #include "llvm/Support/StreamingMemoryObject.h"
21 #include <climits>
22 #include <string>
23 #include <vector>
24
25 namespace llvm {
26
27 class Deserializer;
28
29 /// This class is used to read from an LLVM bitcode stream, maintaining
30 /// information that is global to decoding the entire file. While a file is
31 /// being read, multiple cursors can be independently advanced or skipped around
32 /// within the file.  These are represented by the BitstreamCursor class.
33 class BitstreamReader {
34 public:
35   /// This contains information emitted to BLOCKINFO_BLOCK blocks. These
36   /// describe abbreviations that all blocks of the specified ID inherit.
37   struct BlockInfo {
38     unsigned BlockID;
39     std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> Abbrevs;
40     std::string Name;
41
42     std::vector<std::pair<unsigned, std::string> > RecordNames;
43   };
44 private:
45   std::unique_ptr<MemoryObject> BitcodeBytes;
46
47   std::vector<BlockInfo> BlockInfoRecords;
48
49   /// This is set to true if we don't care about the block/record name
50   /// information in the BlockInfo block. Only llvm-bcanalyzer uses this.
51   bool IgnoreBlockInfoNames;
52
53   BitstreamReader(const BitstreamReader&) LLVM_DELETED_FUNCTION;
54   void operator=(const BitstreamReader&) LLVM_DELETED_FUNCTION;
55 public:
56   BitstreamReader() : IgnoreBlockInfoNames(true) {
57   }
58
59   BitstreamReader(const unsigned char *Start, const unsigned char *End)
60       : IgnoreBlockInfoNames(true) {
61     init(Start, End);
62   }
63
64   BitstreamReader(MemoryObject *bytes) : IgnoreBlockInfoNames(true) {
65     BitcodeBytes.reset(bytes);
66   }
67
68   BitstreamReader(BitstreamReader &&Other) {
69     *this = std::move(Other);
70   }
71
72   BitstreamReader &operator=(BitstreamReader &&Other) {
73     BitcodeBytes = std::move(Other.BitcodeBytes);
74     // Explicitly swap block info, so that nothing gets destroyed twice.
75     std::swap(BlockInfoRecords, Other.BlockInfoRecords);
76     IgnoreBlockInfoNames = Other.IgnoreBlockInfoNames;
77     return *this;
78   }
79
80   void init(const unsigned char *Start, const unsigned char *End) {
81     assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
82     BitcodeBytes.reset(getNonStreamedMemoryObject(Start, End));
83   }
84
85   MemoryObject &getBitcodeBytes() { return *BitcodeBytes; }
86
87   /// This is called by clients that want block/record name information.
88   void CollectBlockInfoNames() { IgnoreBlockInfoNames = false; }
89   bool isIgnoringBlockInfoNames() { return IgnoreBlockInfoNames; }
90
91   //===--------------------------------------------------------------------===//
92   // Block Manipulation
93   //===--------------------------------------------------------------------===//
94
95   /// Return true if we've already read and processed the block info block for
96   /// this Bitstream. We only process it for the first cursor that walks over
97   /// it.
98   bool hasBlockInfoRecords() const { return !BlockInfoRecords.empty(); }
99
100   /// If there is block info for the specified ID, return it, otherwise return
101   /// null.
102   const BlockInfo *getBlockInfo(unsigned BlockID) const {
103     // Common case, the most recent entry matches BlockID.
104     if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
105       return &BlockInfoRecords.back();
106
107     for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
108          i != e; ++i)
109       if (BlockInfoRecords[i].BlockID == BlockID)
110         return &BlockInfoRecords[i];
111     return nullptr;
112   }
113
114   BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
115     if (const BlockInfo *BI = getBlockInfo(BlockID))
116       return *const_cast<BlockInfo*>(BI);
117
118     // Otherwise, add a new record.
119     BlockInfoRecords.push_back(BlockInfo());
120     BlockInfoRecords.back().BlockID = BlockID;
121     return BlockInfoRecords.back();
122   }
123
124   /// Takes block info from the other bitstream reader.
125   ///
126   /// This is a "take" operation because BlockInfo records are non-trivial, and
127   /// indeed rather expensive.
128   void takeBlockInfo(BitstreamReader &&Other) {
129     assert(!hasBlockInfoRecords());
130     BlockInfoRecords = std::move(Other.BlockInfoRecords);
131   }
132 };
133
134 /// When advancing through a bitstream cursor, each advance can discover a few
135 /// different kinds of entries:
136 struct BitstreamEntry {
137   enum {
138     Error,    // Malformed bitcode was found.
139     EndBlock, // We've reached the end of the current block, (or the end of the
140               // file, which is treated like a series of EndBlock records.
141     SubBlock, // This is the start of a new subblock of a specific ID.
142     Record    // This is a record with a specific AbbrevID.
143   } Kind;
144
145   unsigned ID;
146
147   static BitstreamEntry getError() {
148     BitstreamEntry E; E.Kind = Error; return E;
149   }
150   static BitstreamEntry getEndBlock() {
151     BitstreamEntry E; E.Kind = EndBlock; return E;
152   }
153   static BitstreamEntry getSubBlock(unsigned ID) {
154     BitstreamEntry E; E.Kind = SubBlock; E.ID = ID; return E;
155   }
156   static BitstreamEntry getRecord(unsigned AbbrevID) {
157     BitstreamEntry E; E.Kind = Record; E.ID = AbbrevID; return E;
158   }
159 };
160
161 /// This represents a position within a bitcode file. There may be multiple
162 /// independent cursors reading within one bitstream, each maintaining their own
163 /// local state.
164 ///
165 /// Unlike iterators, BitstreamCursors are heavy-weight objects that should not
166 /// be passed by value.
167 class BitstreamCursor {
168   friend class Deserializer;
169   BitstreamReader *BitStream;
170   size_t NextChar;
171
172   // The size of the bicode. 0 if we don't know it yet.
173   size_t Size;
174
175   /// This is the current data we have pulled from the stream but have not
176   /// returned to the client. This is specifically and intentionally defined to
177   /// follow the word size of the host machine for efficiency. We use word_t in
178   /// places that are aware of this to make it perfectly explicit what is going
179   /// on.
180   typedef size_t word_t;
181   word_t CurWord;
182
183   /// This is the number of bits in CurWord that are valid. This is always from
184   /// [0...bits_of(size_t)-1] inclusive.
185   unsigned BitsInCurWord;
186
187   // This is the declared size of code values used for the current block, in
188   // bits.
189   unsigned CurCodeSize;
190
191   /// Abbrevs installed at in this block.
192   std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> CurAbbrevs;
193
194   struct Block {
195     unsigned PrevCodeSize;
196     std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> PrevAbbrevs;
197     explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
198   };
199
200   /// This tracks the codesize of parent blocks.
201   SmallVector<Block, 8> BlockScope;
202
203
204 public:
205   BitstreamCursor() { init(nullptr); }
206
207   explicit BitstreamCursor(BitstreamReader &R) { init(&R); }
208
209   void init(BitstreamReader *R) {
210     freeState();
211
212     BitStream = R;
213     NextChar = 0;
214     Size = 0;
215     BitsInCurWord = 0;
216     CurCodeSize = 2;
217   }
218
219   void freeState();
220
221   bool canSkipToPos(size_t pos) const {
222     // pos can be skipped to if it is a valid address or one byte past the end.
223     return pos == 0 || BitStream->getBitcodeBytes().isValidAddress(
224         static_cast<uint64_t>(pos - 1));
225   }
226
227   bool AtEndOfStream() {
228     if (BitsInCurWord != 0)
229       return false;
230     if (Size != 0)
231       return Size == NextChar;
232     fillCurWord();
233     return BitsInCurWord == 0;
234   }
235
236   /// Return the number of bits used to encode an abbrev #.
237   unsigned getAbbrevIDWidth() const { return CurCodeSize; }
238
239   /// Return the bit # of the bit we are reading.
240   uint64_t GetCurrentBitNo() const {
241     return NextChar*CHAR_BIT - BitsInCurWord;
242   }
243
244   BitstreamReader *getBitStreamReader() {
245     return BitStream;
246   }
247   const BitstreamReader *getBitStreamReader() const {
248     return BitStream;
249   }
250
251   /// Flags that modify the behavior of advance().
252   enum {
253     /// If this flag is used, the advance() method does not automatically pop
254     /// the block scope when the end of a block is reached.
255     AF_DontPopBlockAtEnd = 1,
256
257     /// If this flag is used, abbrev entries are returned just like normal
258     /// records.
259     AF_DontAutoprocessAbbrevs = 2
260   };
261
262       /// Advance the current bitstream, returning the next entry in the stream.
263       BitstreamEntry advance(unsigned Flags = 0) {
264     while (1) {
265       unsigned Code = ReadCode();
266       if (Code == bitc::END_BLOCK) {
267         // Pop the end of the block unless Flags tells us not to.
268         if (!(Flags & AF_DontPopBlockAtEnd) && ReadBlockEnd())
269           return BitstreamEntry::getError();
270         return BitstreamEntry::getEndBlock();
271       }
272
273       if (Code == bitc::ENTER_SUBBLOCK)
274         return BitstreamEntry::getSubBlock(ReadSubBlockID());
275
276       if (Code == bitc::DEFINE_ABBREV &&
277           !(Flags & AF_DontAutoprocessAbbrevs)) {
278         // We read and accumulate abbrev's, the client can't do anything with
279         // them anyway.
280         ReadAbbrevRecord();
281         continue;
282       }
283
284       return BitstreamEntry::getRecord(Code);
285     }
286   }
287
288   /// This is a convenience function for clients that don't expect any
289   /// subblocks. This just skips over them automatically.
290   BitstreamEntry advanceSkippingSubblocks(unsigned Flags = 0) {
291     while (1) {
292       // If we found a normal entry, return it.
293       BitstreamEntry Entry = advance(Flags);
294       if (Entry.Kind != BitstreamEntry::SubBlock)
295         return Entry;
296
297       // If we found a sub-block, just skip over it and check the next entry.
298       if (SkipBlock())
299         return BitstreamEntry::getError();
300     }
301   }
302
303   /// Reset the stream to the specified bit number.
304   void JumpToBit(uint64_t BitNo) {
305     uintptr_t ByteNo = uintptr_t(BitNo/8) & ~(sizeof(word_t)-1);
306     unsigned WordBitNo = unsigned(BitNo & (sizeof(word_t)*8-1));
307     assert(canSkipToPos(ByteNo) && "Invalid location");
308
309     // Move the cursor to the right word.
310     NextChar = ByteNo;
311     BitsInCurWord = 0;
312
313     // Skip over any bits that are already consumed.
314     if (WordBitNo) {
315       if (sizeof(word_t) > 4)
316         Read64(WordBitNo);
317       else
318         Read(WordBitNo);
319     }
320   }
321
322   void fillCurWord() {
323     assert(Size == 0 || NextChar < (unsigned)Size);
324
325     // Read the next word from the stream.
326     uint8_t Array[sizeof(word_t)] = {0};
327
328     uint64_t BytesRead =
329         BitStream->getBitcodeBytes().readBytes(Array, sizeof(Array), NextChar);
330
331     // If we run out of data, stop at the end of the stream.
332     if (BytesRead == 0) {
333       Size = NextChar;
334       return;
335     }
336
337     // Handle big-endian byte-swapping if necessary.
338     support::detail::packed_endian_specific_integral<
339         word_t, support::little, support::unaligned> EndianValue;
340     memcpy(&EndianValue, Array, sizeof(Array));
341
342     CurWord = EndianValue;
343     NextChar += BytesRead;
344     BitsInCurWord = BytesRead * 8;
345   }
346
347   uint32_t Read(unsigned NumBits) {
348     assert(NumBits && NumBits <= 32 &&
349            "Cannot return zero or more than 32 bits!");
350
351     static const unsigned Mask = sizeof(word_t) > 4 ? 0x3f : 0x1f;
352
353     // If the field is fully contained by CurWord, return it quickly.
354     if (BitsInCurWord >= NumBits) {
355       uint32_t R = uint32_t(CurWord) & (~0U >> (32-NumBits));
356
357       // Use a mask to avoid undefined behavior.
358       CurWord >>= (NumBits & Mask);
359
360       BitsInCurWord -= NumBits;
361       return R;
362     }
363
364     uint32_t R = BitsInCurWord ? uint32_t(CurWord) : 0;
365     unsigned BitsLeft = NumBits - BitsInCurWord;
366
367     fillCurWord();
368
369     // If we run out of data, stop at the end of the stream.
370     if (BitsLeft > BitsInCurWord)
371       return 0;
372
373     uint32_t R2 =
374         uint32_t(CurWord) & (~word_t(0) >> (sizeof(word_t) * 8 - BitsLeft));
375
376     // Use a mask to avoid undefined behavior.
377     CurWord >>= (BitsLeft & Mask);
378
379     BitsInCurWord -= BitsLeft;
380
381     R |= uint32_t(R2 << (NumBits - BitsLeft));
382
383     return R;
384   }
385
386   uint64_t Read64(unsigned NumBits) {
387     if (NumBits <= 32) return Read(NumBits);
388
389     uint64_t V = Read(32);
390     return V | (uint64_t)Read(NumBits-32) << 32;
391   }
392
393   uint32_t ReadVBR(unsigned NumBits) {
394     uint32_t Piece = Read(NumBits);
395     if ((Piece & (1U << (NumBits-1))) == 0)
396       return Piece;
397
398     uint32_t Result = 0;
399     unsigned NextBit = 0;
400     while (1) {
401       Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
402
403       if ((Piece & (1U << (NumBits-1))) == 0)
404         return Result;
405
406       NextBit += NumBits-1;
407       Piece = Read(NumBits);
408     }
409   }
410
411   // Read a VBR that may have a value up to 64-bits in size. The chunk size of
412   // the VBR must still be <= 32 bits though.
413   uint64_t ReadVBR64(unsigned NumBits) {
414     uint32_t Piece = Read(NumBits);
415     if ((Piece & (1U << (NumBits-1))) == 0)
416       return uint64_t(Piece);
417
418     uint64_t Result = 0;
419     unsigned NextBit = 0;
420     while (1) {
421       Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
422
423       if ((Piece & (1U << (NumBits-1))) == 0)
424         return Result;
425
426       NextBit += NumBits-1;
427       Piece = Read(NumBits);
428     }
429   }
430
431 private:
432   void SkipToFourByteBoundary() {
433     // If word_t is 64-bits and if we've read less than 32 bits, just dump
434     // the bits we have up to the next 32-bit boundary.
435     if (sizeof(word_t) > 4 &&
436         BitsInCurWord >= 32) {
437       CurWord >>= BitsInCurWord-32;
438       BitsInCurWord = 32;
439       return;
440     }
441
442     BitsInCurWord = 0;
443   }
444 public:
445
446   unsigned ReadCode() {
447     return Read(CurCodeSize);
448   }
449
450
451   // Block header:
452   //    [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
453
454   /// Having read the ENTER_SUBBLOCK code, read the BlockID for the block.
455   unsigned ReadSubBlockID() {
456     return ReadVBR(bitc::BlockIDWidth);
457   }
458
459   /// Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body
460   /// of this block. If the block record is malformed, return true.
461   bool SkipBlock() {
462     // Read and ignore the codelen value.  Since we are skipping this block, we
463     // don't care what code widths are used inside of it.
464     ReadVBR(bitc::CodeLenWidth);
465     SkipToFourByteBoundary();
466     unsigned NumFourBytes = Read(bitc::BlockSizeWidth);
467
468     // Check that the block wasn't partially defined, and that the offset isn't
469     // bogus.
470     size_t SkipTo = GetCurrentBitNo() + NumFourBytes*4*8;
471     if (AtEndOfStream() || !canSkipToPos(SkipTo/8))
472       return true;
473
474     JumpToBit(SkipTo);
475     return false;
476   }
477
478   /// Having read the ENTER_SUBBLOCK abbrevid, enter the block, and return true
479   /// if the block has an error.
480   bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = nullptr);
481
482   bool ReadBlockEnd() {
483     if (BlockScope.empty()) return true;
484
485     // Block tail:
486     //    [END_BLOCK, <align4bytes>]
487     SkipToFourByteBoundary();
488
489     popBlockScope();
490     return false;
491   }
492
493 private:
494
495   void popBlockScope() {
496     CurCodeSize = BlockScope.back().PrevCodeSize;
497
498     CurAbbrevs = std::move(BlockScope.back().PrevAbbrevs);
499     BlockScope.pop_back();
500   }
501
502   //===--------------------------------------------------------------------===//
503   // Record Processing
504   //===--------------------------------------------------------------------===//
505
506 private:
507   void readAbbreviatedLiteral(const BitCodeAbbrevOp &Op,
508                               SmallVectorImpl<uint64_t> &Vals);
509   void readAbbreviatedField(const BitCodeAbbrevOp &Op,
510                             SmallVectorImpl<uint64_t> &Vals);
511   void skipAbbreviatedField(const BitCodeAbbrevOp &Op);
512
513 public:
514
515   /// Return the abbreviation for the specified AbbrevId.
516   const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
517     unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
518     assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
519     return CurAbbrevs[AbbrevNo].get();
520   }
521
522   /// Read the current record and discard it.
523   void skipRecord(unsigned AbbrevID);
524
525   unsigned readRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
526                       StringRef *Blob = nullptr);
527
528   //===--------------------------------------------------------------------===//
529   // Abbrev Processing
530   //===--------------------------------------------------------------------===//
531   void ReadAbbrevRecord();
532
533   bool ReadBlockInfoBlock();
534 };
535
536 } // End llvm namespace
537
538 #endif