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/SmallVector.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Bitcode/BitCodes.h"
25 class BitstreamWriter {
26 SmallVectorImpl<char> &Out;
28 /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
31 /// CurValue - The current value. Only bits < CurBit are valid.
34 /// CurCodeSize - This is the declared size of code values used for the
35 /// current block, in bits.
38 /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
39 /// selected BLOCK ID.
40 unsigned BlockInfoCurBID;
42 /// CurAbbrevs - Abbrevs installed at in this block.
43 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> CurAbbrevs;
46 unsigned PrevCodeSize;
47 unsigned StartSizeWord;
48 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> PrevAbbrevs;
49 Block(unsigned PCS, unsigned SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
52 /// BlockScope - This tracks the current blocks that we have entered.
53 std::vector<Block> BlockScope;
55 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
56 /// These describe abbreviations that all blocks of the specified ID inherit.
59 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> Abbrevs;
61 std::vector<BlockInfo> BlockInfoRecords;
63 // BackpatchWord - Backpatch a 32-bit word in the output with the specified
65 void BackpatchWord(unsigned ByteNo, unsigned NewWord) {
66 Out[ByteNo++] = (unsigned char)(NewWord >> 0);
67 Out[ByteNo++] = (unsigned char)(NewWord >> 8);
68 Out[ByteNo++] = (unsigned char)(NewWord >> 16);
69 Out[ByteNo ] = (unsigned char)(NewWord >> 24);
72 void WriteByte(unsigned char Value) {
76 void WriteWord(unsigned Value) {
77 unsigned char Bytes[4] = {
78 (unsigned char)(Value >> 0),
79 (unsigned char)(Value >> 8),
80 (unsigned char)(Value >> 16),
81 (unsigned char)(Value >> 24) };
82 Out.append(&Bytes[0], &Bytes[4]);
85 unsigned GetBufferOffset() const {
89 unsigned GetWordIndex() const {
90 unsigned Offset = GetBufferOffset();
91 assert((Offset & 3) == 0 && "Not 32-bit aligned");
96 explicit BitstreamWriter(SmallVectorImpl<char> &O)
97 : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
100 assert(CurBit == 0 && "Unflushed data remaining");
101 assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
104 /// \brief Retrieve the current position in the stream, in bits.
105 uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; }
107 //===--------------------------------------------------------------------===//
108 // Basic Primitives for emitting bits to the stream.
109 //===--------------------------------------------------------------------===//
111 void Emit(uint32_t Val, unsigned NumBits) {
112 assert(NumBits && NumBits <= 32 && "Invalid value size!");
113 assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
114 CurValue |= Val << CurBit;
115 if (CurBit + NumBits < 32) {
120 // Add the current word.
124 CurValue = Val >> (32-CurBit);
127 CurBit = (CurBit+NumBits) & 31;
130 void Emit64(uint64_t Val, unsigned NumBits) {
132 Emit((uint32_t)Val, NumBits);
134 Emit((uint32_t)Val, 32);
135 Emit((uint32_t)(Val >> 32), NumBits-32);
147 void EmitVBR(uint32_t Val, unsigned NumBits) {
148 assert(NumBits <= 32 && "Too many bits to emit!");
149 uint32_t Threshold = 1U << (NumBits-1);
151 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
152 while (Val >= Threshold) {
153 Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
160 void EmitVBR64(uint64_t Val, unsigned NumBits) {
161 assert(NumBits <= 32 && "Too many bits to emit!");
162 if ((uint32_t)Val == Val)
163 return EmitVBR((uint32_t)Val, NumBits);
165 uint32_t Threshold = 1U << (NumBits-1);
167 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
168 while (Val >= Threshold) {
169 Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
170 (1 << (NumBits-1)), NumBits);
174 Emit((uint32_t)Val, NumBits);
177 /// EmitCode - Emit the specified code.
178 void EmitCode(unsigned Val) {
179 Emit(Val, CurCodeSize);
182 //===--------------------------------------------------------------------===//
183 // Block Manipulation
184 //===--------------------------------------------------------------------===//
186 /// getBlockInfo - If there is block info for the specified ID, return it,
187 /// otherwise return null.
188 BlockInfo *getBlockInfo(unsigned BlockID) {
189 // Common case, the most recent entry matches BlockID.
190 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
191 return &BlockInfoRecords.back();
193 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
195 if (BlockInfoRecords[i].BlockID == BlockID)
196 return &BlockInfoRecords[i];
200 void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
202 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
203 EmitCode(bitc::ENTER_SUBBLOCK);
204 EmitVBR(BlockID, bitc::BlockIDWidth);
205 EmitVBR(CodeLen, bitc::CodeLenWidth);
208 unsigned BlockSizeWordIndex = GetWordIndex();
209 unsigned OldCodeSize = CurCodeSize;
211 // Emit a placeholder, which will be replaced when the block is popped.
212 Emit(0, bitc::BlockSizeWidth);
214 CurCodeSize = CodeLen;
216 // Push the outer block's abbrev set onto the stack, start out with an
218 BlockScope.push_back(Block(OldCodeSize, BlockSizeWordIndex));
219 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
221 // If there is a blockinfo for this BlockID, add all the predefined abbrevs
222 // to the abbrev list.
223 if (BlockInfo *Info = getBlockInfo(BlockID)) {
224 CurAbbrevs.insert(CurAbbrevs.end(), Info->Abbrevs.begin(),
225 Info->Abbrevs.end());
230 assert(!BlockScope.empty() && "Block scope imbalance!");
231 const Block &B = BlockScope.back();
234 // [END_BLOCK, <align4bytes>]
235 EmitCode(bitc::END_BLOCK);
238 // Compute the size of the block, in words, not counting the size field.
239 unsigned SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
240 unsigned ByteNo = B.StartSizeWord*4;
242 // Update the block size field in the header of this sub-block.
243 BackpatchWord(ByteNo, SizeInWords);
245 // Restore the inner block's code size and abbrev table.
246 CurCodeSize = B.PrevCodeSize;
247 CurAbbrevs = std::move(B.PrevAbbrevs);
248 BlockScope.pop_back();
251 //===--------------------------------------------------------------------===//
253 //===--------------------------------------------------------------------===//
256 /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
257 /// record. This is a no-op, since the abbrev specifies the literal to use.
258 template<typename uintty>
259 void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
260 assert(Op.isLiteral() && "Not a literal");
261 // If the abbrev specifies the literal value to use, don't emit
263 assert(V == Op.getLiteralValue() &&
264 "Invalid abbrev for record!");
267 /// EmitAbbreviatedField - Emit a single scalar field value with the specified
269 template<typename uintty>
270 void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
271 assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
273 // Encode the value as we are commanded.
274 switch (Op.getEncoding()) {
275 default: llvm_unreachable("Unknown encoding!");
276 case BitCodeAbbrevOp::Fixed:
277 if (Op.getEncodingData())
278 Emit((unsigned)V, (unsigned)Op.getEncodingData());
280 case BitCodeAbbrevOp::VBR:
281 if (Op.getEncodingData())
282 EmitVBR64(V, (unsigned)Op.getEncodingData());
284 case BitCodeAbbrevOp::Char6:
285 Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
290 /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
291 /// emission code. If BlobData is non-null, then it specifies an array of
292 /// data that should be emitted as part of the Blob or Array operand that is
293 /// known to exist at the end of the record.
294 template<typename uintty>
295 void EmitRecordWithAbbrevImpl(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
297 const char *BlobData = Blob.data();
298 unsigned BlobLen = (unsigned) Blob.size();
299 unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
300 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
301 const BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo].get();
305 unsigned RecordIdx = 0;
306 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
308 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
309 if (Op.isLiteral()) {
310 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
311 EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
313 } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
315 assert(i+2 == e && "array op not second to last?");
316 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
318 // If this record has blob data, emit it, otherwise we must have record
319 // entries to encode this way.
321 assert(RecordIdx == Vals.size() &&
322 "Blob data and record entries specified for array!");
323 // Emit a vbr6 to indicate the number of elements present.
324 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
327 for (unsigned i = 0; i != BlobLen; ++i)
328 EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
330 // Know that blob data is consumed for assertion below.
333 // Emit a vbr6 to indicate the number of elements present.
334 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
337 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
338 EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
340 } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
341 // If this record has blob data, emit it, otherwise we must have record
342 // entries to encode this way.
344 // Emit a vbr6 to indicate the number of elements present.
346 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
347 assert(RecordIdx == Vals.size() &&
348 "Blob data and record entries specified for blob operand!");
350 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
353 // Flush to a 32-bit alignment boundary.
356 // Emit each field as a literal byte.
358 for (unsigned i = 0; i != BlobLen; ++i)
359 WriteByte((unsigned char)BlobData[i]);
361 // Know that blob data is consumed for assertion below.
364 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx) {
365 assert(isUInt<8>(Vals[RecordIdx]) &&
366 "Value too large to emit as blob");
367 WriteByte((unsigned char)Vals[RecordIdx]);
371 // Align end to 32-bits.
372 while (GetBufferOffset() & 3)
374 } else { // Single scalar field.
375 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
376 EmitAbbreviatedField(Op, Vals[RecordIdx]);
380 assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
381 assert(BlobData == nullptr &&
382 "Blob data specified for record that doesn't use it!");
387 /// EmitRecord - Emit the specified record to the stream, using an abbrev if
388 /// we have one to compress the output.
389 template<typename uintty>
390 void EmitRecord(unsigned Code, SmallVectorImpl<uintty> &Vals,
391 unsigned Abbrev = 0) {
393 // If we don't have an abbrev to use, emit this in its fully unabbreviated
395 EmitCode(bitc::UNABBREV_RECORD);
397 EmitVBR(static_cast<uint32_t>(Vals.size()), 6);
398 for (unsigned i = 0, e = static_cast<unsigned>(Vals.size()); i != e; ++i)
399 EmitVBR64(Vals[i], 6);
403 // Insert the code into Vals to treat it uniformly.
404 Vals.insert(Vals.begin(), Code);
406 EmitRecordWithAbbrev(Abbrev, Vals);
409 /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
410 /// Unlike EmitRecord, the code for the record should be included in Vals as
412 template<typename uintty>
413 void EmitRecordWithAbbrev(unsigned Abbrev, SmallVectorImpl<uintty> &Vals) {
414 EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef());
417 /// EmitRecordWithBlob - Emit the specified record to the stream, using an
418 /// abbrev that includes a blob at the end. The blob data to emit is
419 /// specified by the pointer and length specified at the end. In contrast to
420 /// EmitRecord, this routine expects that the first entry in Vals is the code
422 template<typename uintty>
423 void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
425 EmitRecordWithAbbrevImpl(Abbrev, Vals, Blob);
427 template<typename uintty>
428 void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
429 const char *BlobData, unsigned BlobLen) {
430 return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(BlobData, BlobLen));
433 /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
434 /// that end with an array.
435 template<typename uintty>
436 void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
438 EmitRecordWithAbbrevImpl(Abbrev, Vals, Array);
440 template<typename uintty>
441 void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
442 const char *ArrayData, unsigned ArrayLen) {
443 return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(ArrayData,
447 //===--------------------------------------------------------------------===//
449 //===--------------------------------------------------------------------===//
452 // Emit the abbreviation as a DEFINE_ABBREV record.
453 void EncodeAbbrev(BitCodeAbbrev *Abbv) {
454 EmitCode(bitc::DEFINE_ABBREV);
455 EmitVBR(Abbv->getNumOperandInfos(), 5);
456 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
458 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
459 Emit(Op.isLiteral(), 1);
460 if (Op.isLiteral()) {
461 EmitVBR64(Op.getLiteralValue(), 8);
463 Emit(Op.getEncoding(), 3);
464 if (Op.hasEncodingData())
465 EmitVBR64(Op.getEncodingData(), 5);
471 /// EmitAbbrev - This emits an abbreviation to the stream. Note that this
472 /// method takes ownership of the specified abbrev.
473 unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
474 // Emit the abbreviation as a record.
476 CurAbbrevs.push_back(Abbv);
477 return static_cast<unsigned>(CurAbbrevs.size())-1 +
478 bitc::FIRST_APPLICATION_ABBREV;
481 //===--------------------------------------------------------------------===//
482 // BlockInfo Block Emission
483 //===--------------------------------------------------------------------===//
485 /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
486 void EnterBlockInfoBlock(unsigned CodeWidth) {
487 EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
488 BlockInfoCurBID = ~0U;
491 /// SwitchToBlockID - If we aren't already talking about the specified block
492 /// ID, emit a BLOCKINFO_CODE_SETBID record.
493 void SwitchToBlockID(unsigned BlockID) {
494 if (BlockInfoCurBID == BlockID) return;
495 SmallVector<unsigned, 2> V;
496 V.push_back(BlockID);
497 EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
498 BlockInfoCurBID = BlockID;
501 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
502 if (BlockInfo *BI = getBlockInfo(BlockID))
505 // Otherwise, add a new record.
506 BlockInfoRecords.push_back(BlockInfo());
507 BlockInfoRecords.back().BlockID = BlockID;
508 return BlockInfoRecords.back();
513 /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
515 unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
516 SwitchToBlockID(BlockID);
519 // Add the abbrev to the specified block record.
520 BlockInfo &Info = getOrCreateBlockInfo(BlockID);
521 Info.Abbrevs.push_back(Abbv);
523 return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
528 } // End llvm namespace