Fix windows compilation warning. Patch by Micah.
[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/ADT/StringRef.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Bitcode/BitCodes.h"
21 #include <vector>
22
23 namespace llvm {
24
25 class BitstreamWriter {
26   SmallVectorImpl<char> &Out;
27
28   /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
29   unsigned CurBit;
30
31   /// CurValue - The current value.  Only bits < CurBit are valid.
32   uint32_t CurValue;
33
34   /// CurCodeSize - This is the declared size of code values used for the
35   /// current block, in bits.
36   unsigned CurCodeSize;
37
38   /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
39   /// selected BLOCK ID.
40   unsigned BlockInfoCurBID;
41
42   /// CurAbbrevs - Abbrevs installed at in this block.
43   std::vector<BitCodeAbbrev*> CurAbbrevs;
44
45   struct Block {
46     unsigned PrevCodeSize;
47     unsigned StartSizeWord;
48     std::vector<BitCodeAbbrev*> PrevAbbrevs;
49     Block(unsigned PCS, unsigned SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
50   };
51
52   /// BlockScope - This tracks the current blocks that we have entered.
53   std::vector<Block> BlockScope;
54
55   /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
56   /// These describe abbreviations that all blocks of the specified ID inherit.
57   struct BlockInfo {
58     unsigned BlockID;
59     std::vector<BitCodeAbbrev*> Abbrevs;
60   };
61   std::vector<BlockInfo> BlockInfoRecords;
62
63   // BackpatchWord - Backpatch a 32-bit word in the output with the specified
64   // value.
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);
70   }
71
72   void WriteByte(unsigned char Value) {
73     Out.push_back(Value);
74   }
75
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]);
83   }
84
85   unsigned GetBufferOffset() const {
86     return Out.size();
87   }
88
89   unsigned GetWordIndex() const {
90     unsigned Offset = GetBufferOffset();
91     assert((Offset & 3) == 0 && "Not 32-bit aligned");
92     return Offset / 4;
93   }
94
95 public:
96   explicit BitstreamWriter(SmallVectorImpl<char> &O)
97     : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
98
99   ~BitstreamWriter() {
100     assert(CurBit == 0 && "Unflused data remaining");
101     assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
102
103     // Free the BlockInfoRecords.
104     while (!BlockInfoRecords.empty()) {
105       BlockInfo &Info = BlockInfoRecords.back();
106       // Free blockinfo abbrev info.
107       for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
108            i != e; ++i)
109         Info.Abbrevs[i]->dropRef();
110       BlockInfoRecords.pop_back();
111     }
112   }
113
114   /// \brief Retrieve the current position in the stream, in bits.
115   uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; }
116
117   //===--------------------------------------------------------------------===//
118   // Basic Primitives for emitting bits to the stream.
119   //===--------------------------------------------------------------------===//
120
121   void Emit(uint32_t Val, unsigned NumBits) {
122     assert(NumBits && NumBits <= 32 && "Invalid value size!");
123     assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
124     CurValue |= Val << CurBit;
125     if (CurBit + NumBits < 32) {
126       CurBit += NumBits;
127       return;
128     }
129
130     // Add the current word.
131     WriteWord(CurValue);
132
133     if (CurBit)
134       CurValue = Val >> (32-CurBit);
135     else
136       CurValue = 0;
137     CurBit = (CurBit+NumBits) & 31;
138   }
139
140   void Emit64(uint64_t Val, unsigned NumBits) {
141     if (NumBits <= 32)
142       Emit((uint32_t)Val, NumBits);
143     else {
144       Emit((uint32_t)Val, 32);
145       Emit((uint32_t)(Val >> 32), NumBits-32);
146     }
147   }
148
149   void FlushToWord() {
150     if (CurBit) {
151       WriteWord(CurValue);
152       CurBit = 0;
153       CurValue = 0;
154     }
155   }
156
157   void EmitVBR(uint32_t Val, unsigned NumBits) {
158     uint32_t Threshold = 1U << (NumBits-1);
159
160     // Emit the bits with VBR encoding, NumBits-1 bits at a time.
161     while (Val >= Threshold) {
162       Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
163       Val >>= NumBits-1;
164     }
165
166     Emit(Val, NumBits);
167   }
168
169   void EmitVBR64(uint64_t Val, unsigned NumBits) {
170     if ((uint32_t)Val == Val)
171       return EmitVBR((uint32_t)Val, NumBits);
172
173     uint64_t Threshold = 1U << (NumBits-1);
174
175     // Emit the bits with VBR encoding, NumBits-1 bits at a time.
176     while (Val >= Threshold) {
177       Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
178            (1 << (NumBits-1)), NumBits);
179       Val >>= NumBits-1;
180     }
181
182     Emit((uint32_t)Val, NumBits);
183   }
184
185   /// EmitCode - Emit the specified code.
186   void EmitCode(unsigned Val) {
187     Emit(Val, CurCodeSize);
188   }
189
190   //===--------------------------------------------------------------------===//
191   // Block Manipulation
192   //===--------------------------------------------------------------------===//
193
194   /// getBlockInfo - If there is block info for the specified ID, return it,
195   /// otherwise return null.
196   BlockInfo *getBlockInfo(unsigned BlockID) {
197     // Common case, the most recent entry matches BlockID.
198     if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
199       return &BlockInfoRecords.back();
200
201     for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
202          i != e; ++i)
203       if (BlockInfoRecords[i].BlockID == BlockID)
204         return &BlockInfoRecords[i];
205     return 0;
206   }
207
208   void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
209     // Block header:
210     //    [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
211     EmitCode(bitc::ENTER_SUBBLOCK);
212     EmitVBR(BlockID, bitc::BlockIDWidth);
213     EmitVBR(CodeLen, bitc::CodeLenWidth);
214     FlushToWord();
215
216     unsigned BlockSizeWordIndex = GetWordIndex();
217     unsigned OldCodeSize = CurCodeSize;
218
219     // Emit a placeholder, which will be replaced when the block is popped.
220     Emit(0, bitc::BlockSizeWidth);
221
222     CurCodeSize = CodeLen;
223
224     // Push the outer block's abbrev set onto the stack, start out with an
225     // empty abbrev set.
226     BlockScope.push_back(Block(OldCodeSize, BlockSizeWordIndex));
227     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
228
229     // If there is a blockinfo for this BlockID, add all the predefined abbrevs
230     // to the abbrev list.
231     if (BlockInfo *Info = getBlockInfo(BlockID)) {
232       for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
233            i != e; ++i) {
234         CurAbbrevs.push_back(Info->Abbrevs[i]);
235         Info->Abbrevs[i]->addRef();
236       }
237     }
238   }
239
240   void ExitBlock() {
241     assert(!BlockScope.empty() && "Block scope imbalance!");
242
243     // Delete all abbrevs.
244     for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
245          i != e; ++i)
246       CurAbbrevs[i]->dropRef();
247
248     const Block &B = BlockScope.back();
249
250     // Block tail:
251     //    [END_BLOCK, <align4bytes>]
252     EmitCode(bitc::END_BLOCK);
253     FlushToWord();
254
255     // Compute the size of the block, in words, not counting the size field.
256     unsigned SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
257     unsigned ByteNo = B.StartSizeWord*4;
258
259     // Update the block size field in the header of this sub-block.
260     BackpatchWord(ByteNo, SizeInWords);
261
262     // Restore the inner block's code size and abbrev table.
263     CurCodeSize = B.PrevCodeSize;
264     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
265     BlockScope.pop_back();
266   }
267
268   //===--------------------------------------------------------------------===//
269   // Record Emission
270   //===--------------------------------------------------------------------===//
271
272 private:
273   /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
274   /// record.  This is a no-op, since the abbrev specifies the literal to use. 
275   template<typename uintty>
276   void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
277     assert(Op.isLiteral() && "Not a literal");
278     // If the abbrev specifies the literal value to use, don't emit
279     // anything.
280     assert(V == Op.getLiteralValue() &&
281            "Invalid abbrev for record!");
282   }
283   
284   /// EmitAbbreviatedField - Emit a single scalar field value with the specified
285   /// encoding.
286   template<typename uintty>
287   void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
288     assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
289     
290     // Encode the value as we are commanded.
291     switch (Op.getEncoding()) {
292     default: llvm_unreachable("Unknown encoding!");
293     case BitCodeAbbrevOp::Fixed:
294       if (Op.getEncodingData())
295         Emit((unsigned)V, (unsigned)Op.getEncodingData());
296       break;
297     case BitCodeAbbrevOp::VBR:
298       if (Op.getEncodingData())
299         EmitVBR64(V, (unsigned)Op.getEncodingData());
300       break;
301     case BitCodeAbbrevOp::Char6:
302       Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
303       break;
304     }
305   }
306   
307   /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
308   /// emission code.  If BlobData is non-null, then it specifies an array of
309   /// data that should be emitted as part of the Blob or Array operand that is
310   /// known to exist at the end of the record.
311   template<typename uintty>
312   void EmitRecordWithAbbrevImpl(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
313                                 StringRef Blob) {
314     const char *BlobData = Blob.data();
315     unsigned BlobLen = (unsigned) Blob.size();
316     unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
317     assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
318     BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
319
320     EmitCode(Abbrev);
321
322     unsigned RecordIdx = 0;
323     for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
324          i != e; ++i) {
325       const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
326       if (Op.isLiteral()) {
327         assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
328         EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
329         ++RecordIdx;
330       } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
331         // Array case.
332         assert(i+2 == e && "array op not second to last?");
333         const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
334
335         // If this record has blob data, emit it, otherwise we must have record
336         // entries to encode this way.
337         if (BlobData) {
338           assert(RecordIdx == Vals.size() &&
339                  "Blob data and record entries specified for array!");
340           // Emit a vbr6 to indicate the number of elements present.
341           EmitVBR(static_cast<uint32_t>(BlobLen), 6);
342           
343           // Emit each field.
344           for (unsigned i = 0; i != BlobLen; ++i)
345             EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
346           
347           // Know that blob data is consumed for assertion below.
348           BlobData = 0;
349         } else {
350           // Emit a vbr6 to indicate the number of elements present.
351           EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
352
353           // Emit each field.
354           for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
355             EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
356         }
357       } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
358         // If this record has blob data, emit it, otherwise we must have record
359         // entries to encode this way.
360         
361         // Emit a vbr6 to indicate the number of elements present.
362         if (BlobData) {
363           EmitVBR(static_cast<uint32_t>(BlobLen), 6);
364           assert(RecordIdx == Vals.size() &&
365                  "Blob data and record entries specified for blob operand!");
366         } else {
367           EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
368         }
369         
370         // Flush to a 32-bit alignment boundary.
371         FlushToWord();
372
373         // Emit each field as a literal byte.
374         if (BlobData) {
375           for (unsigned i = 0; i != BlobLen; ++i)
376             WriteByte((unsigned char)BlobData[i]);
377           
378           // Know that blob data is consumed for assertion below.
379           BlobData = 0;
380         } else {
381           for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx) {
382             assert(Vals[RecordIdx] < 256 && "Value too large to emit as blob");
383             WriteByte((unsigned char)Vals[RecordIdx]);
384           }
385         }
386
387         // Align end to 32-bits.
388         while (GetBufferOffset() & 3)
389           WriteByte(0);
390       } else {  // Single scalar field.
391         assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
392         EmitAbbreviatedField(Op, Vals[RecordIdx]);
393         ++RecordIdx;
394       }
395     }
396     assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
397     assert(BlobData == 0 &&
398            "Blob data specified for record that doesn't use it!");
399   }
400   
401 public:
402
403   /// EmitRecord - Emit the specified record to the stream, using an abbrev if
404   /// we have one to compress the output.
405   template<typename uintty>
406   void EmitRecord(unsigned Code, SmallVectorImpl<uintty> &Vals,
407                   unsigned Abbrev = 0) {
408     if (!Abbrev) {
409       // If we don't have an abbrev to use, emit this in its fully unabbreviated
410       // form.
411       EmitCode(bitc::UNABBREV_RECORD);
412       EmitVBR(Code, 6);
413       EmitVBR(static_cast<uint32_t>(Vals.size()), 6);
414       for (unsigned i = 0, e = static_cast<unsigned>(Vals.size()); i != e; ++i)
415         EmitVBR64(Vals[i], 6);
416       return;
417     }
418
419     // Insert the code into Vals to treat it uniformly.
420     Vals.insert(Vals.begin(), Code);
421     
422     EmitRecordWithAbbrev(Abbrev, Vals);
423   }
424   
425   /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
426   /// Unlike EmitRecord, the code for the record should be included in Vals as
427   /// the first entry.
428   template<typename uintty>
429   void EmitRecordWithAbbrev(unsigned Abbrev, SmallVectorImpl<uintty> &Vals) {
430     EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef());
431   }
432   
433   /// EmitRecordWithBlob - Emit the specified record to the stream, using an
434   /// abbrev that includes a blob at the end.  The blob data to emit is
435   /// specified by the pointer and length specified at the end.  In contrast to
436   /// EmitRecord, this routine expects that the first entry in Vals is the code
437   /// of the record.
438   template<typename uintty>
439   void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
440                           StringRef Blob) {
441     EmitRecordWithAbbrevImpl(Abbrev, Vals, Blob);
442   }
443   template<typename uintty>
444   void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
445                           const char *BlobData, unsigned BlobLen) {
446     return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(BlobData, BlobLen));
447   }
448
449   /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
450   /// that end with an array.
451   template<typename uintty>
452   void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
453                           StringRef Array) {
454     EmitRecordWithAbbrevImpl(Abbrev, Vals, Array);
455   }
456   template<typename uintty>
457   void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
458                           const char *ArrayData, unsigned ArrayLen) {
459     return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(ArrayData, 
460                                                             ArrayLen));
461   }
462   
463   //===--------------------------------------------------------------------===//
464   // Abbrev Emission
465   //===--------------------------------------------------------------------===//
466
467 private:
468   // Emit the abbreviation as a DEFINE_ABBREV record.
469   void EncodeAbbrev(BitCodeAbbrev *Abbv) {
470     EmitCode(bitc::DEFINE_ABBREV);
471     EmitVBR(Abbv->getNumOperandInfos(), 5);
472     for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
473          i != e; ++i) {
474       const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
475       Emit(Op.isLiteral(), 1);
476       if (Op.isLiteral()) {
477         EmitVBR64(Op.getLiteralValue(), 8);
478       } else {
479         Emit(Op.getEncoding(), 3);
480         if (Op.hasEncodingData())
481           EmitVBR64(Op.getEncodingData(), 5);
482       }
483     }
484   }
485 public:
486
487   /// EmitAbbrev - This emits an abbreviation to the stream.  Note that this
488   /// method takes ownership of the specified abbrev.
489   unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
490     // Emit the abbreviation as a record.
491     EncodeAbbrev(Abbv);
492     CurAbbrevs.push_back(Abbv);
493     return static_cast<unsigned>(CurAbbrevs.size())-1 +
494       bitc::FIRST_APPLICATION_ABBREV;
495   }
496
497   //===--------------------------------------------------------------------===//
498   // BlockInfo Block Emission
499   //===--------------------------------------------------------------------===//
500
501   /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
502   void EnterBlockInfoBlock(unsigned CodeWidth) {
503     EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
504     BlockInfoCurBID = ~0U;
505   }
506 private:
507   /// SwitchToBlockID - If we aren't already talking about the specified block
508   /// ID, emit a BLOCKINFO_CODE_SETBID record.
509   void SwitchToBlockID(unsigned BlockID) {
510     if (BlockInfoCurBID == BlockID) return;
511     SmallVector<unsigned, 2> V;
512     V.push_back(BlockID);
513     EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
514     BlockInfoCurBID = BlockID;
515   }
516
517   BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
518     if (BlockInfo *BI = getBlockInfo(BlockID))
519       return *BI;
520
521     // Otherwise, add a new record.
522     BlockInfoRecords.push_back(BlockInfo());
523     BlockInfoRecords.back().BlockID = BlockID;
524     return BlockInfoRecords.back();
525   }
526
527 public:
528
529   /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
530   /// BlockID.
531   unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
532     SwitchToBlockID(BlockID);
533     EncodeAbbrev(Abbv);
534
535     // Add the abbrev to the specified block record.
536     BlockInfo &Info = getOrCreateBlockInfo(BlockID);
537     Info.Abbrevs.push_back(Abbv);
538
539     return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
540   }
541 };
542
543
544 } // End llvm namespace
545
546 #endif