1 //===- BitstreamWriter.h - Low-level bitstream writer interface -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This header defines the BitstreamWriter class. This class can be used to
11 // write an arbitrary bitstream, regardless of its contents.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_BITCODE_BITSTREAMWRITER_H
16 #define LLVM_BITCODE_BITSTREAMWRITER_H
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/Bitcode/BitCodes.h"
23 #include "llvm/Support/Endian.h"
28 class BitstreamWriter {
29 SmallVectorImpl<char> &Out;
31 /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
34 /// CurValue - The current value. Only bits < CurBit are valid.
37 /// CurCodeSize - This is the declared size of code values used for the
38 /// current block, in bits.
41 /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
42 /// selected BLOCK ID.
43 unsigned BlockInfoCurBID;
45 /// CurAbbrevs - Abbrevs installed at in this block.
46 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> CurAbbrevs;
49 unsigned PrevCodeSize;
51 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> PrevAbbrevs;
52 Block(unsigned PCS, size_t SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
55 /// BlockScope - This tracks the current blocks that we have entered.
56 std::vector<Block> BlockScope;
58 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
59 /// These describe abbreviations that all blocks of the specified ID inherit.
62 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> Abbrevs;
64 std::vector<BlockInfo> BlockInfoRecords;
66 void WriteByte(unsigned char Value) {
70 void WriteWord(unsigned Value) {
71 Value = support::endian::byte_swap<uint32_t, support::little>(Value);
72 Out.append(reinterpret_cast<const char *>(&Value),
73 reinterpret_cast<const char *>(&Value + 1));
76 size_t GetBufferOffset() const { return Out.size(); }
78 size_t GetWordIndex() const {
79 size_t Offset = GetBufferOffset();
80 assert((Offset & 3) == 0 && "Not 32-bit aligned");
85 explicit BitstreamWriter(SmallVectorImpl<char> &O)
86 : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
89 assert(CurBit == 0 && "Unflushed data remaining");
90 assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
93 /// \brief Retrieve the current position in the stream, in bits.
94 uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; }
96 /// \brief Retrieve the number of bits currently used to encode an abbrev ID.
97 unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
99 //===--------------------------------------------------------------------===//
100 // Basic Primitives for emitting bits to the stream.
101 //===--------------------------------------------------------------------===//
103 /// Backpatch a 32-bit word in the output at the given bit offset
104 /// with the specified value.
105 void BackpatchWord(uint64_t BitNo, unsigned NewWord) {
106 using namespace llvm::support;
107 unsigned ByteNo = BitNo / 8;
108 assert((!endian::readAtBitAlignment<uint32_t, little, unaligned>(
109 &Out[ByteNo], BitNo & 7)) &&
110 "Expected to be patching over 0-value placeholders");
111 endian::writeAtBitAlignment<uint32_t, little, unaligned>(
112 &Out[ByteNo], NewWord, BitNo & 7);
115 void Emit(uint32_t Val, unsigned NumBits) {
116 assert(NumBits && NumBits <= 32 && "Invalid value size!");
117 assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
118 CurValue |= Val << CurBit;
119 if (CurBit + NumBits < 32) {
124 // Add the current word.
128 CurValue = Val >> (32-CurBit);
131 CurBit = (CurBit+NumBits) & 31;
134 void Emit64(uint64_t Val, unsigned NumBits) {
136 Emit((uint32_t)Val, NumBits);
138 Emit((uint32_t)Val, 32);
139 Emit((uint32_t)(Val >> 32), NumBits-32);
151 void EmitVBR(uint32_t Val, unsigned NumBits) {
152 assert(NumBits <= 32 && "Too many bits to emit!");
153 uint32_t Threshold = 1U << (NumBits-1);
155 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
156 while (Val >= Threshold) {
157 Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
164 void EmitVBR64(uint64_t Val, unsigned NumBits) {
165 assert(NumBits <= 32 && "Too many bits to emit!");
166 if ((uint32_t)Val == Val)
167 return EmitVBR((uint32_t)Val, NumBits);
169 uint32_t Threshold = 1U << (NumBits-1);
171 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
172 while (Val >= Threshold) {
173 Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
174 (1 << (NumBits-1)), NumBits);
178 Emit((uint32_t)Val, NumBits);
181 /// EmitCode - Emit the specified code.
182 void EmitCode(unsigned Val) {
183 Emit(Val, CurCodeSize);
186 //===--------------------------------------------------------------------===//
187 // Block Manipulation
188 //===--------------------------------------------------------------------===//
190 /// getBlockInfo - If there is block info for the specified ID, return it,
191 /// otherwise return null.
192 BlockInfo *getBlockInfo(unsigned BlockID) {
193 // Common case, the most recent entry matches BlockID.
194 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
195 return &BlockInfoRecords.back();
197 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
199 if (BlockInfoRecords[i].BlockID == BlockID)
200 return &BlockInfoRecords[i];
204 void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
206 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
207 EmitCode(bitc::ENTER_SUBBLOCK);
208 EmitVBR(BlockID, bitc::BlockIDWidth);
209 EmitVBR(CodeLen, bitc::CodeLenWidth);
212 size_t BlockSizeWordIndex = GetWordIndex();
213 unsigned OldCodeSize = CurCodeSize;
215 // Emit a placeholder, which will be replaced when the block is popped.
216 Emit(0, bitc::BlockSizeWidth);
218 CurCodeSize = CodeLen;
220 // Push the outer block's abbrev set onto the stack, start out with an
222 BlockScope.emplace_back(OldCodeSize, BlockSizeWordIndex);
223 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
225 // If there is a blockinfo for this BlockID, add all the predefined abbrevs
226 // to the abbrev list.
227 if (BlockInfo *Info = getBlockInfo(BlockID)) {
228 CurAbbrevs.insert(CurAbbrevs.end(), Info->Abbrevs.begin(),
229 Info->Abbrevs.end());
234 assert(!BlockScope.empty() && "Block scope imbalance!");
235 const Block &B = BlockScope.back();
238 // [END_BLOCK, <align4bytes>]
239 EmitCode(bitc::END_BLOCK);
242 // Compute the size of the block, in words, not counting the size field.
243 size_t SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
244 uint64_t BitNo = uint64_t(B.StartSizeWord) * 32;
246 // Update the block size field in the header of this sub-block.
247 BackpatchWord(BitNo, SizeInWords);
249 // Restore the inner block's code size and abbrev table.
250 CurCodeSize = B.PrevCodeSize;
251 CurAbbrevs = std::move(B.PrevAbbrevs);
252 BlockScope.pop_back();
255 //===--------------------------------------------------------------------===//
257 //===--------------------------------------------------------------------===//
260 /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
261 /// record. This is a no-op, since the abbrev specifies the literal to use.
262 template<typename uintty>
263 void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
264 assert(Op.isLiteral() && "Not a literal");
265 // If the abbrev specifies the literal value to use, don't emit
267 assert(V == Op.getLiteralValue() &&
268 "Invalid abbrev for record!");
271 /// EmitAbbreviatedField - Emit a single scalar field value with the specified
273 template<typename uintty>
274 void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
275 assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
277 // Encode the value as we are commanded.
278 switch (Op.getEncoding()) {
279 default: llvm_unreachable("Unknown encoding!");
280 case BitCodeAbbrevOp::Fixed:
281 if (Op.getEncodingData())
282 Emit((unsigned)V, (unsigned)Op.getEncodingData());
284 case BitCodeAbbrevOp::VBR:
285 if (Op.getEncodingData())
286 EmitVBR64(V, (unsigned)Op.getEncodingData());
288 case BitCodeAbbrevOp::Char6:
289 Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
294 /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
295 /// emission code. If BlobData is non-null, then it specifies an array of
296 /// data that should be emitted as part of the Blob or Array operand that is
297 /// known to exist at the end of the record. If Code is specified, then
298 /// it is the record code to emit before the Vals, which must not contain
300 template <typename uintty>
301 void EmitRecordWithAbbrevImpl(unsigned Abbrev, ArrayRef<uintty> Vals,
302 StringRef Blob, Optional<unsigned> Code) {
303 const char *BlobData = Blob.data();
304 unsigned BlobLen = (unsigned) Blob.size();
305 unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
306 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
307 const BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo].get();
311 unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
313 assert(e && "Expected non-empty abbreviation");
314 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i++);
317 EmitAbbreviatedLiteral(Op, Code.getValue());
319 assert(Op.getEncoding() != BitCodeAbbrevOp::Array &&
320 Op.getEncoding() != BitCodeAbbrevOp::Blob &&
321 "Expected literal or scalar");
322 EmitAbbreviatedField(Op, Code.getValue());
326 unsigned RecordIdx = 0;
327 for (; i != e; ++i) {
328 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
329 if (Op.isLiteral()) {
330 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
331 EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
333 } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
335 assert(i + 2 == e && "array op not second to last?");
336 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
338 // If this record has blob data, emit it, otherwise we must have record
339 // entries to encode this way.
341 assert(RecordIdx == Vals.size() &&
342 "Blob data and record entries specified for array!");
343 // Emit a vbr6 to indicate the number of elements present.
344 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
347 for (unsigned i = 0; i != BlobLen; ++i)
348 EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
350 // Know that blob data is consumed for assertion below.
353 // Emit a vbr6 to indicate the number of elements present.
354 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
357 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
358 EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
360 } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
361 // If this record has blob data, emit it, otherwise we must have record
362 // entries to encode this way.
364 // Emit a vbr6 to indicate the number of elements present.
366 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
367 assert(RecordIdx == Vals.size() &&
368 "Blob data and record entries specified for blob operand!");
370 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
373 // Flush to a 32-bit alignment boundary.
376 // Emit each field as a literal byte.
378 for (unsigned i = 0; i != BlobLen; ++i)
379 WriteByte((unsigned char)BlobData[i]);
381 // Know that blob data is consumed for assertion below.
384 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx) {
385 assert(isUInt<8>(Vals[RecordIdx]) &&
386 "Value too large to emit as blob");
387 WriteByte((unsigned char)Vals[RecordIdx]);
391 // Align end to 32-bits.
392 while (GetBufferOffset() & 3)
394 } else { // Single scalar field.
395 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
396 EmitAbbreviatedField(Op, Vals[RecordIdx]);
400 assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
401 assert(BlobData == nullptr &&
402 "Blob data specified for record that doesn't use it!");
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) {
412 // If we don't have an abbrev to use, emit this in its fully unabbreviated
414 auto Count = static_cast<uint32_t>(makeArrayRef(Vals).size());
415 EmitCode(bitc::UNABBREV_RECORD);
418 for (unsigned i = 0, e = Count; i != e; ++i)
419 EmitVBR64(Vals[i], 6);
423 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), StringRef(), Code);
426 /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
427 /// Unlike EmitRecord, the code for the record should be included in Vals as
429 template <typename Container>
430 void EmitRecordWithAbbrev(unsigned Abbrev, const Container &Vals) {
431 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), StringRef(), None);
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
439 template <typename Container>
440 void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
442 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Blob, None);
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);
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,
456 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Array, None);
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);
465 //===--------------------------------------------------------------------===//
467 //===--------------------------------------------------------------------===//
470 // Emit the abbreviation as a DEFINE_ABBREV record.
471 void EncodeAbbrev(BitCodeAbbrev *Abbv) {
472 EmitCode(bitc::DEFINE_ABBREV);
473 EmitVBR(Abbv->getNumOperandInfos(), 5);
474 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
476 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
477 Emit(Op.isLiteral(), 1);
478 if (Op.isLiteral()) {
479 EmitVBR64(Op.getLiteralValue(), 8);
481 Emit(Op.getEncoding(), 3);
482 if (Op.hasEncodingData())
483 EmitVBR64(Op.getEncodingData(), 5);
489 /// EmitAbbrev - This emits an abbreviation to the stream. Note that this
490 /// method takes ownership of the specified abbrev.
491 unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
492 // Emit the abbreviation as a record.
494 CurAbbrevs.push_back(Abbv);
495 return static_cast<unsigned>(CurAbbrevs.size())-1 +
496 bitc::FIRST_APPLICATION_ABBREV;
499 //===--------------------------------------------------------------------===//
500 // BlockInfo Block Emission
501 //===--------------------------------------------------------------------===//
503 /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
504 void EnterBlockInfoBlock(unsigned CodeWidth) {
505 EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
506 BlockInfoCurBID = ~0U;
509 /// SwitchToBlockID - If we aren't already talking about the specified block
510 /// ID, emit a BLOCKINFO_CODE_SETBID record.
511 void SwitchToBlockID(unsigned BlockID) {
512 if (BlockInfoCurBID == BlockID) return;
513 SmallVector<unsigned, 2> V;
514 V.push_back(BlockID);
515 EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
516 BlockInfoCurBID = BlockID;
519 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
520 if (BlockInfo *BI = getBlockInfo(BlockID))
523 // Otherwise, add a new record.
524 BlockInfoRecords.emplace_back();
525 BlockInfoRecords.back().BlockID = BlockID;
526 return BlockInfoRecords.back();
531 /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
533 unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
534 SwitchToBlockID(BlockID);
537 // Add the abbrev to the specified block record.
538 BlockInfo &Info = getOrCreateBlockInfo(BlockID);
539 Info.Abbrevs.push_back(Abbv);
541 return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
546 } // End llvm namespace