1//===- BitstreamWriter.h - Low-level bitstream writer interface -*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This header defines the BitstreamWriter class.  This class can be used to
10// write an arbitrary bitstream, regardless of its contents.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_BITSTREAM_BITSTREAMWRITER_H
15#define LLVM_BITSTREAM_BITSTREAMWRITER_H
16
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/Optional.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/Bitstream/BitCodes.h"
22#include "llvm/Support/Endian.h"
23#include <vector>
24
25namespace llvm {
26
27class BitstreamWriter {
28  SmallVectorImpl<char> &Out;
29
30  /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
31  unsigned CurBit;
32
33  /// CurValue - The current value.  Only bits < CurBit are valid.
34  uint32_t CurValue;
35
36  /// CurCodeSize - This is the declared size of code values used for the
37  /// current block, in bits.
38  unsigned CurCodeSize;
39
40  /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
41  /// selected BLOCK ID.
42  unsigned BlockInfoCurBID;
43
44  /// CurAbbrevs - Abbrevs installed at in this block.
45  std::vector<std::shared_ptr<BitCodeAbbrev>> CurAbbrevs;
46
47  struct Block {
48    unsigned PrevCodeSize;
49    size_t StartSizeWord;
50    std::vector<std::shared_ptr<BitCodeAbbrev>> PrevAbbrevs;
51    Block(unsigned PCS, size_t SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
52  };
53
54  /// BlockScope - This tracks the current blocks that we have entered.
55  std::vector<Block> BlockScope;
56
57  /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
58  /// These describe abbreviations that all blocks of the specified ID inherit.
59  struct BlockInfo {
60    unsigned BlockID;
61    std::vector<std::shared_ptr<BitCodeAbbrev>> Abbrevs;
62  };
63  std::vector<BlockInfo> BlockInfoRecords;
64
65  void WriteByte(unsigned char Value) {
66    Out.push_back(Value);
67  }
68
69  void WriteWord(unsigned Value) {
70    Value = support::endian::byte_swap<uint32_t, support::little>(Value);
71    Out.append(reinterpret_cast<const char *>(&Value),
72               reinterpret_cast<const char *>(&Value + 1));
73  }
74
75  size_t GetBufferOffset() const { return Out.size(); }
76
77  size_t GetWordIndex() const {
78    size_t Offset = GetBufferOffset();
79    assert((Offset & 3) == 0 && "Not 32-bit aligned");
80    return Offset / 4;
81  }
82
83public:
84  explicit BitstreamWriter(SmallVectorImpl<char> &O)
85    : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
86
87  ~BitstreamWriter() {
88    assert(CurBit == 0 && "Unflushed data remaining");
89    assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
90  }
91
92  /// Retrieve the current position in the stream, in bits.
93  uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; }
94
95  /// Retrieve the number of bits currently used to encode an abbrev ID.
96  unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
97
98  //===--------------------------------------------------------------------===//
99  // Basic Primitives for emitting bits to the stream.
100  //===--------------------------------------------------------------------===//
101
102  /// Backpatch a 32-bit word in the output at the given bit offset
103  /// with the specified value.
104  void BackpatchWord(uint64_t BitNo, unsigned NewWord) {
105    using namespace llvm::support;
106    unsigned ByteNo = BitNo / 8;
107    assert((!endian::readAtBitAlignment<uint32_t, little, unaligned>(
108               &Out[ByteNo], BitNo & 7)) &&
109           "Expected to be patching over 0-value placeholders");
110    endian::writeAtBitAlignment<uint32_t, little, unaligned>(
111        &Out[ByteNo], NewWord, BitNo & 7);
112  }
113
114  void BackpatchWord64(uint64_t BitNo, uint64_t Val) {
115    BackpatchWord(BitNo, (uint32_t)Val);
116    BackpatchWord(BitNo + 32, (uint32_t)(Val >> 32));
117  }
118
119  void Emit(uint32_t Val, unsigned NumBits) {
120    assert(NumBits && NumBits <= 32 && "Invalid value size!");
121    assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
122    CurValue |= Val << CurBit;
123    if (CurBit + NumBits < 32) {
124      CurBit += NumBits;
125      return;
126    }
127
128    // Add the current word.
129    WriteWord(CurValue);
130
131    if (CurBit)
132      CurValue = Val >> (32-CurBit);
133    else
134      CurValue = 0;
135    CurBit = (CurBit+NumBits) & 31;
136  }
137
138  void FlushToWord() {
139    if (CurBit) {
140      WriteWord(CurValue);
141      CurBit = 0;
142      CurValue = 0;
143    }
144  }
145
146  void EmitVBR(uint32_t Val, unsigned NumBits) {
147    assert(NumBits <= 32 && "Too many bits to emit!");
148    uint32_t Threshold = 1U << (NumBits-1);
149
150    // Emit the bits with VBR encoding, NumBits-1 bits at a time.
151    while (Val >= Threshold) {
152      Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
153      Val >>= NumBits-1;
154    }
155
156    Emit(Val, NumBits);
157  }
158
159  void EmitVBR64(uint64_t Val, unsigned NumBits) {
160    assert(NumBits <= 32 && "Too many bits to emit!");
161    if ((uint32_t)Val == Val)
162      return EmitVBR((uint32_t)Val, NumBits);
163
164    uint32_t Threshold = 1U << (NumBits-1);
165
166    // Emit the bits with VBR encoding, NumBits-1 bits at a time.
167    while (Val >= Threshold) {
168      Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
169           (1 << (NumBits-1)), NumBits);
170      Val >>= NumBits-1;
171    }
172
173    Emit((uint32_t)Val, NumBits);
174  }
175
176  /// EmitCode - Emit the specified code.
177  void EmitCode(unsigned Val) {
178    Emit(Val, CurCodeSize);
179  }
180
181  //===--------------------------------------------------------------------===//
182  // Block Manipulation
183  //===--------------------------------------------------------------------===//
184
185  /// getBlockInfo - If there is block info for the specified ID, return it,
186  /// otherwise return null.
187  BlockInfo *getBlockInfo(unsigned BlockID) {
188    // Common case, the most recent entry matches BlockID.
189    if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
190      return &BlockInfoRecords.back();
191
192    for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
193         i != e; ++i)
194      if (BlockInfoRecords[i].BlockID == BlockID)
195        return &BlockInfoRecords[i];
196    return nullptr;
197  }
198
199  void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
200    // Block header:
201    //    [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
202    EmitCode(bitc::ENTER_SUBBLOCK);
203    EmitVBR(BlockID, bitc::BlockIDWidth);
204    EmitVBR(CodeLen, bitc::CodeLenWidth);
205    FlushToWord();
206
207    size_t BlockSizeWordIndex = GetWordIndex();
208    unsigned OldCodeSize = CurCodeSize;
209
210    // Emit a placeholder, which will be replaced when the block is popped.
211    Emit(0, bitc::BlockSizeWidth);
212
213    CurCodeSize = CodeLen;
214
215    // Push the outer block's abbrev set onto the stack, start out with an
216    // empty abbrev set.
217    BlockScope.emplace_back(OldCodeSize, BlockSizeWordIndex);
218    BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
219
220    // If there is a blockinfo for this BlockID, add all the predefined abbrevs
221    // to the abbrev list.
222    if (BlockInfo *Info = getBlockInfo(BlockID)) {
223      CurAbbrevs.insert(CurAbbrevs.end(), Info->Abbrevs.begin(),
224                        Info->Abbrevs.end());
225    }
226  }
227
228  void ExitBlock() {
229    assert(!BlockScope.empty() && "Block scope imbalance!");
230    const Block &B = BlockScope.back();
231
232    // Block tail:
233    //    [END_BLOCK, <align4bytes>]
234    EmitCode(bitc::END_BLOCK);
235    FlushToWord();
236
237    // Compute the size of the block, in words, not counting the size field.
238    size_t SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
239    uint64_t BitNo = uint64_t(B.StartSizeWord) * 32;
240
241    // Update the block size field in the header of this sub-block.
242    BackpatchWord(BitNo, SizeInWords);
243
244    // Restore the inner block's code size and abbrev table.
245    CurCodeSize = B.PrevCodeSize;
246    CurAbbrevs = std::move(B.PrevAbbrevs);
247    BlockScope.pop_back();
248  }
249
250  //===--------------------------------------------------------------------===//
251  // Record Emission
252  //===--------------------------------------------------------------------===//
253
254private:
255  /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
256  /// record.  This is a no-op, since the abbrev specifies the literal to use.
257  template<typename uintty>
258  void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
259    assert(Op.isLiteral() && "Not a literal");
260    // If the abbrev specifies the literal value to use, don't emit
261    // anything.
262    assert(V == Op.getLiteralValue() &&
263           "Invalid abbrev for record!");
264  }
265
266  /// EmitAbbreviatedField - Emit a single scalar field value with the specified
267  /// encoding.
268  template<typename uintty>
269  void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
270    assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
271
272    // Encode the value as we are commanded.
273    switch (Op.getEncoding()) {
274    default: llvm_unreachable("Unknown encoding!");
275    case BitCodeAbbrevOp::Fixed:
276      if (Op.getEncodingData())
277        Emit((unsigned)V, (unsigned)Op.getEncodingData());
278      break;
279    case BitCodeAbbrevOp::VBR:
280      if (Op.getEncodingData())
281        EmitVBR64(V, (unsigned)Op.getEncodingData());
282      break;
283    case BitCodeAbbrevOp::Char6:
284      Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
285      break;
286    }
287  }
288
289  /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
290  /// emission code.  If BlobData is non-null, then it specifies an array of
291  /// data that should be emitted as part of the Blob or Array operand that is
292  /// known to exist at the end of the record. If Code is specified, then
293  /// it is the record code to emit before the Vals, which must not contain
294  /// the code.
295  template <typename uintty>
296  void EmitRecordWithAbbrevImpl(unsigned Abbrev, ArrayRef<uintty> Vals,
297                                StringRef Blob, Optional<unsigned> Code) {
298    const char *BlobData = Blob.data();
299    unsigned BlobLen = (unsigned) Blob.size();
300    unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
301    assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
302    const BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo].get();
303
304    EmitCode(Abbrev);
305
306    unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
307    if (Code) {
308      assert(e && "Expected non-empty abbreviation");
309      const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i++);
310
311      if (Op.isLiteral())
312        EmitAbbreviatedLiteral(Op, Code.getValue());
313      else {
314        assert(Op.getEncoding() != BitCodeAbbrevOp::Array &&
315               Op.getEncoding() != BitCodeAbbrevOp::Blob &&
316               "Expected literal or scalar");
317        EmitAbbreviatedField(Op, Code.getValue());
318      }
319    }
320
321    unsigned RecordIdx = 0;
322    for (; i != e; ++i) {
323      const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
324      if (Op.isLiteral()) {
325        assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
326        EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
327        ++RecordIdx;
328      } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
329        // Array case.
330        assert(i + 2 == e && "array op not second to last?");
331        const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
332
333        // If this record has blob data, emit it, otherwise we must have record
334        // entries to encode this way.
335        if (BlobData) {
336          assert(RecordIdx == Vals.size() &&
337                 "Blob data and record entries specified for array!");
338          // Emit a vbr6 to indicate the number of elements present.
339          EmitVBR(static_cast<uint32_t>(BlobLen), 6);
340
341          // Emit each field.
342          for (unsigned i = 0; i != BlobLen; ++i)
343            EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
344
345          // Know that blob data is consumed for assertion below.
346          BlobData = nullptr;
347        } else {
348          // Emit a vbr6 to indicate the number of elements present.
349          EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
350
351          // Emit each field.
352          for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
353            EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
354        }
355      } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
356        // If this record has blob data, emit it, otherwise we must have record
357        // entries to encode this way.
358
359        if (BlobData) {
360          assert(RecordIdx == Vals.size() &&
361                 "Blob data and record entries specified for blob operand!");
362
363          assert(Blob.data() == BlobData && "BlobData got moved");
364          assert(Blob.size() == BlobLen && "BlobLen got changed");
365          emitBlob(Blob);
366          BlobData = nullptr;
367        } else {
368          emitBlob(Vals.slice(RecordIdx));
369        }
370      } else {  // Single scalar field.
371        assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
372        EmitAbbreviatedField(Op, Vals[RecordIdx]);
373        ++RecordIdx;
374      }
375    }
376    assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
377    assert(BlobData == nullptr &&
378           "Blob data specified for record that doesn't use it!");
379  }
380
381public:
382  /// Emit a blob, including flushing before and tail-padding.
383  template <class UIntTy>
384  void emitBlob(ArrayRef<UIntTy> Bytes, bool ShouldEmitSize = true) {
385    // Emit a vbr6 to indicate the number of elements present.
386    if (ShouldEmitSize)
387      EmitVBR(static_cast<uint32_t>(Bytes.size()), 6);
388
389    // Flush to a 32-bit alignment boundary.
390    FlushToWord();
391
392    // Emit literal bytes.
393    for (const auto &B : Bytes) {
394      assert(isUInt<8>(B) && "Value too large to emit as byte");
395      WriteByte((unsigned char)B);
396    }
397
398    // Align end to 32-bits.
399    while (GetBufferOffset() & 3)
400      WriteByte(0);
401  }
402  void emitBlob(StringRef Bytes, bool ShouldEmitSize = true) {
403    emitBlob(makeArrayRef((const uint8_t *)Bytes.data(), Bytes.size()),
404             ShouldEmitSize);
405  }
406
407  /// EmitRecord - Emit the specified record to the stream, using an abbrev if
408  /// we have one to compress the output.
409  template <typename Container>
410  void EmitRecord(unsigned Code, const Container &Vals, unsigned Abbrev = 0) {
411    if (!Abbrev) {
412      // If we don't have an abbrev to use, emit this in its fully unabbreviated
413      // form.
414      auto Count = static_cast<uint32_t>(makeArrayRef(Vals).size());
415      EmitCode(bitc::UNABBREV_RECORD);
416      EmitVBR(Code, 6);
417      EmitVBR(Count, 6);
418      for (unsigned i = 0, e = Count; i != e; ++i)
419        EmitVBR64(Vals[i], 6);
420      return;
421    }
422
423    EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), StringRef(), Code);
424  }
425
426  /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
427  /// Unlike EmitRecord, the code for the record should be included in Vals as
428  /// the first entry.
429  template <typename Container>
430  void EmitRecordWithAbbrev(unsigned Abbrev, const Container &Vals) {
431    EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), StringRef(), None);
432  }
433
434  /// EmitRecordWithBlob - Emit the specified record to the stream, using an
435  /// abbrev that includes a blob at the end.  The blob data to emit is
436  /// specified by the pointer and length specified at the end.  In contrast to
437  /// EmitRecord, this routine expects that the first entry in Vals is the code
438  /// of the record.
439  template <typename Container>
440  void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
441                          StringRef Blob) {
442    EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Blob, None);
443  }
444  template <typename Container>
445  void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
446                          const char *BlobData, unsigned BlobLen) {
447    return EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals),
448                                    StringRef(BlobData, BlobLen), None);
449  }
450
451  /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
452  /// that end with an array.
453  template <typename Container>
454  void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
455                           StringRef Array) {
456    EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Array, None);
457  }
458  template <typename Container>
459  void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
460                           const char *ArrayData, unsigned ArrayLen) {
461    return EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals),
462                                    StringRef(ArrayData, ArrayLen), None);
463  }
464
465  //===--------------------------------------------------------------------===//
466  // Abbrev Emission
467  //===--------------------------------------------------------------------===//
468
469private:
470  // Emit the abbreviation as a DEFINE_ABBREV record.
471  void EncodeAbbrev(const BitCodeAbbrev &Abbv) {
472    EmitCode(bitc::DEFINE_ABBREV);
473    EmitVBR(Abbv.getNumOperandInfos(), 5);
474    for (unsigned i = 0, e = static_cast<unsigned>(Abbv.getNumOperandInfos());
475         i != e; ++i) {
476      const BitCodeAbbrevOp &Op = Abbv.getOperandInfo(i);
477      Emit(Op.isLiteral(), 1);
478      if (Op.isLiteral()) {
479        EmitVBR64(Op.getLiteralValue(), 8);
480      } else {
481        Emit(Op.getEncoding(), 3);
482        if (Op.hasEncodingData())
483          EmitVBR64(Op.getEncodingData(), 5);
484      }
485    }
486  }
487public:
488
489  /// Emits the abbreviation \p Abbv to the stream.
490  unsigned EmitAbbrev(std::shared_ptr<BitCodeAbbrev> Abbv) {
491    EncodeAbbrev(*Abbv);
492    CurAbbrevs.push_back(std::move(Abbv));
493    return static_cast<unsigned>(CurAbbrevs.size())-1 +
494      bitc::FIRST_APPLICATION_ABBREV;
495  }
496
497  //===--------------------------------------------------------------------===//
498  // BlockInfo Block Emission
499  //===--------------------------------------------------------------------===//
500
501  /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
502  void EnterBlockInfoBlock() {
503    EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, 2);
504    BlockInfoCurBID = ~0U;
505    BlockInfoRecords.clear();
506  }
507private:
508  /// SwitchToBlockID - If we aren't already talking about the specified block
509  /// ID, emit a BLOCKINFO_CODE_SETBID record.
510  void SwitchToBlockID(unsigned BlockID) {
511    if (BlockInfoCurBID == BlockID) return;
512    SmallVector<unsigned, 2> V;
513    V.push_back(BlockID);
514    EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
515    BlockInfoCurBID = BlockID;
516  }
517
518  BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
519    if (BlockInfo *BI = getBlockInfo(BlockID))
520      return *BI;
521
522    // Otherwise, add a new record.
523    BlockInfoRecords.emplace_back();
524    BlockInfoRecords.back().BlockID = BlockID;
525    return BlockInfoRecords.back();
526  }
527
528public:
529
530  /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
531  /// BlockID.
532  unsigned EmitBlockInfoAbbrev(unsigned BlockID, std::shared_ptr<BitCodeAbbrev> Abbv) {
533    SwitchToBlockID(BlockID);
534    EncodeAbbrev(*Abbv);
535
536    // Add the abbrev to the specified block record.
537    BlockInfo &Info = getOrCreateBlockInfo(BlockID);
538    Info.Abbrevs.push_back(std::move(Abbv));
539
540    return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
541  }
542};
543
544
545} // End llvm namespace
546
547#endif
548