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/Bitcode/BitCodes.h"
23 class BitstreamWriter {
24 std::vector<unsigned char> &Out;
26 /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
29 /// CurValue - The current value. Only bits < CurBit are valid.
32 /// CurCodeSize - This is the declared size of code values used for the
33 /// current block, in bits.
36 /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
37 /// selected BLOCK ID.
38 unsigned BlockInfoCurBID;
40 /// CurAbbrevs - Abbrevs installed at in this block.
41 std::vector<BitCodeAbbrev*> CurAbbrevs;
44 unsigned PrevCodeSize;
45 unsigned StartSizeWord;
46 std::vector<BitCodeAbbrev*> PrevAbbrevs;
47 Block(unsigned PCS, unsigned SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
50 /// BlockScope - This tracks the current blocks that we have entered.
51 std::vector<Block> BlockScope;
53 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
54 /// These describe abbreviations that all blocks of the specified ID inherit.
57 std::vector<BitCodeAbbrev*> Abbrevs;
59 std::vector<BlockInfo> BlockInfoRecords;
62 explicit BitstreamWriter(std::vector<unsigned char> &O)
63 : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
66 assert(CurBit == 0 && "Unflused data remaining");
67 assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
69 // Free the BlockInfoRecords.
70 while (!BlockInfoRecords.empty()) {
71 BlockInfo &Info = BlockInfoRecords.back();
72 // Free blockinfo abbrev info.
73 for (unsigned i = 0, e = Info.Abbrevs.size(); i != e; ++i)
74 Info.Abbrevs[i]->dropRef();
75 BlockInfoRecords.pop_back();
78 //===--------------------------------------------------------------------===//
79 // Basic Primitives for emitting bits to the stream.
80 //===--------------------------------------------------------------------===//
82 void Emit(uint32_t Val, unsigned NumBits) {
83 assert(NumBits <= 32 && "Invalid value size!");
84 assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
85 CurValue |= Val << CurBit;
86 if (CurBit + NumBits < 32) {
91 // Add the current word.
92 unsigned V = CurValue;
93 Out.push_back((unsigned char)(V >> 0));
94 Out.push_back((unsigned char)(V >> 8));
95 Out.push_back((unsigned char)(V >> 16));
96 Out.push_back((unsigned char)(V >> 24));
99 CurValue = Val >> (32-CurBit);
102 CurBit = (CurBit+NumBits) & 31;
105 void Emit64(uint64_t Val, unsigned NumBits) {
107 Emit((uint32_t)Val, NumBits);
109 Emit((uint32_t)Val, 32);
110 Emit((uint32_t)(Val >> 32), NumBits-32);
116 unsigned V = CurValue;
117 Out.push_back((unsigned char)(V >> 0));
118 Out.push_back((unsigned char)(V >> 8));
119 Out.push_back((unsigned char)(V >> 16));
120 Out.push_back((unsigned char)(V >> 24));
126 void EmitVBR(uint32_t Val, unsigned NumBits) {
127 uint32_t Threshold = 1U << (NumBits-1);
129 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
130 while (Val >= Threshold) {
131 Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
138 void EmitVBR64(uint64_t Val, unsigned NumBits) {
139 if ((uint32_t)Val == Val)
140 return EmitVBR((uint32_t)Val, NumBits);
142 uint64_t Threshold = 1U << (NumBits-1);
144 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
145 while (Val >= Threshold) {
146 Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
147 (1 << (NumBits-1)), NumBits);
151 Emit((uint32_t)Val, NumBits);
154 /// EmitCode - Emit the specified code.
155 void EmitCode(unsigned Val) {
156 Emit(Val, CurCodeSize);
159 //===--------------------------------------------------------------------===//
160 // Block Manipulation
161 //===--------------------------------------------------------------------===//
163 /// getBlockInfo - If there is block info for the specified ID, return it,
164 /// otherwise return null.
165 BlockInfo *getBlockInfo(unsigned BlockID) {
166 // Common case, the most recent entry matches BlockID.
167 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
168 return &BlockInfoRecords.back();
170 for (unsigned i = 0, e = BlockInfoRecords.size(); i != e; ++i)
171 if (BlockInfoRecords[i].BlockID == BlockID)
172 return &BlockInfoRecords[i];
176 void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
178 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
179 EmitCode(bitc::ENTER_SUBBLOCK);
180 EmitVBR(BlockID, bitc::BlockIDWidth);
181 EmitVBR(CodeLen, bitc::CodeLenWidth);
184 unsigned BlockSizeWordLoc = Out.size();
185 unsigned OldCodeSize = CurCodeSize;
187 // Emit a placeholder, which will be replaced when the block is popped.
188 Emit(0, bitc::BlockSizeWidth);
190 CurCodeSize = CodeLen;
192 // Push the outer block's abbrev set onto the stack, start out with an
194 BlockScope.push_back(Block(OldCodeSize, BlockSizeWordLoc/4));
195 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
197 // If there is a blockinfo for this BlockID, add all the predefined abbrevs
198 // to the abbrev list.
199 if (BlockInfo *Info = getBlockInfo(BlockID)) {
200 for (unsigned i = 0, e = Info->Abbrevs.size(); i != e; ++i) {
201 CurAbbrevs.push_back(Info->Abbrevs[i]);
202 Info->Abbrevs[i]->addRef();
208 assert(!BlockScope.empty() && "Block scope imbalance!");
210 // Delete all abbrevs.
211 for (unsigned i = 0, e = CurAbbrevs.size(); i != e; ++i)
212 CurAbbrevs[i]->dropRef();
214 const Block &B = BlockScope.back();
217 // [END_BLOCK, <align4bytes>]
218 EmitCode(bitc::END_BLOCK);
221 // Compute the size of the block, in words, not counting the size field.
222 unsigned SizeInWords = Out.size()/4-B.StartSizeWord - 1;
223 unsigned ByteNo = B.StartSizeWord*4;
225 // Update the block size field in the header of this sub-block.
226 Out[ByteNo++] = (unsigned char)(SizeInWords >> 0);
227 Out[ByteNo++] = (unsigned char)(SizeInWords >> 8);
228 Out[ByteNo++] = (unsigned char)(SizeInWords >> 16);
229 Out[ByteNo++] = (unsigned char)(SizeInWords >> 24);
231 // Restore the inner block's code size and abbrev table.
232 CurCodeSize = B.PrevCodeSize;
233 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
234 BlockScope.pop_back();
237 //===--------------------------------------------------------------------===//
239 //===--------------------------------------------------------------------===//
242 /// EmitAbbreviatedField - Emit a single scalar field value with the specified
244 template<typename uintty>
245 void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
246 if (Op.isLiteral()) {
247 // If the abbrev specifies the literal value to use, don't emit
249 assert(V == Op.getLiteralValue() &&
250 "Invalid abbrev for record!");
254 // Encode the value as we are commanded.
255 switch (Op.getEncoding()) {
256 default: assert(0 && "Unknown encoding!");
257 case BitCodeAbbrevOp::Fixed:
258 Emit((unsigned)V, (unsigned)Op.getEncodingData());
260 case BitCodeAbbrevOp::VBR:
261 EmitVBR64(V, (unsigned)Op.getEncodingData());
263 case BitCodeAbbrevOp::Char6:
264 Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
270 /// EmitRecord - Emit the specified record to the stream, using an abbrev if
271 /// we have one to compress the output.
272 template<typename uintty>
273 void EmitRecord(unsigned Code, SmallVectorImpl<uintty> &Vals,
274 unsigned Abbrev = 0) {
276 unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
277 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
278 BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
282 // Insert the code into Vals to treat it uniformly.
283 Vals.insert(Vals.begin(), Code);
285 unsigned RecordIdx = 0;
286 for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
287 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
288 if (Op.isLiteral() || Op.getEncoding() != BitCodeAbbrevOp::Array) {
289 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
290 EmitAbbreviatedField(Op, Vals[RecordIdx]);
294 assert(i+2 == e && "array op not second to last?");
295 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
297 // Emit a vbr6 to indicate the number of elements present.
298 EmitVBR(Vals.size()-RecordIdx, 6);
301 for (; RecordIdx != Vals.size(); ++RecordIdx)
302 EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
305 assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
307 // If we don't have an abbrev to use, emit this in its fully unabbreviated
309 EmitCode(bitc::UNABBREV_RECORD);
311 EmitVBR(Vals.size(), 6);
312 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
313 EmitVBR64(Vals[i], 6);
317 //===--------------------------------------------------------------------===//
319 //===--------------------------------------------------------------------===//
322 // Emit the abbreviation as a DEFINE_ABBREV record.
323 void EncodeAbbrev(BitCodeAbbrev *Abbv) {
324 EmitCode(bitc::DEFINE_ABBREV);
325 EmitVBR(Abbv->getNumOperandInfos(), 5);
326 for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
327 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
328 Emit(Op.isLiteral(), 1);
329 if (Op.isLiteral()) {
330 EmitVBR64(Op.getLiteralValue(), 8);
332 Emit(Op.getEncoding(), 3);
333 if (Op.hasEncodingData())
334 EmitVBR64(Op.getEncodingData(), 5);
340 /// EmitAbbrev - This emits an abbreviation to the stream. Note that this
341 /// method takes ownership of the specified abbrev.
342 unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
343 // Emit the abbreviation as a record.
345 CurAbbrevs.push_back(Abbv);
346 return CurAbbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
349 //===--------------------------------------------------------------------===//
350 // BlockInfo Block Emission
351 //===--------------------------------------------------------------------===//
353 /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
354 void EnterBlockInfoBlock(unsigned CodeWidth) {
355 EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
356 BlockInfoCurBID = -1U;
359 /// SwitchToBlockID - If we aren't already talking about the specified block
360 /// ID, emit a BLOCKINFO_CODE_SETBID record.
361 void SwitchToBlockID(unsigned BlockID) {
362 if (BlockInfoCurBID == BlockID) return;
363 SmallVector<unsigned, 2> V;
364 V.push_back(BlockID);
365 EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
366 BlockInfoCurBID = BlockID;
369 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
370 if (BlockInfo *BI = getBlockInfo(BlockID))
373 // Otherwise, add a new record.
374 BlockInfoRecords.push_back(BlockInfo());
375 BlockInfoRecords.back().BlockID = BlockID;
376 return BlockInfoRecords.back();
381 /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
383 unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
384 SwitchToBlockID(BlockID);
387 // Add the abbrev to the specified block record.
388 BlockInfo &Info = getOrCreateBlockInfo(BlockID);
389 Info.Abbrevs.push_back(Abbv);
391 return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
396 } // End llvm namespace