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/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.
290 template <typename uintty>
291 void EmitRecordWithAbbrevImpl(unsigned Abbrev, const ArrayRef<uintty> &Vals,
293 const char *BlobData = Blob.data();
294 unsigned BlobLen = (unsigned) Blob.size();
295 unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
296 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
297 const BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo].get();
301 unsigned RecordIdx = 0;
302 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
304 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
305 if (Op.isLiteral()) {
306 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
307 EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
309 } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
311 assert(i+2 == e && "array op not second to last?");
312 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
314 // If this record has blob data, emit it, otherwise we must have record
315 // entries to encode this way.
317 assert(RecordIdx == Vals.size() &&
318 "Blob data and record entries specified for array!");
319 // Emit a vbr6 to indicate the number of elements present.
320 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
323 for (unsigned i = 0; i != BlobLen; ++i)
324 EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
326 // Know that blob data is consumed for assertion below.
329 // Emit a vbr6 to indicate the number of elements present.
330 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
333 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
334 EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
336 } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
337 // If this record has blob data, emit it, otherwise we must have record
338 // entries to encode this way.
340 // Emit a vbr6 to indicate the number of elements present.
342 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
343 assert(RecordIdx == Vals.size() &&
344 "Blob data and record entries specified for blob operand!");
346 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
349 // Flush to a 32-bit alignment boundary.
352 // Emit each field as a literal byte.
354 for (unsigned i = 0; i != BlobLen; ++i)
355 WriteByte((unsigned char)BlobData[i]);
357 // Know that blob data is consumed for assertion below.
360 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx) {
361 assert(isUInt<8>(Vals[RecordIdx]) &&
362 "Value too large to emit as blob");
363 WriteByte((unsigned char)Vals[RecordIdx]);
367 // Align end to 32-bits.
368 while (GetBufferOffset() & 3)
370 } else { // Single scalar field.
371 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
372 EmitAbbreviatedField(Op, Vals[RecordIdx]);
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!");
383 /// EmitRecord - Emit the specified record to the stream, using an abbrev if
384 /// we have one to compress the output.
385 template<typename uintty>
386 void EmitRecord(unsigned Code, SmallVectorImpl<uintty> &Vals,
387 unsigned Abbrev = 0) {
389 // If we don't have an abbrev to use, emit this in its fully unabbreviated
391 EmitCode(bitc::UNABBREV_RECORD);
393 EmitVBR(static_cast<uint32_t>(Vals.size()), 6);
394 for (unsigned i = 0, e = static_cast<unsigned>(Vals.size()); i != e; ++i)
395 EmitVBR64(Vals[i], 6);
399 // Insert the code into Vals to treat it uniformly.
400 Vals.insert(Vals.begin(), Code);
402 EmitRecordWithAbbrev(Abbrev, makeArrayRef(Vals));
405 /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
406 /// Unlike EmitRecord, the code for the record should be included in Vals as
408 template <typename uintty>
409 void EmitRecordWithAbbrev(unsigned Abbrev, const ArrayRef<uintty> &Vals) {
410 EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef());
413 /// EmitRecordWithBlob - Emit the specified record to the stream, using an
414 /// abbrev that includes a blob at the end. The blob data to emit is
415 /// specified by the pointer and length specified at the end. In contrast to
416 /// EmitRecord, this routine expects that the first entry in Vals is the code
418 template <typename uintty>
419 void EmitRecordWithBlob(unsigned Abbrev, const ArrayRef<uintty> &Vals,
421 EmitRecordWithAbbrevImpl(Abbrev, Vals, Blob);
423 template <typename uintty>
424 void EmitRecordWithBlob(unsigned Abbrev, const ArrayRef<uintty> &Vals,
425 const char *BlobData, unsigned BlobLen) {
426 return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(BlobData, BlobLen));
429 /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
430 /// that end with an array.
431 template <typename uintty>
432 void EmitRecordWithArray(unsigned Abbrev, const ArrayRef<uintty> &Vals,
434 EmitRecordWithAbbrevImpl(Abbrev, Vals, Array);
436 template <typename uintty>
437 void EmitRecordWithArray(unsigned Abbrev, const ArrayRef<uintty> &Vals,
438 const char *ArrayData, unsigned ArrayLen) {
439 return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(ArrayData,
443 //===--------------------------------------------------------------------===//
445 //===--------------------------------------------------------------------===//
448 // Emit the abbreviation as a DEFINE_ABBREV record.
449 void EncodeAbbrev(BitCodeAbbrev *Abbv) {
450 EmitCode(bitc::DEFINE_ABBREV);
451 EmitVBR(Abbv->getNumOperandInfos(), 5);
452 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
454 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
455 Emit(Op.isLiteral(), 1);
456 if (Op.isLiteral()) {
457 EmitVBR64(Op.getLiteralValue(), 8);
459 Emit(Op.getEncoding(), 3);
460 if (Op.hasEncodingData())
461 EmitVBR64(Op.getEncodingData(), 5);
467 /// EmitAbbrev - This emits an abbreviation to the stream. Note that this
468 /// method takes ownership of the specified abbrev.
469 unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
470 // Emit the abbreviation as a record.
472 CurAbbrevs.push_back(Abbv);
473 return static_cast<unsigned>(CurAbbrevs.size())-1 +
474 bitc::FIRST_APPLICATION_ABBREV;
477 //===--------------------------------------------------------------------===//
478 // BlockInfo Block Emission
479 //===--------------------------------------------------------------------===//
481 /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
482 void EnterBlockInfoBlock(unsigned CodeWidth) {
483 EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
484 BlockInfoCurBID = ~0U;
487 /// SwitchToBlockID - If we aren't already talking about the specified block
488 /// ID, emit a BLOCKINFO_CODE_SETBID record.
489 void SwitchToBlockID(unsigned BlockID) {
490 if (BlockInfoCurBID == BlockID) return;
491 SmallVector<unsigned, 2> V;
492 V.push_back(BlockID);
493 EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
494 BlockInfoCurBID = BlockID;
497 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
498 if (BlockInfo *BI = getBlockInfo(BlockID))
501 // Otherwise, add a new record.
502 BlockInfoRecords.emplace_back();
503 BlockInfoRecords.back().BlockID = BlockID;
504 return BlockInfoRecords.back();
509 /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
511 unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
512 SwitchToBlockID(BlockID);
515 // Add the abbrev to the specified block record.
516 BlockInfo &Info = getOrCreateBlockInfo(BlockID);
517 Info.Abbrevs.push_back(Abbv);
519 return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
524 } // End llvm namespace