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 BITSTREAM_WRITER_H
16 #define BITSTREAM_WRITER_H
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/Bitcode/BitCodes.h"
24 class BitstreamWriter {
25 std::vector<unsigned char> &Out;
27 /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
30 /// CurValue - The current value. Only bits < CurBit are valid.
33 /// CurCodeSize - This is the declared size of code values used for the
34 /// current block, in bits.
37 /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
38 /// selected BLOCK ID.
39 unsigned BlockInfoCurBID;
41 /// CurAbbrevs - Abbrevs installed at in this block.
42 std::vector<BitCodeAbbrev*> CurAbbrevs;
45 unsigned PrevCodeSize;
46 unsigned StartSizeWord;
47 std::vector<BitCodeAbbrev*> PrevAbbrevs;
48 Block(unsigned PCS, unsigned SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
51 /// BlockScope - This tracks the current blocks that we have entered.
52 std::vector<Block> BlockScope;
54 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
55 /// These describe abbreviations that all blocks of the specified ID inherit.
58 std::vector<BitCodeAbbrev*> Abbrevs;
60 std::vector<BlockInfo> BlockInfoRecords;
62 // BackpatchWord - Backpatch a 32-bit word in the output with the specified
64 void BackpatchWord(unsigned ByteNo, unsigned NewWord) {
65 Out[ByteNo++] = (unsigned char)(NewWord >> 0);
66 Out[ByteNo++] = (unsigned char)(NewWord >> 8);
67 Out[ByteNo++] = (unsigned char)(NewWord >> 16);
68 Out[ByteNo ] = (unsigned char)(NewWord >> 24);
71 void WriteByte(unsigned char Value) {
75 void WriteWord(unsigned Value) {
76 Out.push_back((unsigned char)(Value >> 0));
77 Out.push_back((unsigned char)(Value >> 8));
78 Out.push_back((unsigned char)(Value >> 16));
79 Out.push_back((unsigned char)(Value >> 24));
82 unsigned GetBufferOffset() const {
86 unsigned GetWordIndex() const {
87 unsigned Offset = GetBufferOffset();
88 assert((Offset & 3) == 0 && "Not 32-bit aligned");
93 explicit BitstreamWriter(std::vector<unsigned char> &O)
94 : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
97 assert(CurBit == 0 && "Unflused data remaining");
98 assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
100 // Free the BlockInfoRecords.
101 while (!BlockInfoRecords.empty()) {
102 BlockInfo &Info = BlockInfoRecords.back();
103 // Free blockinfo abbrev info.
104 for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
106 Info.Abbrevs[i]->dropRef();
107 BlockInfoRecords.pop_back();
111 /// \brief Retrieve the current position in the stream, in bits.
112 uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; }
114 //===--------------------------------------------------------------------===//
115 // Basic Primitives for emitting bits to the stream.
116 //===--------------------------------------------------------------------===//
118 void Emit(uint32_t Val, unsigned NumBits) {
119 assert(NumBits && NumBits <= 32 && "Invalid value size!");
120 assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
121 CurValue |= Val << CurBit;
122 if (CurBit + NumBits < 32) {
127 // Add the current word.
131 CurValue = Val >> (32-CurBit);
134 CurBit = (CurBit+NumBits) & 31;
137 void Emit64(uint64_t Val, unsigned NumBits) {
139 Emit((uint32_t)Val, NumBits);
141 Emit((uint32_t)Val, 32);
142 Emit((uint32_t)(Val >> 32), NumBits-32);
154 void EmitVBR(uint32_t Val, unsigned NumBits) {
155 uint32_t Threshold = 1U << (NumBits-1);
157 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
158 while (Val >= Threshold) {
159 Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
166 void EmitVBR64(uint64_t Val, unsigned NumBits) {
167 if ((uint32_t)Val == Val)
168 return EmitVBR((uint32_t)Val, NumBits);
170 uint64_t Threshold = 1U << (NumBits-1);
172 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
173 while (Val >= Threshold) {
174 Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
175 (1 << (NumBits-1)), NumBits);
179 Emit((uint32_t)Val, NumBits);
182 /// EmitCode - Emit the specified code.
183 void EmitCode(unsigned Val) {
184 Emit(Val, CurCodeSize);
187 //===--------------------------------------------------------------------===//
188 // Block Manipulation
189 //===--------------------------------------------------------------------===//
191 /// getBlockInfo - If there is block info for the specified ID, return it,
192 /// otherwise return null.
193 BlockInfo *getBlockInfo(unsigned BlockID) {
194 // Common case, the most recent entry matches BlockID.
195 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
196 return &BlockInfoRecords.back();
198 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
200 if (BlockInfoRecords[i].BlockID == BlockID)
201 return &BlockInfoRecords[i];
205 void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
207 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
208 EmitCode(bitc::ENTER_SUBBLOCK);
209 EmitVBR(BlockID, bitc::BlockIDWidth);
210 EmitVBR(CodeLen, bitc::CodeLenWidth);
213 unsigned BlockSizeWordIndex = GetWordIndex();
214 unsigned OldCodeSize = CurCodeSize;
216 // Emit a placeholder, which will be replaced when the block is popped.
217 Emit(0, bitc::BlockSizeWidth);
219 CurCodeSize = CodeLen;
221 // Push the outer block's abbrev set onto the stack, start out with an
223 BlockScope.push_back(Block(OldCodeSize, BlockSizeWordIndex));
224 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
226 // If there is a blockinfo for this BlockID, add all the predefined abbrevs
227 // to the abbrev list.
228 if (BlockInfo *Info = getBlockInfo(BlockID)) {
229 for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
231 CurAbbrevs.push_back(Info->Abbrevs[i]);
232 Info->Abbrevs[i]->addRef();
238 assert(!BlockScope.empty() && "Block scope imbalance!");
240 // Delete all abbrevs.
241 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
243 CurAbbrevs[i]->dropRef();
245 const Block &B = BlockScope.back();
248 // [END_BLOCK, <align4bytes>]
249 EmitCode(bitc::END_BLOCK);
252 // Compute the size of the block, in words, not counting the size field.
253 unsigned SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
254 unsigned ByteNo = B.StartSizeWord*4;
256 // Update the block size field in the header of this sub-block.
257 BackpatchWord(ByteNo, SizeInWords);
259 // Restore the inner block's code size and abbrev table.
260 CurCodeSize = B.PrevCodeSize;
261 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
262 BlockScope.pop_back();
265 //===--------------------------------------------------------------------===//
267 //===--------------------------------------------------------------------===//
270 /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
271 /// record. This is a no-op, since the abbrev specifies the literal to use.
272 template<typename uintty>
273 void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
274 assert(Op.isLiteral() && "Not a literal");
275 // If the abbrev specifies the literal value to use, don't emit
277 assert(V == Op.getLiteralValue() &&
278 "Invalid abbrev for record!");
281 /// EmitAbbreviatedField - Emit a single scalar field value with the specified
283 template<typename uintty>
284 void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
285 assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
287 // Encode the value as we are commanded.
288 switch (Op.getEncoding()) {
289 default: llvm_unreachable("Unknown encoding!");
290 case BitCodeAbbrevOp::Fixed:
291 if (Op.getEncodingData())
292 Emit((unsigned)V, (unsigned)Op.getEncodingData());
294 case BitCodeAbbrevOp::VBR:
295 if (Op.getEncodingData())
296 EmitVBR64(V, (unsigned)Op.getEncodingData());
298 case BitCodeAbbrevOp::Char6:
299 Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
304 /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
305 /// emission code. If BlobData is non-null, then it specifies an array of
306 /// data that should be emitted as part of the Blob or Array operand that is
307 /// known to exist at the end of the record.
308 template<typename uintty>
309 void EmitRecordWithAbbrevImpl(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
311 const char *BlobData = Blob.data();
312 unsigned BlobLen = (unsigned) Blob.size();
313 unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
314 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
315 BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
319 unsigned RecordIdx = 0;
320 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
322 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
323 if (Op.isLiteral()) {
324 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
325 EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
327 } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
329 assert(i+2 == e && "array op not second to last?");
330 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
332 // If this record has blob data, emit it, otherwise we must have record
333 // entries to encode this way.
335 assert(RecordIdx == Vals.size() &&
336 "Blob data and record entries specified for array!");
337 // Emit a vbr6 to indicate the number of elements present.
338 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
341 for (unsigned i = 0; i != BlobLen; ++i)
342 EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
344 // Know that blob data is consumed for assertion below.
347 // Emit a vbr6 to indicate the number of elements present.
348 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
351 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
352 EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
354 } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
355 // If this record has blob data, emit it, otherwise we must have record
356 // entries to encode this way.
358 // Emit a vbr6 to indicate the number of elements present.
360 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
361 assert(RecordIdx == Vals.size() &&
362 "Blob data and record entries specified for blob operand!");
364 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
367 // Flush to a 32-bit alignment boundary.
370 // Emit each field as a literal byte.
372 for (unsigned i = 0; i != BlobLen; ++i)
373 WriteByte((unsigned char)BlobData[i]);
375 // Know that blob data is consumed for assertion below.
378 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx) {
379 assert(Vals[RecordIdx] < 256 && "Value too large to emit as blob");
380 WriteByte((unsigned char)Vals[RecordIdx]);
384 // Align end to 32-bits.
385 while (GetBufferOffset() & 3)
387 } else { // Single scalar field.
388 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
389 EmitAbbreviatedField(Op, Vals[RecordIdx]);
393 assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
394 assert(BlobData == 0 &&
395 "Blob data specified for record that doesn't use it!");
400 /// EmitRecord - Emit the specified record to the stream, using an abbrev if
401 /// we have one to compress the output.
402 template<typename uintty>
403 void EmitRecord(unsigned Code, SmallVectorImpl<uintty> &Vals,
404 unsigned Abbrev = 0) {
406 // If we don't have an abbrev to use, emit this in its fully unabbreviated
408 EmitCode(bitc::UNABBREV_RECORD);
410 EmitVBR(static_cast<uint32_t>(Vals.size()), 6);
411 for (unsigned i = 0, e = static_cast<unsigned>(Vals.size()); i != e; ++i)
412 EmitVBR64(Vals[i], 6);
416 // Insert the code into Vals to treat it uniformly.
417 Vals.insert(Vals.begin(), Code);
419 EmitRecordWithAbbrev(Abbrev, Vals);
422 /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
423 /// Unlike EmitRecord, the code for the record should be included in Vals as
425 template<typename uintty>
426 void EmitRecordWithAbbrev(unsigned Abbrev, SmallVectorImpl<uintty> &Vals) {
427 EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef());
430 /// EmitRecordWithBlob - Emit the specified record to the stream, using an
431 /// abbrev that includes a blob at the end. The blob data to emit is
432 /// specified by the pointer and length specified at the end. In contrast to
433 /// EmitRecord, this routine expects that the first entry in Vals is the code
435 template<typename uintty>
436 void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
438 EmitRecordWithAbbrevImpl(Abbrev, Vals, Blob);
440 template<typename uintty>
441 void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
442 const char *BlobData, unsigned BlobLen) {
443 return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(BlobData, BlobLen));
446 /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
447 /// that end with an array.
448 template<typename uintty>
449 void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
451 EmitRecordWithAbbrevImpl(Abbrev, Vals, Array);
453 template<typename uintty>
454 void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
455 const char *ArrayData, unsigned ArrayLen) {
456 return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(ArrayData,
460 //===--------------------------------------------------------------------===//
462 //===--------------------------------------------------------------------===//
465 // Emit the abbreviation as a DEFINE_ABBREV record.
466 void EncodeAbbrev(BitCodeAbbrev *Abbv) {
467 EmitCode(bitc::DEFINE_ABBREV);
468 EmitVBR(Abbv->getNumOperandInfos(), 5);
469 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
471 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
472 Emit(Op.isLiteral(), 1);
473 if (Op.isLiteral()) {
474 EmitVBR64(Op.getLiteralValue(), 8);
476 Emit(Op.getEncoding(), 3);
477 if (Op.hasEncodingData())
478 EmitVBR64(Op.getEncodingData(), 5);
484 /// EmitAbbrev - This emits an abbreviation to the stream. Note that this
485 /// method takes ownership of the specified abbrev.
486 unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
487 // Emit the abbreviation as a record.
489 CurAbbrevs.push_back(Abbv);
490 return static_cast<unsigned>(CurAbbrevs.size())-1 +
491 bitc::FIRST_APPLICATION_ABBREV;
494 //===--------------------------------------------------------------------===//
495 // BlockInfo Block Emission
496 //===--------------------------------------------------------------------===//
498 /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
499 void EnterBlockInfoBlock(unsigned CodeWidth) {
500 EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
501 BlockInfoCurBID = -1U;
504 /// SwitchToBlockID - If we aren't already talking about the specified block
505 /// ID, emit a BLOCKINFO_CODE_SETBID record.
506 void SwitchToBlockID(unsigned BlockID) {
507 if (BlockInfoCurBID == BlockID) return;
508 SmallVector<unsigned, 2> V;
509 V.push_back(BlockID);
510 EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
511 BlockInfoCurBID = BlockID;
514 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
515 if (BlockInfo *BI = getBlockInfo(BlockID))
518 // Otherwise, add a new record.
519 BlockInfoRecords.push_back(BlockInfo());
520 BlockInfoRecords.back().BlockID = BlockID;
521 return BlockInfoRecords.back();
526 /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
528 unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
529 SwitchToBlockID(BlockID);
532 // Add the abbrev to the specified block record.
533 BlockInfo &Info = getOrCreateBlockInfo(BlockID);
534 Info.Abbrevs.push_back(Abbv);
536 return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
541 } // End llvm namespace