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;
50 unsigned StartSizeWord;
51 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> PrevAbbrevs;
52 Block(unsigned PCS, unsigned 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 unsigned GetBufferOffset() const {
80 unsigned GetWordIndex() const {
81 unsigned Offset = GetBufferOffset();
82 assert((Offset & 3) == 0 && "Not 32-bit aligned");
87 explicit BitstreamWriter(SmallVectorImpl<char> &O)
88 : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
91 assert(CurBit == 0 && "Unflushed data remaining");
92 assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
95 /// \brief Retrieve the current position in the stream, in bits.
96 uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; }
98 //===--------------------------------------------------------------------===//
99 // Basic Primitives for emitting bits to the stream.
100 //===--------------------------------------------------------------------===//
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 unsigned ByteNo = BitNo / 8;
106 if ((BitNo & 7) == 0) {
107 // Already 8-bit aligned
108 support::endian::write32le(&Out[ByteNo], NewWord);
110 uint64_t CurDWord = support::endian::read64le(&Out[ByteNo]);
111 unsigned StartBit = BitNo & 7;
112 // Currently expect to backpatch 0-value placeholders.
113 assert(((CurDWord >> StartBit) & 0xffffffff) == 0);
114 CurDWord |= NewWord << StartBit;
115 support::endian::write64le(&Out[ByteNo], CurDWord);
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) {
128 // Add the current word.
132 CurValue = Val >> (32-CurBit);
135 CurBit = (CurBit+NumBits) & 31;
138 void Emit64(uint64_t Val, unsigned NumBits) {
140 Emit((uint32_t)Val, NumBits);
142 Emit((uint32_t)Val, 32);
143 Emit((uint32_t)(Val >> 32), NumBits-32);
155 void EmitVBR(uint32_t Val, unsigned NumBits) {
156 assert(NumBits <= 32 && "Too many bits to emit!");
157 uint32_t Threshold = 1U << (NumBits-1);
159 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
160 while (Val >= Threshold) {
161 Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
168 void EmitVBR64(uint64_t Val, unsigned NumBits) {
169 assert(NumBits <= 32 && "Too many bits to emit!");
170 if ((uint32_t)Val == Val)
171 return EmitVBR((uint32_t)Val, NumBits);
173 uint32_t Threshold = 1U << (NumBits-1);
175 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
176 while (Val >= Threshold) {
177 Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
178 (1 << (NumBits-1)), NumBits);
182 Emit((uint32_t)Val, NumBits);
185 /// EmitCode - Emit the specified code.
186 void EmitCode(unsigned Val) {
187 Emit(Val, CurCodeSize);
190 //===--------------------------------------------------------------------===//
191 // Block Manipulation
192 //===--------------------------------------------------------------------===//
194 /// getBlockInfo - If there is block info for the specified ID, return it,
195 /// otherwise return null.
196 BlockInfo *getBlockInfo(unsigned BlockID) {
197 // Common case, the most recent entry matches BlockID.
198 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
199 return &BlockInfoRecords.back();
201 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
203 if (BlockInfoRecords[i].BlockID == BlockID)
204 return &BlockInfoRecords[i];
208 void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
210 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
211 EmitCode(bitc::ENTER_SUBBLOCK);
212 EmitVBR(BlockID, bitc::BlockIDWidth);
213 EmitVBR(CodeLen, bitc::CodeLenWidth);
216 unsigned BlockSizeWordIndex = GetWordIndex();
217 unsigned OldCodeSize = CurCodeSize;
219 // Emit a placeholder, which will be replaced when the block is popped.
220 Emit(0, bitc::BlockSizeWidth);
222 CurCodeSize = CodeLen;
224 // Push the outer block's abbrev set onto the stack, start out with an
226 BlockScope.emplace_back(OldCodeSize, BlockSizeWordIndex);
227 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
229 // If there is a blockinfo for this BlockID, add all the predefined abbrevs
230 // to the abbrev list.
231 if (BlockInfo *Info = getBlockInfo(BlockID)) {
232 CurAbbrevs.insert(CurAbbrevs.end(), Info->Abbrevs.begin(),
233 Info->Abbrevs.end());
238 assert(!BlockScope.empty() && "Block scope imbalance!");
239 const Block &B = BlockScope.back();
242 // [END_BLOCK, <align4bytes>]
243 EmitCode(bitc::END_BLOCK);
246 // Compute the size of the block, in words, not counting the size field.
247 unsigned SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
248 uint64_t BitNo = B.StartSizeWord * 32;
250 // Update the block size field in the header of this sub-block.
251 BackpatchWord(BitNo, SizeInWords);
253 // Restore the inner block's code size and abbrev table.
254 CurCodeSize = B.PrevCodeSize;
255 CurAbbrevs = std::move(B.PrevAbbrevs);
256 BlockScope.pop_back();
259 //===--------------------------------------------------------------------===//
261 //===--------------------------------------------------------------------===//
264 /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
265 /// record. This is a no-op, since the abbrev specifies the literal to use.
266 template<typename uintty>
267 void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
268 assert(Op.isLiteral() && "Not a literal");
269 // If the abbrev specifies the literal value to use, don't emit
271 assert(V == Op.getLiteralValue() &&
272 "Invalid abbrev for record!");
275 /// EmitAbbreviatedField - Emit a single scalar field value with the specified
277 template<typename uintty>
278 void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
279 assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
281 // Encode the value as we are commanded.
282 switch (Op.getEncoding()) {
283 default: llvm_unreachable("Unknown encoding!");
284 case BitCodeAbbrevOp::Fixed:
285 if (Op.getEncodingData())
286 Emit((unsigned)V, (unsigned)Op.getEncodingData());
288 case BitCodeAbbrevOp::VBR:
289 if (Op.getEncodingData())
290 EmitVBR64(V, (unsigned)Op.getEncodingData());
292 case BitCodeAbbrevOp::Char6:
293 Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
298 /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
299 /// emission code. If BlobData is non-null, then it specifies an array of
300 /// data that should be emitted as part of the Blob or Array operand that is
301 /// known to exist at the end of the record. If Code is specified, then
302 /// it is the record code to emit before the Vals, which must not contain
304 template <typename uintty>
305 void EmitRecordWithAbbrevImpl(unsigned Abbrev, ArrayRef<uintty> Vals,
306 StringRef Blob, Optional<unsigned> Code) {
307 const char *BlobData = Blob.data();
308 unsigned BlobLen = (unsigned) Blob.size();
309 unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
310 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
311 const BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo].get();
315 unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
317 assert(e && "Expected non-empty abbreviation");
318 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i++);
321 EmitAbbreviatedLiteral(Op, Code.getValue());
323 assert(Op.getEncoding() != BitCodeAbbrevOp::Array &&
324 Op.getEncoding() != BitCodeAbbrevOp::Blob &&
325 "Expected literal or scalar");
326 EmitAbbreviatedField(Op, Code.getValue());
330 unsigned RecordIdx = 0;
331 for (; i != e; ++i) {
332 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
333 if (Op.isLiteral()) {
334 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
335 EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
337 } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
339 assert(i + 2 == e && "array op not second to last?");
340 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
342 // If this record has blob data, emit it, otherwise we must have record
343 // entries to encode this way.
345 assert(RecordIdx == Vals.size() &&
346 "Blob data and record entries specified for array!");
347 // Emit a vbr6 to indicate the number of elements present.
348 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
351 for (unsigned i = 0; i != BlobLen; ++i)
352 EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
354 // Know that blob data is consumed for assertion below.
357 // Emit a vbr6 to indicate the number of elements present.
358 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
361 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
362 EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
364 } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
365 // If this record has blob data, emit it, otherwise we must have record
366 // entries to encode this way.
368 // Emit a vbr6 to indicate the number of elements present.
370 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
371 assert(RecordIdx == Vals.size() &&
372 "Blob data and record entries specified for blob operand!");
374 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
377 // Flush to a 32-bit alignment boundary.
380 // Emit each field as a literal byte.
382 for (unsigned i = 0; i != BlobLen; ++i)
383 WriteByte((unsigned char)BlobData[i]);
385 // Know that blob data is consumed for assertion below.
388 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx) {
389 assert(isUInt<8>(Vals[RecordIdx]) &&
390 "Value too large to emit as blob");
391 WriteByte((unsigned char)Vals[RecordIdx]);
395 // Align end to 32-bits.
396 while (GetBufferOffset() & 3)
398 } else { // Single scalar field.
399 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
400 EmitAbbreviatedField(Op, Vals[RecordIdx]);
404 assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
405 assert(BlobData == nullptr &&
406 "Blob data specified for record that doesn't use it!");
411 /// EmitRecord - Emit the specified record to the stream, using an abbrev if
412 /// we have one to compress the output.
413 template <typename Container>
414 void EmitRecord(unsigned Code, const Container &Vals, unsigned Abbrev = 0) {
416 // If we don't have an abbrev to use, emit this in its fully unabbreviated
418 auto Count = static_cast<uint32_t>(makeArrayRef(Vals).size());
419 EmitCode(bitc::UNABBREV_RECORD);
422 for (unsigned i = 0, e = Count; i != e; ++i)
423 EmitVBR64(Vals[i], 6);
427 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), StringRef(), Code);
430 /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
431 /// Unlike EmitRecord, the code for the record should be included in Vals as
433 template <typename Container>
434 void EmitRecordWithAbbrev(unsigned Abbrev, const Container &Vals) {
435 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), StringRef(), None);
438 /// EmitRecordWithBlob - Emit the specified record to the stream, using an
439 /// abbrev that includes a blob at the end. The blob data to emit is
440 /// specified by the pointer and length specified at the end. In contrast to
441 /// EmitRecord, this routine expects that the first entry in Vals is the code
443 template <typename Container>
444 void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
446 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Blob, None);
448 template <typename Container>
449 void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
450 const char *BlobData, unsigned BlobLen) {
451 return EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals),
452 StringRef(BlobData, BlobLen), None);
455 /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
456 /// that end with an array.
457 template <typename Container>
458 void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
460 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Array, None);
462 template <typename Container>
463 void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
464 const char *ArrayData, unsigned ArrayLen) {
465 return EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals),
466 StringRef(ArrayData, ArrayLen), None);
469 //===--------------------------------------------------------------------===//
471 //===--------------------------------------------------------------------===//
474 // Emit the abbreviation as a DEFINE_ABBREV record.
475 void EncodeAbbrev(BitCodeAbbrev *Abbv) {
476 EmitCode(bitc::DEFINE_ABBREV);
477 EmitVBR(Abbv->getNumOperandInfos(), 5);
478 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
480 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
481 Emit(Op.isLiteral(), 1);
482 if (Op.isLiteral()) {
483 EmitVBR64(Op.getLiteralValue(), 8);
485 Emit(Op.getEncoding(), 3);
486 if (Op.hasEncodingData())
487 EmitVBR64(Op.getEncodingData(), 5);
493 /// EmitAbbrev - This emits an abbreviation to the stream. Note that this
494 /// method takes ownership of the specified abbrev.
495 unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
496 // Emit the abbreviation as a record.
498 CurAbbrevs.push_back(Abbv);
499 return static_cast<unsigned>(CurAbbrevs.size())-1 +
500 bitc::FIRST_APPLICATION_ABBREV;
503 //===--------------------------------------------------------------------===//
504 // BlockInfo Block Emission
505 //===--------------------------------------------------------------------===//
507 /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
508 void EnterBlockInfoBlock(unsigned CodeWidth) {
509 EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
510 BlockInfoCurBID = ~0U;
513 /// SwitchToBlockID - If we aren't already talking about the specified block
514 /// ID, emit a BLOCKINFO_CODE_SETBID record.
515 void SwitchToBlockID(unsigned BlockID) {
516 if (BlockInfoCurBID == BlockID) return;
517 SmallVector<unsigned, 2> V;
518 V.push_back(BlockID);
519 EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
520 BlockInfoCurBID = BlockID;
523 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
524 if (BlockInfo *BI = getBlockInfo(BlockID))
527 // Otherwise, add a new record.
528 BlockInfoRecords.emplace_back();
529 BlockInfoRecords.back().BlockID = BlockID;
530 return BlockInfoRecords.back();
535 /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
537 unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
538 SwitchToBlockID(BlockID);
541 // Add the abbrev to the specified block record.
542 BlockInfo &Info = getOrCreateBlockInfo(BlockID);
543 Info.Abbrevs.push_back(Abbv);
545 return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
550 } // End llvm namespace