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/Optional.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/Bitcode/BitCodes.h"
22 #include "llvm/Support/Endian.h"
27 class BitstreamWriter {
28 SmallVectorImpl<char> &Out;
30 /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
33 /// CurValue - The current value. Only bits < CurBit are valid.
36 /// CurCodeSize - This is the declared size of code values used for the
37 /// current block, in bits.
40 /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
41 /// selected BLOCK ID.
42 unsigned BlockInfoCurBID;
44 /// CurAbbrevs - Abbrevs installed at in this block.
45 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> CurAbbrevs;
48 unsigned PrevCodeSize;
49 unsigned StartSizeWord;
50 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> PrevAbbrevs;
51 Block(unsigned PCS, unsigned SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
54 /// BlockScope - This tracks the current blocks that we have entered.
55 std::vector<Block> BlockScope;
57 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
58 /// These describe abbreviations that all blocks of the specified ID inherit.
61 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> Abbrevs;
63 std::vector<BlockInfo> BlockInfoRecords;
65 // BackpatchWord - Backpatch a 32-bit word in the output with the specified
67 void BackpatchWord(unsigned ByteNo, unsigned NewWord) {
68 support::endian::write32le(&Out[ByteNo], NewWord);
71 void WriteByte(unsigned char Value) {
75 void WriteWord(unsigned Value) {
76 Value = support::endian::byte_swap<uint32_t, support::little>(Value);
77 Out.append(reinterpret_cast<const char *>(&Value),
78 reinterpret_cast<const char *>(&Value + 1));
81 unsigned GetBufferOffset() const {
85 unsigned GetWordIndex() const {
86 unsigned Offset = GetBufferOffset();
87 assert((Offset & 3) == 0 && "Not 32-bit aligned");
92 explicit BitstreamWriter(SmallVectorImpl<char> &O)
93 : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
96 assert(CurBit == 0 && "Unflushed data remaining");
97 assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
100 /// \brief Retrieve the current position in the stream, in bits.
101 uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; }
103 //===--------------------------------------------------------------------===//
104 // Basic Primitives for emitting bits to the stream.
105 //===--------------------------------------------------------------------===//
107 void Emit(uint32_t Val, unsigned NumBits) {
108 assert(NumBits && NumBits <= 32 && "Invalid value size!");
109 assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
110 CurValue |= Val << CurBit;
111 if (CurBit + NumBits < 32) {
116 // Add the current word.
120 CurValue = Val >> (32-CurBit);
123 CurBit = (CurBit+NumBits) & 31;
126 void Emit64(uint64_t Val, unsigned NumBits) {
128 Emit((uint32_t)Val, NumBits);
130 Emit((uint32_t)Val, 32);
131 Emit((uint32_t)(Val >> 32), NumBits-32);
143 void EmitVBR(uint32_t Val, unsigned NumBits) {
144 assert(NumBits <= 32 && "Too many bits to emit!");
145 uint32_t Threshold = 1U << (NumBits-1);
147 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
148 while (Val >= Threshold) {
149 Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
156 void EmitVBR64(uint64_t Val, unsigned NumBits) {
157 assert(NumBits <= 32 && "Too many bits to emit!");
158 if ((uint32_t)Val == Val)
159 return EmitVBR((uint32_t)Val, NumBits);
161 uint32_t Threshold = 1U << (NumBits-1);
163 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
164 while (Val >= Threshold) {
165 Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
166 (1 << (NumBits-1)), NumBits);
170 Emit((uint32_t)Val, NumBits);
173 /// EmitCode - Emit the specified code.
174 void EmitCode(unsigned Val) {
175 Emit(Val, CurCodeSize);
178 //===--------------------------------------------------------------------===//
179 // Block Manipulation
180 //===--------------------------------------------------------------------===//
182 /// getBlockInfo - If there is block info for the specified ID, return it,
183 /// otherwise return null.
184 BlockInfo *getBlockInfo(unsigned BlockID) {
185 // Common case, the most recent entry matches BlockID.
186 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
187 return &BlockInfoRecords.back();
189 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
191 if (BlockInfoRecords[i].BlockID == BlockID)
192 return &BlockInfoRecords[i];
196 void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
198 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
199 EmitCode(bitc::ENTER_SUBBLOCK);
200 EmitVBR(BlockID, bitc::BlockIDWidth);
201 EmitVBR(CodeLen, bitc::CodeLenWidth);
204 unsigned BlockSizeWordIndex = GetWordIndex();
205 unsigned OldCodeSize = CurCodeSize;
207 // Emit a placeholder, which will be replaced when the block is popped.
208 Emit(0, bitc::BlockSizeWidth);
210 CurCodeSize = CodeLen;
212 // Push the outer block's abbrev set onto the stack, start out with an
214 BlockScope.emplace_back(OldCodeSize, BlockSizeWordIndex);
215 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
217 // If there is a blockinfo for this BlockID, add all the predefined abbrevs
218 // to the abbrev list.
219 if (BlockInfo *Info = getBlockInfo(BlockID)) {
220 CurAbbrevs.insert(CurAbbrevs.end(), Info->Abbrevs.begin(),
221 Info->Abbrevs.end());
226 assert(!BlockScope.empty() && "Block scope imbalance!");
227 const Block &B = BlockScope.back();
230 // [END_BLOCK, <align4bytes>]
231 EmitCode(bitc::END_BLOCK);
234 // Compute the size of the block, in words, not counting the size field.
235 unsigned SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
236 unsigned ByteNo = B.StartSizeWord*4;
238 // Update the block size field in the header of this sub-block.
239 BackpatchWord(ByteNo, SizeInWords);
241 // Restore the inner block's code size and abbrev table.
242 CurCodeSize = B.PrevCodeSize;
243 CurAbbrevs = std::move(B.PrevAbbrevs);
244 BlockScope.pop_back();
247 //===--------------------------------------------------------------------===//
249 //===--------------------------------------------------------------------===//
252 /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
253 /// record. This is a no-op, since the abbrev specifies the literal to use.
254 template<typename uintty>
255 void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
256 assert(Op.isLiteral() && "Not a literal");
257 // If the abbrev specifies the literal value to use, don't emit
259 assert(V == Op.getLiteralValue() &&
260 "Invalid abbrev for record!");
263 /// EmitAbbreviatedField - Emit a single scalar field value with the specified
265 template<typename uintty>
266 void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
267 assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
269 // Encode the value as we are commanded.
270 switch (Op.getEncoding()) {
271 default: llvm_unreachable("Unknown encoding!");
272 case BitCodeAbbrevOp::Fixed:
273 if (Op.getEncodingData())
274 Emit((unsigned)V, (unsigned)Op.getEncodingData());
276 case BitCodeAbbrevOp::VBR:
277 if (Op.getEncodingData())
278 EmitVBR64(V, (unsigned)Op.getEncodingData());
280 case BitCodeAbbrevOp::Char6:
281 Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
286 /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
287 /// emission code. If BlobData is non-null, then it specifies an array of
288 /// data that should be emitted as part of the Blob or Array operand that is
289 /// known to exist at the end of the record. If Code is specified, then
290 /// it is the record code to emit before the Vals, which must not contain
292 template<typename uintty>
293 void EmitRecordWithAbbrevImpl(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
294 StringRef Blob, Optional<unsigned> Code) {
295 const char *BlobData = Blob.data();
296 unsigned BlobLen = (unsigned) Blob.size();
297 unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
298 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
299 const BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo].get();
303 unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
305 assert(e && "Expected non-empty abbreviation");
306 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i++);
309 EmitAbbreviatedLiteral(Op, Code.getValue());
311 assert(Op.getEncoding() != BitCodeAbbrevOp::Array &&
312 Op.getEncoding() != BitCodeAbbrevOp::Blob &&
313 "Expected literal or scalar");
314 EmitAbbreviatedField(Op, Code.getValue());
318 unsigned RecordIdx = 0;
319 for (; i != e; ++i) {
320 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
321 if (Op.isLiteral()) {
322 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
323 EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
325 } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
327 assert(i + 2 == e && "array op not second to last?");
328 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
330 // If this record has blob data, emit it, otherwise we must have record
331 // entries to encode this way.
333 assert(RecordIdx == Vals.size() &&
334 "Blob data and record entries specified for array!");
335 // Emit a vbr6 to indicate the number of elements present.
336 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
339 for (unsigned i = 0; i != BlobLen; ++i)
340 EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
342 // Know that blob data is consumed for assertion below.
345 // Emit a vbr6 to indicate the number of elements present.
346 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
349 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
350 EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
352 } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
353 // If this record has blob data, emit it, otherwise we must have record
354 // entries to encode this way.
356 // Emit a vbr6 to indicate the number of elements present.
358 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
359 assert(RecordIdx == Vals.size() &&
360 "Blob data and record entries specified for blob operand!");
362 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
365 // Flush to a 32-bit alignment boundary.
368 // Emit each field as a literal byte.
370 for (unsigned i = 0; i != BlobLen; ++i)
371 WriteByte((unsigned char)BlobData[i]);
373 // Know that blob data is consumed for assertion below.
376 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx) {
377 assert(isUInt<8>(Vals[RecordIdx]) &&
378 "Value too large to emit as blob");
379 WriteByte((unsigned char)Vals[RecordIdx]);
383 // Align end to 32-bits.
384 while (GetBufferOffset() & 3)
386 } else { // Single scalar field.
387 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
388 EmitAbbreviatedField(Op, Vals[RecordIdx]);
392 assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
393 assert(BlobData == nullptr &&
394 "Blob data specified for record that doesn't use it!");
399 /// EmitRecord - Emit the specified record to the stream, using an abbrev if
400 /// we have one to compress the output.
401 template<typename uintty>
402 void EmitRecord(unsigned Code, SmallVectorImpl<uintty> &Vals,
403 unsigned Abbrev = 0) {
405 // If we don't have an abbrev to use, emit this in its fully unabbreviated
407 EmitCode(bitc::UNABBREV_RECORD);
409 EmitVBR(static_cast<uint32_t>(Vals.size()), 6);
410 for (unsigned i = 0, e = static_cast<unsigned>(Vals.size()); i != e; ++i)
411 EmitVBR64(Vals[i], 6);
415 EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(), Code);
418 /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
419 /// Unlike EmitRecord, the code for the record should be included in Vals as
421 template<typename uintty>
422 void EmitRecordWithAbbrev(unsigned Abbrev, SmallVectorImpl<uintty> &Vals) {
423 EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(), None);
426 /// EmitRecordWithBlob - Emit the specified record to the stream, using an
427 /// abbrev that includes a blob at the end. The blob data to emit is
428 /// specified by the pointer and length specified at the end. In contrast to
429 /// EmitRecord, this routine expects that the first entry in Vals is the code
431 template<typename uintty>
432 void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
434 EmitRecordWithAbbrevImpl(Abbrev, Vals, Blob, None);
436 template<typename uintty>
437 void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
438 const char *BlobData, unsigned BlobLen) {
439 return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(BlobData, BlobLen),
443 /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
444 /// that end with an array.
445 template<typename uintty>
446 void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
448 EmitRecordWithAbbrevImpl(Abbrev, Vals, Array, None);
450 template<typename uintty>
451 void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
452 const char *ArrayData, unsigned ArrayLen) {
453 return EmitRecordWithAbbrevImpl(Abbrev, Vals,
454 StringRef(ArrayData, ArrayLen), None);
457 //===--------------------------------------------------------------------===//
459 //===--------------------------------------------------------------------===//
462 // Emit the abbreviation as a DEFINE_ABBREV record.
463 void EncodeAbbrev(BitCodeAbbrev *Abbv) {
464 EmitCode(bitc::DEFINE_ABBREV);
465 EmitVBR(Abbv->getNumOperandInfos(), 5);
466 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
468 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
469 Emit(Op.isLiteral(), 1);
470 if (Op.isLiteral()) {
471 EmitVBR64(Op.getLiteralValue(), 8);
473 Emit(Op.getEncoding(), 3);
474 if (Op.hasEncodingData())
475 EmitVBR64(Op.getEncodingData(), 5);
481 /// EmitAbbrev - This emits an abbreviation to the stream. Note that this
482 /// method takes ownership of the specified abbrev.
483 unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
484 // Emit the abbreviation as a record.
486 CurAbbrevs.push_back(Abbv);
487 return static_cast<unsigned>(CurAbbrevs.size())-1 +
488 bitc::FIRST_APPLICATION_ABBREV;
491 //===--------------------------------------------------------------------===//
492 // BlockInfo Block Emission
493 //===--------------------------------------------------------------------===//
495 /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
496 void EnterBlockInfoBlock(unsigned CodeWidth) {
497 EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
498 BlockInfoCurBID = ~0U;
501 /// SwitchToBlockID - If we aren't already talking about the specified block
502 /// ID, emit a BLOCKINFO_CODE_SETBID record.
503 void SwitchToBlockID(unsigned BlockID) {
504 if (BlockInfoCurBID == BlockID) return;
505 SmallVector<unsigned, 2> V;
506 V.push_back(BlockID);
507 EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
508 BlockInfoCurBID = BlockID;
511 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
512 if (BlockInfo *BI = getBlockInfo(BlockID))
515 // Otherwise, add a new record.
516 BlockInfoRecords.emplace_back();
517 BlockInfoRecords.back().BlockID = BlockID;
518 return BlockInfoRecords.back();
523 /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
525 unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
526 SwitchToBlockID(BlockID);
529 // Add the abbrev to the specified block record.
530 BlockInfo &Info = getOrCreateBlockInfo(BlockID);
531 Info.Abbrevs.push_back(Abbv);
533 return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
538 } // End llvm namespace