Removed trailing whitespace.
[oota-llvm.git] / include / llvm / Bitcode / BitstreamWriter.h
1 //===- BitstreamWriter.h - Low-level bitstream writer interface -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This header defines the BitstreamWriter class.  This class can be used to
11 // write an arbitrary bitstream, regardless of its contents.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef BITSTREAM_WRITER_H
16 #define BITSTREAM_WRITER_H
17
18 #include "llvm/Bitcode/BitCodes.h"
19 #include <vector>
20
21 namespace llvm {
22
23 class BitstreamWriter {
24   std::vector<unsigned char> &Out;
25
26   /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
27   unsigned CurBit;
28
29   /// CurValue - The current value.  Only bits < CurBit are valid.
30   uint32_t CurValue;
31
32   /// CurCodeSize - This is the declared size of code values used for the
33   /// current block, in bits.
34   unsigned CurCodeSize;
35
36   /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
37   /// selected BLOCK ID.
38   unsigned BlockInfoCurBID;
39
40   /// CurAbbrevs - Abbrevs installed at in this block.
41   std::vector<BitCodeAbbrev*> CurAbbrevs;
42
43   struct Block {
44     unsigned PrevCodeSize;
45     unsigned StartSizeWord;
46     std::vector<BitCodeAbbrev*> PrevAbbrevs;
47     Block(unsigned PCS, unsigned SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
48   };
49
50   /// BlockScope - This tracks the current blocks that we have entered.
51   std::vector<Block> BlockScope;
52
53   /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
54   /// These describe abbreviations that all blocks of the specified ID inherit.
55   struct BlockInfo {
56     unsigned BlockID;
57     std::vector<BitCodeAbbrev*> Abbrevs;
58   };
59   std::vector<BlockInfo> BlockInfoRecords;
60
61 public:
62   explicit BitstreamWriter(std::vector<unsigned char> &O)
63     : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
64
65   ~BitstreamWriter() {
66     assert(CurBit == 0 && "Unflused data remaining");
67     assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
68
69     // Free the BlockInfoRecords.
70     while (!BlockInfoRecords.empty()) {
71       BlockInfo &Info = BlockInfoRecords.back();
72       // Free blockinfo abbrev info.
73       for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
74            i != e; ++i)
75         Info.Abbrevs[i]->dropRef();
76       BlockInfoRecords.pop_back();
77     }
78   }
79
80   std::vector<unsigned char> &getBuffer() { return Out; }
81
82   //===--------------------------------------------------------------------===//
83   // Basic Primitives for emitting bits to the stream.
84   //===--------------------------------------------------------------------===//
85
86   void Emit(uint32_t Val, unsigned NumBits) {
87     assert(NumBits <= 32 && "Invalid value size!");
88     assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
89     CurValue |= Val << CurBit;
90     if (CurBit + NumBits < 32) {
91       CurBit += NumBits;
92       return;
93     }
94
95     // Add the current word.
96     unsigned V = CurValue;
97     Out.push_back((unsigned char)(V >>  0));
98     Out.push_back((unsigned char)(V >>  8));
99     Out.push_back((unsigned char)(V >> 16));
100     Out.push_back((unsigned char)(V >> 24));
101
102     if (CurBit)
103       CurValue = Val >> (32-CurBit);
104     else
105       CurValue = 0;
106     CurBit = (CurBit+NumBits) & 31;
107   }
108
109   void Emit64(uint64_t Val, unsigned NumBits) {
110     if (NumBits <= 32)
111       Emit((uint32_t)Val, NumBits);
112     else {
113       Emit((uint32_t)Val, 32);
114       Emit((uint32_t)(Val >> 32), NumBits-32);
115     }
116   }
117
118   void FlushToWord() {
119     if (CurBit) {
120       unsigned V = CurValue;
121       Out.push_back((unsigned char)(V >>  0));
122       Out.push_back((unsigned char)(V >>  8));
123       Out.push_back((unsigned char)(V >> 16));
124       Out.push_back((unsigned char)(V >> 24));
125       CurBit = 0;
126       CurValue = 0;
127     }
128   }
129
130   void EmitVBR(uint32_t Val, unsigned NumBits) {
131     uint32_t Threshold = 1U << (NumBits-1);
132
133     // Emit the bits with VBR encoding, NumBits-1 bits at a time.
134     while (Val >= Threshold) {
135       Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
136       Val >>= NumBits-1;
137     }
138
139     Emit(Val, NumBits);
140   }
141
142   void EmitVBR64(uint64_t Val, unsigned NumBits) {
143     if ((uint32_t)Val == Val)
144       return EmitVBR((uint32_t)Val, NumBits);
145
146     uint64_t Threshold = 1U << (NumBits-1);
147
148     // Emit the bits with VBR encoding, NumBits-1 bits at a time.
149     while (Val >= Threshold) {
150       Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
151            (1 << (NumBits-1)), NumBits);
152       Val >>= NumBits-1;
153     }
154
155     Emit((uint32_t)Val, NumBits);
156   }
157
158   /// EmitCode - Emit the specified code.
159   void EmitCode(unsigned Val) {
160     Emit(Val, CurCodeSize);
161   }
162
163   // BackpatchWord - Backpatch a 32-bit word in the output with the specified
164   // value.
165   void BackpatchWord(unsigned ByteNo, unsigned NewWord) {
166     Out[ByteNo++] = (unsigned char)(NewWord >>  0);
167     Out[ByteNo++] = (unsigned char)(NewWord >>  8);
168     Out[ByteNo++] = (unsigned char)(NewWord >> 16);
169     Out[ByteNo  ] = (unsigned char)(NewWord >> 24);
170   }
171
172   //===--------------------------------------------------------------------===//
173   // Block Manipulation
174   //===--------------------------------------------------------------------===//
175
176   /// getBlockInfo - If there is block info for the specified ID, return it,
177   /// otherwise return null.
178   BlockInfo *getBlockInfo(unsigned BlockID) {
179     // Common case, the most recent entry matches BlockID.
180     if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
181       return &BlockInfoRecords.back();
182
183     for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
184          i != e; ++i)
185       if (BlockInfoRecords[i].BlockID == BlockID)
186         return &BlockInfoRecords[i];
187     return 0;
188   }
189
190   void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
191     // Block header:
192     //    [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
193     EmitCode(bitc::ENTER_SUBBLOCK);
194     EmitVBR(BlockID, bitc::BlockIDWidth);
195     EmitVBR(CodeLen, bitc::CodeLenWidth);
196     FlushToWord();
197
198     unsigned BlockSizeWordLoc = static_cast<unsigned>(Out.size());
199     unsigned OldCodeSize = CurCodeSize;
200
201     // Emit a placeholder, which will be replaced when the block is popped.
202     Emit(0, bitc::BlockSizeWidth);
203
204     CurCodeSize = CodeLen;
205
206     // Push the outer block's abbrev set onto the stack, start out with an
207     // empty abbrev set.
208     BlockScope.push_back(Block(OldCodeSize, BlockSizeWordLoc/4));
209     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
210
211     // If there is a blockinfo for this BlockID, add all the predefined abbrevs
212     // to the abbrev list.
213     if (BlockInfo *Info = getBlockInfo(BlockID)) {
214       for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
215            i != e; ++i) {
216         CurAbbrevs.push_back(Info->Abbrevs[i]);
217         Info->Abbrevs[i]->addRef();
218       }
219     }
220   }
221
222   void ExitBlock() {
223     assert(!BlockScope.empty() && "Block scope imbalance!");
224
225     // Delete all abbrevs.
226     for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
227          i != e; ++i)
228       CurAbbrevs[i]->dropRef();
229
230     const Block &B = BlockScope.back();
231
232     // Block tail:
233     //    [END_BLOCK, <align4bytes>]
234     EmitCode(bitc::END_BLOCK);
235     FlushToWord();
236
237     // Compute the size of the block, in words, not counting the size field.
238     unsigned SizeInWords= static_cast<unsigned>(Out.size())/4-B.StartSizeWord-1;
239     unsigned ByteNo = B.StartSizeWord*4;
240
241     // Update the block size field in the header of this sub-block.
242     BackpatchWord(ByteNo, SizeInWords);
243
244     // Restore the inner block's code size and abbrev table.
245     CurCodeSize = B.PrevCodeSize;
246     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
247     BlockScope.pop_back();
248   }
249
250   //===--------------------------------------------------------------------===//
251   // Record Emission
252   //===--------------------------------------------------------------------===//
253
254 private:
255   /// EmitAbbreviatedField - Emit a single scalar field value with the specified
256   /// encoding.
257   template<typename uintty>
258   void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
259     if (Op.isLiteral()) {
260       // If the abbrev specifies the literal value to use, don't emit
261       // anything.
262       assert(V == Op.getLiteralValue() &&
263              "Invalid abbrev for record!");
264       return;
265     }
266
267     // Encode the value as we are commanded.
268     switch (Op.getEncoding()) {
269     default: assert(0 && "Unknown encoding!");
270     case BitCodeAbbrevOp::Fixed:
271       Emit((unsigned)V, (unsigned)Op.getEncodingData());
272       break;
273     case BitCodeAbbrevOp::VBR:
274       EmitVBR64(V, (unsigned)Op.getEncodingData());
275       break;
276     case BitCodeAbbrevOp::Char6:
277       Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
278       break;
279     }
280   }
281 public:
282
283   /// EmitRecord - Emit the specified record to the stream, using an abbrev if
284   /// we have one to compress the output.
285   template<typename uintty>
286   void EmitRecord(unsigned Code, SmallVectorImpl<uintty> &Vals,
287                   unsigned Abbrev = 0) {
288     if (Abbrev) {
289       unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
290       assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
291       BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
292
293       EmitCode(Abbrev);
294
295       // Insert the code into Vals to treat it uniformly.
296       Vals.insert(Vals.begin(), Code);
297
298       unsigned RecordIdx = 0;
299       for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
300            i != e; ++i) {
301         const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
302         if (Op.isLiteral() || Op.getEncoding() != BitCodeAbbrevOp::Array) {
303           assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
304           EmitAbbreviatedField(Op, Vals[RecordIdx]);
305           ++RecordIdx;
306         } else {
307           // Array case.
308           assert(i+2 == e && "array op not second to last?");
309           const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
310
311           // Emit a vbr6 to indicate the number of elements present.
312           EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
313
314           // Emit each field.
315           for (; RecordIdx != Vals.size(); ++RecordIdx)
316             EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
317         }
318       }
319       assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
320     } else {
321       // If we don't have an abbrev to use, emit this in its fully unabbreviated
322       // form.
323       EmitCode(bitc::UNABBREV_RECORD);
324       EmitVBR(Code, 6);
325       EmitVBR(static_cast<uint32_t>(Vals.size()), 6);
326       for (unsigned i = 0, e = static_cast<unsigned>(Vals.size()); i != e; ++i)
327         EmitVBR64(Vals[i], 6);
328     }
329   }
330
331   //===--------------------------------------------------------------------===//
332   // Abbrev Emission
333   //===--------------------------------------------------------------------===//
334
335 private:
336   // Emit the abbreviation as a DEFINE_ABBREV record.
337   void EncodeAbbrev(BitCodeAbbrev *Abbv) {
338     EmitCode(bitc::DEFINE_ABBREV);
339     EmitVBR(Abbv->getNumOperandInfos(), 5);
340     for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
341          i != e; ++i) {
342       const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
343       Emit(Op.isLiteral(), 1);
344       if (Op.isLiteral()) {
345         EmitVBR64(Op.getLiteralValue(), 8);
346       } else {
347         Emit(Op.getEncoding(), 3);
348         if (Op.hasEncodingData())
349           EmitVBR64(Op.getEncodingData(), 5);
350       }
351     }
352   }
353 public:
354
355   /// EmitAbbrev - This emits an abbreviation to the stream.  Note that this
356   /// method takes ownership of the specified abbrev.
357   unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
358     // Emit the abbreviation as a record.
359     EncodeAbbrev(Abbv);
360     CurAbbrevs.push_back(Abbv);
361     return static_cast<unsigned>(CurAbbrevs.size())-1 +
362       bitc::FIRST_APPLICATION_ABBREV;
363   }
364
365   //===--------------------------------------------------------------------===//
366   // BlockInfo Block Emission
367   //===--------------------------------------------------------------------===//
368
369   /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
370   void EnterBlockInfoBlock(unsigned CodeWidth) {
371     EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
372     BlockInfoCurBID = -1U;
373   }
374 private:
375   /// SwitchToBlockID - If we aren't already talking about the specified block
376   /// ID, emit a BLOCKINFO_CODE_SETBID record.
377   void SwitchToBlockID(unsigned BlockID) {
378     if (BlockInfoCurBID == BlockID) return;
379     SmallVector<unsigned, 2> V;
380     V.push_back(BlockID);
381     EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
382     BlockInfoCurBID = BlockID;
383   }
384
385   BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
386     if (BlockInfo *BI = getBlockInfo(BlockID))
387       return *BI;
388
389     // Otherwise, add a new record.
390     BlockInfoRecords.push_back(BlockInfo());
391     BlockInfoRecords.back().BlockID = BlockID;
392     return BlockInfoRecords.back();
393   }
394
395 public:
396
397   /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
398   /// BlockID.
399   unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
400     SwitchToBlockID(BlockID);
401     EncodeAbbrev(Abbv);
402
403     // Add the abbrev to the specified block record.
404     BlockInfo &Info = getOrCreateBlockInfo(BlockID);
405     Info.Abbrevs.push_back(Abbv);
406
407     return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
408   }
409 };
410
411
412 } // End llvm namespace
413
414 #endif