Coverage Report

Created: 2017-10-03 07:32

/Users/buildslave/jenkins/sharedspace/clang-stage2-coverage-R@2/llvm/include/llvm/Bitcode/BitstreamReader.h
Line
Count
Source (jump to first uncovered line)
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/ADT/ArrayRef.h"
19
#include "llvm/ADT/SmallVector.h"
20
#include "llvm/Bitcode/BitCodes.h"
21
#include "llvm/Support/Endian.h"
22
#include "llvm/Support/ErrorHandling.h"
23
#include "llvm/Support/MathExtras.h"
24
#include "llvm/Support/MemoryBuffer.h"
25
#include <algorithm>
26
#include <cassert>
27
#include <climits>
28
#include <cstddef>
29
#include <cstdint>
30
#include <memory>
31
#include <string>
32
#include <utility>
33
#include <vector>
34
35
namespace llvm {
36
37
/// This class maintains the abbreviations read from a block info block.
38
class BitstreamBlockInfo {
39
public:
40
  /// This contains information emitted to BLOCKINFO_BLOCK blocks. These
41
  /// describe abbreviations that all blocks of the specified ID inherit.
42
  struct BlockInfo {
43
    unsigned BlockID;
44
    std::vector<std::shared_ptr<BitCodeAbbrev>> Abbrevs;
45
    std::string Name;
46
    std::vector<std::pair<unsigned, std::string>> RecordNames;
47
  };
48
49
private:
50
  std::vector<BlockInfo> BlockInfoRecords;
51
52
public:
53
  /// If there is block info for the specified ID, return it, otherwise return
54
  /// null.
55
2.10M
  const BlockInfo *getBlockInfo(unsigned BlockID) const {
56
2.10M
    // Common case, the most recent entry matches BlockID.
57
2.10M
    if (
!BlockInfoRecords.empty() && 2.10M
BlockInfoRecords.back().BlockID == BlockID2.07M
)
58
655k
      return &BlockInfoRecords.back();
59
2.10M
60
1.45M
    for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
61
3.11M
         
i != e3.11M
;
++i1.66M
)
62
2.61M
      
if (2.61M
BlockInfoRecords[i].BlockID == BlockID2.61M
)
63
955k
        return &BlockInfoRecords[i];
64
495k
    return nullptr;
65
2.10M
  }
66
67
34.2k
  BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
68
34.2k
    if (const BlockInfo *BI = getBlockInfo(BlockID))
69
30
      return *const_cast<BlockInfo*>(BI);
70
34.2k
71
34.2k
    // Otherwise, add a new record.
72
34.2k
    BlockInfoRecords.emplace_back();
73
34.2k
    BlockInfoRecords.back().BlockID = BlockID;
74
34.2k
    return BlockInfoRecords.back();
75
34.2k
  }
76
};
77
78
/// This represents a position within a bitstream. There may be multiple
79
/// independent cursors reading within one bitstream, each maintaining their
80
/// own local state.
81
class SimpleBitstreamCursor {
82
  ArrayRef<uint8_t> BitcodeBytes;
83
  size_t NextChar = 0;
84
85
public:
86
  /// This is the current data we have pulled from the stream but have not
87
  /// returned to the client. This is specifically and intentionally defined to
88
  /// follow the word size of the host machine for efficiency. We use word_t in
89
  /// places that are aware of this to make it perfectly explicit what is going
90
  /// on.
91
  using word_t = size_t;
92
93
private:
94
  word_t CurWord = 0;
95
96
  /// This is the number of bits in CurWord that are valid. This is always from
97
  /// [0...bits_of(size_t)-1] inclusive.
98
  unsigned BitsInCurWord = 0;
99
100
public:
101
  static const size_t MaxChunkSize = sizeof(word_t) * 8;
102
103
38.8k
  SimpleBitstreamCursor() = default;
104
  explicit SimpleBitstreamCursor(ArrayRef<uint8_t> BitcodeBytes)
105
23.4k
      : BitcodeBytes(BitcodeBytes) {}
106
  explicit SimpleBitstreamCursor(StringRef BitcodeBytes)
107
      : BitcodeBytes(reinterpret_cast<const uint8_t *>(BitcodeBytes.data()),
108
38.0k
                     BitcodeBytes.size()) {}
109
  explicit SimpleBitstreamCursor(MemoryBufferRef BitcodeBytes)
110
0
      : SimpleBitstreamCursor(BitcodeBytes.getBuffer()) {}
111
112
319k
  bool canSkipToPos(size_t pos) const {
113
319k
    // pos can be skipped to if it is a valid address or one byte past the end.
114
319k
    return pos <= BitcodeBytes.size();
115
319k
  }
116
117
58.1M
  bool AtEndOfStream() {
118
4.57M
    return BitsInCurWord == 0 && BitcodeBytes.size() <= NextChar;
119
58.1M
  }
120
121
  /// Return the bit # of the bit we are reading.
122
1.00M
  uint64_t GetCurrentBitNo() const {
123
1.00M
    return NextChar*CHAR_BIT - BitsInCurWord;
124
1.00M
  }
125
126
  // Return the byte # of the current bit.
127
39.0k
  uint64_t getCurrentByteNo() const { return GetCurrentBitNo() / 8; }
128
129
38.1k
  ArrayRef<uint8_t> getBitcodeBytes() const { return BitcodeBytes; }
130
131
  /// Reset the stream to the specified bit number.
132
1.62M
  void JumpToBit(uint64_t BitNo) {
133
1.62M
    size_t ByteNo = size_t(BitNo/8) & ~(sizeof(word_t)-1);
134
1.62M
    unsigned WordBitNo = unsigned(BitNo & (sizeof(word_t)*8-1));
135
1.62M
    assert(canSkipToPos(ByteNo) && "Invalid location");
136
1.62M
137
1.62M
    // Move the cursor to the right word.
138
1.62M
    NextChar = ByteNo;
139
1.62M
    BitsInCurWord = 0;
140
1.62M
141
1.62M
    // Skip over any bits that are already consumed.
142
1.62M
    if (WordBitNo)
143
1.39M
      Read(WordBitNo);
144
1.62M
  }
145
146
  /// Get a pointer into the bitstream at the specified byte offset.
147
176k
  const uint8_t *getPointerToByte(uint64_t ByteNo, uint64_t NumBytes) {
148
176k
    return BitcodeBytes.data() + ByteNo;
149
176k
  }
150
151
  /// Get a pointer into the bitstream at the specified bit offset.
152
  ///
153
  /// The bit offset must be on a byte boundary.
154
176k
  const uint8_t *getPointerToBit(uint64_t BitNo, uint64_t NumBytes) {
155
176k
    assert(!(BitNo % 8) && "Expected bit on byte boundary");
156
176k
    return getPointerToByte(BitNo / 8, NumBytes);
157
176k
  }
158
159
61.4M
  void fillCurWord() {
160
61.4M
    if (NextChar >= BitcodeBytes.size())
161
0
      report_fatal_error("Unexpected end of file");
162
61.4M
163
61.4M
    // Read the next word from the stream.
164
61.4M
    const uint8_t *NextCharPtr = BitcodeBytes.data() + NextChar;
165
61.4M
    unsigned BytesRead;
166
61.4M
    if (
BitcodeBytes.size() >= NextChar + sizeof(word_t)61.4M
) {
167
61.4M
      BytesRead = sizeof(word_t);
168
61.4M
      CurWord =
169
61.4M
          support::endian::read<word_t, support::little, support::unaligned>(
170
61.4M
              NextCharPtr);
171
61.4M
    } else {
172
33.7k
      // Short read.
173
33.7k
      BytesRead = BitcodeBytes.size() - NextChar;
174
33.7k
      CurWord = 0;
175
168k
      for (unsigned B = 0; 
B != BytesRead168k
;
++B135k
)
176
135k
        CurWord |= uint64_t(NextCharPtr[B]) << (B * 8);
177
33.7k
    }
178
61.4M
    NextChar += BytesRead;
179
61.4M
    BitsInCurWord = BytesRead * 8;
180
61.4M
  }
181
182
629M
  word_t Read(unsigned NumBits) {
183
629M
    static const unsigned BitsInWord = MaxChunkSize;
184
629M
185
629M
    assert(NumBits && NumBits <= BitsInWord &&
186
629M
           "Cannot return zero or more than BitsInWord bits!");
187
629M
188
629M
    static const unsigned Mask = sizeof(word_t) > 4 ? 
0x3f0
:
0x1f629M
;
189
629M
190
629M
    // If the field is fully contained by CurWord, return it quickly.
191
629M
    if (
BitsInCurWord >= NumBits629M
) {
192
568M
      word_t R = CurWord & (~word_t(0) >> (BitsInWord - NumBits));
193
568M
194
568M
      // Use a mask to avoid undefined behavior.
195
568M
      CurWord >>= (NumBits & Mask);
196
568M
197
568M
      BitsInCurWord -= NumBits;
198
568M
      return R;
199
568M
    }
200
629M
201
61.4M
    
word_t R = BitsInCurWord ? 61.4M
CurWord44.2M
:
017.1M
;
202
61.4M
    unsigned BitsLeft = NumBits - BitsInCurWord;
203
61.4M
204
61.4M
    fillCurWord();
205
61.4M
206
61.4M
    // If we run out of data, abort.
207
61.4M
    if (BitsLeft > BitsInCurWord)
208
0
      report_fatal_error("Unexpected end of file");
209
61.4M
210
61.4M
    word_t R2 = CurWord & (~word_t(0) >> (BitsInWord - BitsLeft));
211
61.4M
212
61.4M
    // Use a mask to avoid undefined behavior.
213
61.4M
    CurWord >>= (BitsLeft & Mask);
214
61.4M
215
61.4M
    BitsInCurWord -= BitsLeft;
216
61.4M
217
61.4M
    R |= R2 << (NumBits - BitsLeft);
218
61.4M
219
61.4M
    return R;
220
629M
  }
221
222
62.4M
  uint32_t ReadVBR(unsigned NumBits) {
223
62.4M
    uint32_t Piece = Read(NumBits);
224
62.4M
    if ((Piece & (1U << (NumBits-1))) == 0)
225
57.6M
      return Piece;
226
62.4M
227
4.85M
    uint32_t Result = 0;
228
4.85M
    unsigned NextBit = 0;
229
9.72M
    while (
true9.72M
) {
230
9.72M
      Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
231
9.72M
232
9.72M
      if ((Piece & (1U << (NumBits-1))) == 0)
233
4.85M
        return Result;
234
9.72M
235
4.86M
      NextBit += NumBits-1;
236
4.86M
      Piece = Read(NumBits);
237
4.86M
    }
238
62.4M
  }
239
240
  // Read a VBR that may have a value up to 64-bits in size. The chunk size of
241
  // the VBR must still be <= 32 bits though.
242
157M
  uint64_t ReadVBR64(unsigned NumBits) {
243
157M
    uint32_t Piece = Read(NumBits);
244
157M
    if ((Piece & (1U << (NumBits-1))) == 0)
245
88.4M
      return uint64_t(Piece);
246
157M
247
68.6M
    uint64_t Result = 0;
248
68.6M
    unsigned NextBit = 0;
249
144M
    while (
true144M
) {
250
144M
      Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
251
144M
252
144M
      if ((Piece & (1U << (NumBits-1))) == 0)
253
68.6M
        return Result;
254
144M
255
75.7M
      NextBit += NumBits-1;
256
75.7M
      Piece = Read(NumBits);
257
75.7M
    }
258
157M
  }
259
260
4.52M
  void SkipToFourByteBoundary() {
261
4.52M
    // If word_t is 64-bits and if we've read less than 32 bits, just dump
262
4.52M
    // the bits we have up to the next 32-bit boundary.
263
4.52M
    if (sizeof(word_t) > 4 &&
264
4.52M
        
BitsInCurWord >= 324.52M
) {
265
2.42M
      CurWord >>= BitsInCurWord-32;
266
2.42M
      BitsInCurWord = 32;
267
2.42M
      return;
268
2.42M
    }
269
4.52M
270
2.09M
    BitsInCurWord = 0;
271
2.09M
  }
272
273
  /// Skip to the end of the file.
274
0
  void skipToEnd() { NextChar = BitcodeBytes.size(); }
275
};
276
277
/// When advancing through a bitstream cursor, each advance can discover a few
278
/// different kinds of entries:
279
struct BitstreamEntry {
280
  enum {
281
    Error,    // Malformed bitcode was found.
282
    EndBlock, // We've reached the end of the current block, (or the end of the
283
              // file, which is treated like a series of EndBlock records.
284
    SubBlock, // This is the start of a new subblock of a specific ID.
285
    Record    // This is a record with a specific AbbrevID.
286
  } Kind;
287
288
  unsigned ID;
289
290
5.64k
  static BitstreamEntry getError() {
291
5.64k
    BitstreamEntry E; E.Kind = Error; return E;
292
5.64k
  }
293
294
2.09M
  static BitstreamEntry getEndBlock() {
295
2.09M
    BitstreamEntry E; E.Kind = EndBlock; return E;
296
2.09M
  }
297
298
1.54M
  static BitstreamEntry getSubBlock(unsigned ID) {
299
1.54M
    BitstreamEntry E; E.Kind = SubBlock; E.ID = ID; return E;
300
1.54M
  }
301
302
51.6M
  static BitstreamEntry getRecord(unsigned AbbrevID) {
303
51.6M
    BitstreamEntry E; E.Kind = Record; E.ID = AbbrevID; return E;
304
51.6M
  }
305
};
306
307
/// This represents a position within a bitcode file, implemented on top of a
308
/// SimpleBitstreamCursor.
309
///
310
/// Unlike iterators, BitstreamCursors are heavy-weight objects that should not
311
/// be passed by value.
312
class BitstreamCursor : SimpleBitstreamCursor {
313
  // This is the declared size of code values used for the current block, in
314
  // bits.
315
  unsigned CurCodeSize = 2;
316
317
  /// Abbrevs installed at in this block.
318
  std::vector<std::shared_ptr<BitCodeAbbrev>> CurAbbrevs;
319
320
  struct Block {
321
    unsigned PrevCodeSize;
322
    std::vector<std::shared_ptr<BitCodeAbbrev>> PrevAbbrevs;
323
324
2.12M
    explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
325
  };
326
327
  /// This tracks the codesize of parent blocks.
328
  SmallVector<Block, 8> BlockScope;
329
330
  BitstreamBlockInfo *BlockInfo = nullptr;
331
332
public:
333
  static const size_t MaxChunkSize = sizeof(word_t) * 8;
334
335
38.8k
  BitstreamCursor() = default;
336
  explicit BitstreamCursor(ArrayRef<uint8_t> BitcodeBytes)
337
23.4k
      : SimpleBitstreamCursor(BitcodeBytes) {}
338
  explicit BitstreamCursor(StringRef BitcodeBytes)
339
0
      : SimpleBitstreamCursor(BitcodeBytes) {}
340
  explicit BitstreamCursor(MemoryBufferRef BitcodeBytes)
341
0
      : SimpleBitstreamCursor(BitcodeBytes) {}
342
343
  using SimpleBitstreamCursor::canSkipToPos;
344
  using SimpleBitstreamCursor::AtEndOfStream;
345
  using SimpleBitstreamCursor::getBitcodeBytes;
346
  using SimpleBitstreamCursor::GetCurrentBitNo;
347
  using SimpleBitstreamCursor::getCurrentByteNo;
348
  using SimpleBitstreamCursor::getPointerToByte;
349
  using SimpleBitstreamCursor::JumpToBit;
350
  using SimpleBitstreamCursor::fillCurWord;
351
  using SimpleBitstreamCursor::Read;
352
  using SimpleBitstreamCursor::ReadVBR;
353
  using SimpleBitstreamCursor::ReadVBR64;
354
355
  /// Return the number of bits used to encode an abbrev #.
356
647k
  unsigned getAbbrevIDWidth() const { return CurCodeSize; }
357
358
  /// Flags that modify the behavior of advance().
359
  enum {
360
    /// If this flag is used, the advance() method does not automatically pop
361
    /// the block scope when the end of a block is reached.
362
    AF_DontPopBlockAtEnd = 1,
363
364
    /// If this flag is used, abbrev entries are returned just like normal
365
    /// records.
366
    AF_DontAutoprocessAbbrevs = 2
367
  };
368
369
  /// Advance the current bitstream, returning the next entry in the stream.
370
55.3M
  BitstreamEntry advance(unsigned Flags = 0) {
371
55.7M
    while (
true55.7M
) {
372
55.7M
      if (AtEndOfStream())
373
5.63k
        return BitstreamEntry::getError();
374
55.7M
375
55.7M
      unsigned Code = ReadCode();
376
55.7M
      if (
Code == bitc::END_BLOCK55.7M
) {
377
2.09M
        // Pop the end of the block unless Flags tells us not to.
378
2.09M
        if (
!(Flags & AF_DontPopBlockAtEnd) && 2.09M
ReadBlockEnd()2.09M
)
379
6
          return BitstreamEntry::getError();
380
2.09M
        return BitstreamEntry::getEndBlock();
381
2.09M
      }
382
55.7M
383
53.6M
      
if (53.6M
Code == bitc::ENTER_SUBBLOCK53.6M
)
384
1.54M
        return BitstreamEntry::getSubBlock(ReadSubBlockID());
385
53.6M
386
52.0M
      
if (52.0M
Code == bitc::DEFINE_ABBREV &&
387
52.0M
          
!(Flags & AF_DontAutoprocessAbbrevs)578k
) {
388
393k
        // We read and accumulate abbrev's, the client can't do anything with
389
393k
        // them anyway.
390
393k
        ReadAbbrevRecord();
391
393k
        continue;
392
393k
      }
393
52.0M
394
51.6M
      return BitstreamEntry::getRecord(Code);
395
55.7M
    }
396
55.3M
  }
397
398
  /// This is a convenience function for clients that don't expect any
399
  /// subblocks. This just skips over them automatically.
400
30.4M
  BitstreamEntry advanceSkippingSubblocks(unsigned Flags = 0) {
401
30.4M
    while (
true30.4M
) {
402
30.4M
      // If we found a normal entry, return it.
403
30.4M
      BitstreamEntry Entry = advance(Flags);
404
30.4M
      if (Entry.Kind != BitstreamEntry::SubBlock)
405
30.4M
        return Entry;
406
30.4M
407
30.4M
      // If we found a sub-block, just skip over it and check the next entry.
408
2.31k
      
if (2.31k
SkipBlock()2.31k
)
409
0
        return BitstreamEntry::getError();
410
30.4M
    }
411
30.4M
  }
412
413
56.0M
  unsigned ReadCode() {
414
56.0M
    return Read(CurCodeSize);
415
56.0M
  }
416
417
  // Block header:
418
  //    [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
419
420
  /// Having read the ENTER_SUBBLOCK code, read the BlockID for the block.
421
1.54M
  unsigned ReadSubBlockID() {
422
1.54M
    return ReadVBR(bitc::BlockIDWidth);
423
1.54M
  }
424
425
  /// Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body
426
  /// of this block. If the block record is malformed, return true.
427
119k
  bool SkipBlock() {
428
119k
    // Read and ignore the codelen value.  Since we are skipping this block, we
429
119k
    // don't care what code widths are used inside of it.
430
119k
    ReadVBR(bitc::CodeLenWidth);
431
119k
    SkipToFourByteBoundary();
432
119k
    unsigned NumFourBytes = Read(bitc::BlockSizeWidth);
433
119k
434
119k
    // Check that the block wasn't partially defined, and that the offset isn't
435
119k
    // bogus.
436
119k
    size_t SkipTo = GetCurrentBitNo() + NumFourBytes*4*8;
437
119k
    if (
AtEndOfStream() || 119k
!canSkipToPos(SkipTo/8)119k
)
438
6
      return true;
439
119k
440
119k
    JumpToBit(SkipTo);
441
119k
    return false;
442
119k
  }
443
444
  /// Having read the ENTER_SUBBLOCK abbrevid, enter the block, and return true
445
  /// if the block has an error.
446
  bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = nullptr);
447
448
2.09M
  bool ReadBlockEnd() {
449
2.09M
    if (
BlockScope.empty()2.09M
)
return true6
;
450
2.09M
451
2.09M
    // Block tail:
452
2.09M
    //    [END_BLOCK, <align4bytes>]
453
2.09M
    SkipToFourByteBoundary();
454
2.09M
455
2.09M
    popBlockScope();
456
2.09M
    return false;
457
2.09M
  }
458
459
private:
460
2.09M
  void popBlockScope() {
461
2.09M
    CurCodeSize = BlockScope.back().PrevCodeSize;
462
2.09M
463
2.09M
    CurAbbrevs = std::move(BlockScope.back().PrevAbbrevs);
464
2.09M
    BlockScope.pop_back();
465
2.09M
  }
466
467
  //===--------------------------------------------------------------------===//
468
  // Record Processing
469
  //===--------------------------------------------------------------------===//
470
471
public:
472
  /// Return the abbreviation for the specified AbbrevId.
473
34.4M
  const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
474
34.4M
    unsigned AbbrevNo = AbbrevID - bitc::FIRST_APPLICATION_ABBREV;
475
34.4M
    if (AbbrevNo >= CurAbbrevs.size())
476
0
      report_fatal_error("Invalid abbrev number");
477
34.4M
    return CurAbbrevs[AbbrevNo].get();
478
34.4M
  }
479
480
  /// Read the current record and discard it, returning the code for the record.
481
  unsigned skipRecord(unsigned AbbrevID);
482
483
  unsigned readRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
484
                      StringRef *Blob = nullptr);
485
486
  //===--------------------------------------------------------------------===//
487
  // Abbrev Processing
488
  //===--------------------------------------------------------------------===//
489
  void ReadAbbrevRecord();
490
491
  /// Read and return a block info block from the bitstream. If an error was
492
  /// encountered, return None.
493
  ///
494
  /// \param ReadBlockInfoNames Whether to read block/record name information in
495
  /// the BlockInfo block. Only llvm-bcanalyzer uses this.
496
  Optional<BitstreamBlockInfo>
497
  ReadBlockInfoBlock(bool ReadBlockInfoNames = false);
498
499
  /// Set the block info to be used by this BitstreamCursor to interpret
500
  /// abbreviated records.
501
11.5k
  void setBlockInfo(BitstreamBlockInfo *BI) { BlockInfo = BI; }
502
};
503
504
} // end llvm namespace
505
506
#endif // LLVM_BITCODE_BITSTREAMREADER_H