2e8c9f46b8c747e5ac400c9ef1032304bb9ce065
[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     assert(NumBits <= 32 && "Too many bits to emit!");
159     uint32_t Threshold = 1U << (NumBits-1);
160
161     // Emit the bits with VBR encoding, NumBits-1 bits at a time.
162     while (Val >= Threshold) {
163       Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
164       Val >>= NumBits-1;
165     }
166
167     Emit(Val, NumBits);
168   }
169
170   void EmitVBR64(uint64_t Val, unsigned NumBits) {
171     assert(NumBits <= 32 && "Too many bits to emit!");
172     if ((uint32_t)Val == Val)
173       return EmitVBR((uint32_t)Val, NumBits);
174
175     uint32_t Threshold = 1U << (NumBits-1);
176
177     // Emit the bits with VBR encoding, NumBits-1 bits at a time.
178     while (Val >= Threshold) {
179       Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
180            (1 << (NumBits-1)), NumBits);
181       Val >>= NumBits-1;
182     }
183
184     Emit((uint32_t)Val, NumBits);
185   }
186
187   /// EmitCode - Emit the specified code.
188   void EmitCode(unsigned Val) {
189     Emit(Val, CurCodeSize);
190   }
191
192   //===--------------------------------------------------------------------===//
193   // Block Manipulation
194   //===--------------------------------------------------------------------===//
195
196   /// getBlockInfo - If there is block info for the specified ID, return it,
197   /// otherwise return null.
198   BlockInfo *getBlockInfo(unsigned BlockID) {
199     // Common case, the most recent entry matches BlockID.
200     if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
201       return &BlockInfoRecords.back();
202
203     for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
204          i != e; ++i)
205       if (BlockInfoRecords[i].BlockID == BlockID)
206         return &BlockInfoRecords[i];
207     return 0;
208   }
209
210   void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
211     // Block header:
212     //    [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
213     EmitCode(bitc::ENTER_SUBBLOCK);
214     EmitVBR(BlockID, bitc::BlockIDWidth);
215     EmitVBR(CodeLen, bitc::CodeLenWidth);
216     FlushToWord();
217
218     unsigned BlockSizeWordIndex = GetWordIndex();
219     unsigned OldCodeSize = CurCodeSize;
220
221     // Emit a placeholder, which will be replaced when the block is popped.
222     Emit(0, bitc::BlockSizeWidth);
223
224     CurCodeSize = CodeLen;
225
226     // Push the outer block's abbrev set onto the stack, start out with an
227     // empty abbrev set.
228     BlockScope.push_back(Block(OldCodeSize, BlockSizeWordIndex));
229     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
230
231     // If there is a blockinfo for this BlockID, add all the predefined abbrevs
232     // to the abbrev list.
233     if (BlockInfo *Info = getBlockInfo(BlockID)) {
234       for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
235            i != e; ++i) {
236         CurAbbrevs.push_back(Info->Abbrevs[i]);
237         Info->Abbrevs[i]->addRef();
238       }
239     }
240   }
241
242   void ExitBlock() {
243     assert(!BlockScope.empty() && "Block scope imbalance!");
244
245     // Delete all abbrevs.
246     for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
247          i != e; ++i)
248       CurAbbrevs[i]->dropRef();
249
250     const Block &B = BlockScope.back();
251
252     // Block tail:
253     //    [END_BLOCK, <align4bytes>]
254     EmitCode(bitc::END_BLOCK);
255     FlushToWord();
256
257     // Compute the size of the block, in words, not counting the size field.
258     unsigned SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
259     unsigned ByteNo = B.StartSizeWord*4;
260
261     // Update the block size field in the header of this sub-block.
262     BackpatchWord(ByteNo, SizeInWords);
263
264     // Restore the inner block's code size and abbrev table.
265     CurCodeSize = B.PrevCodeSize;
266     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
267     BlockScope.pop_back();
268   }
269
270   //===--------------------------------------------------------------------===//
271   // Record Emission
272   //===--------------------------------------------------------------------===//
273
274 private:
275   /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
276   /// record.  This is a no-op, since the abbrev specifies the literal to use.
277   template<typename uintty>
278   void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
279     assert(Op.isLiteral() && "Not a literal");
280     // If the abbrev specifies the literal value to use, don't emit
281     // anything.
282     assert(V == Op.getLiteralValue() &&
283            "Invalid abbrev for record!");
284   }
285
286   /// EmitAbbreviatedField - Emit a single scalar field value with the specified
287   /// encoding.
288   template<typename uintty>
289   void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
290     assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
291
292     // Encode the value as we are commanded.
293     switch (Op.getEncoding()) {
294     default: llvm_unreachable("Unknown encoding!");
295     case BitCodeAbbrevOp::Fixed:
296       if (Op.getEncodingData())
297         Emit((unsigned)V, (unsigned)Op.getEncodingData());
298       break;
299     case BitCodeAbbrevOp::VBR:
300       if (Op.getEncodingData())
301         EmitVBR64(V, (unsigned)Op.getEncodingData());
302       break;
303     case BitCodeAbbrevOp::Char6:
304       Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
305       break;
306     }
307   }
308
309   /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
310   /// emission code.  If BlobData is non-null, then it specifies an array of
311   /// data that should be emitted as part of the Blob or Array operand that is
312   /// known to exist at the end of the record.
313   template<typename uintty>
314   void EmitRecordWithAbbrevImpl(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
315                                 StringRef Blob) {
316     const char *BlobData = Blob.data();
317     unsigned BlobLen = (unsigned) Blob.size();
318     unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
319     assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
320     BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
321
322     EmitCode(Abbrev);
323
324     unsigned RecordIdx = 0;
325     for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
326          i != e; ++i) {
327       const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
328       if (Op.isLiteral()) {
329         assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
330         EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
331         ++RecordIdx;
332       } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
333         // Array case.
334         assert(i+2 == e && "array op not second to last?");
335         const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
336
337         // If this record has blob data, emit it, otherwise we must have record
338         // entries to encode this way.
339         if (BlobData) {
340           assert(RecordIdx == Vals.size() &&
341                  "Blob data and record entries specified for array!");
342           // Emit a vbr6 to indicate the number of elements present.
343           EmitVBR(static_cast<uint32_t>(BlobLen), 6);
344
345           // Emit each field.
346           for (unsigned i = 0; i != BlobLen; ++i)
347             EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
348
349           // Know that blob data is consumed for assertion below.
350           BlobData = 0;
351         } else {
352           // Emit a vbr6 to indicate the number of elements present.
353           EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
354
355           // Emit each field.
356           for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
357             EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
358         }
359       } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
360         // If this record has blob data, emit it, otherwise we must have record
361         // entries to encode this way.
362
363         // Emit a vbr6 to indicate the number of elements present.
364         if (BlobData) {
365           EmitVBR(static_cast<uint32_t>(BlobLen), 6);
366           assert(RecordIdx == Vals.size() &&
367                  "Blob data and record entries specified for blob operand!");
368         } else {
369           EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
370         }
371
372         // Flush to a 32-bit alignment boundary.
373         FlushToWord();
374
375         // Emit each field as a literal byte.
376         if (BlobData) {
377           for (unsigned i = 0; i != BlobLen; ++i)
378             WriteByte((unsigned char)BlobData[i]);
379
380           // Know that blob data is consumed for assertion below.
381           BlobData = 0;
382         } else {
383           for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx) {
384             assert(Vals[RecordIdx] < 256 && "Value too large to emit as blob");
385             WriteByte((unsigned char)Vals[RecordIdx]);
386           }
387         }
388
389         // Align end to 32-bits.
390         while (GetBufferOffset() & 3)
391           WriteByte(0);
392       } else {  // Single scalar field.
393         assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
394         EmitAbbreviatedField(Op, Vals[RecordIdx]);
395         ++RecordIdx;
396       }
397     }
398     assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
399     assert(BlobData == 0 &&
400            "Blob data specified for record that doesn't use it!");
401   }
402
403 public:
404
405   /// EmitRecord - Emit the specified record to the stream, using an abbrev if
406   /// we have one to compress the output.
407   template<typename uintty>
408   void EmitRecord(unsigned Code, SmallVectorImpl<uintty> &Vals,
409                   unsigned Abbrev = 0) {
410     if (!Abbrev) {
411       // If we don't have an abbrev to use, emit this in its fully unabbreviated
412       // form.
413       EmitCode(bitc::UNABBREV_RECORD);
414       EmitVBR(Code, 6);
415       EmitVBR(static_cast<uint32_t>(Vals.size()), 6);
416       for (unsigned i = 0, e = static_cast<unsigned>(Vals.size()); i != e; ++i)
417         EmitVBR64(Vals[i], 6);
418       return;
419     }
420
421     // Insert the code into Vals to treat it uniformly.
422     Vals.insert(Vals.begin(), Code);
423
424     EmitRecordWithAbbrev(Abbrev, Vals);
425   }
426
427   /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
428   /// Unlike EmitRecord, the code for the record should be included in Vals as
429   /// the first entry.
430   template<typename uintty>
431   void EmitRecordWithAbbrev(unsigned Abbrev, SmallVectorImpl<uintty> &Vals) {
432     EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef());
433   }
434
435   /// EmitRecordWithBlob - Emit the specified record to the stream, using an
436   /// abbrev that includes a blob at the end.  The blob data to emit is
437   /// specified by the pointer and length specified at the end.  In contrast to
438   /// EmitRecord, this routine expects that the first entry in Vals is the code
439   /// of the record.
440   template<typename uintty>
441   void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
442                           StringRef Blob) {
443     EmitRecordWithAbbrevImpl(Abbrev, Vals, Blob);
444   }
445   template<typename uintty>
446   void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
447                           const char *BlobData, unsigned BlobLen) {
448     return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(BlobData, BlobLen));
449   }
450
451   /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
452   /// that end with an array.
453   template<typename uintty>
454   void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
455                           StringRef Array) {
456     EmitRecordWithAbbrevImpl(Abbrev, Vals, Array);
457   }
458   template<typename uintty>
459   void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
460                           const char *ArrayData, unsigned ArrayLen) {
461     return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(ArrayData, 
462                                                             ArrayLen));
463   }
464
465   //===--------------------------------------------------------------------===//
466   // Abbrev Emission
467   //===--------------------------------------------------------------------===//
468
469 private:
470   // Emit the abbreviation as a DEFINE_ABBREV record.
471   void EncodeAbbrev(BitCodeAbbrev *Abbv) {
472     EmitCode(bitc::DEFINE_ABBREV);
473     EmitVBR(Abbv->getNumOperandInfos(), 5);
474     for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
475          i != e; ++i) {
476       const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
477       Emit(Op.isLiteral(), 1);
478       if (Op.isLiteral()) {
479         EmitVBR64(Op.getLiteralValue(), 8);
480       } else {
481         Emit(Op.getEncoding(), 3);
482         if (Op.hasEncodingData())
483           EmitVBR64(Op.getEncodingData(), 5);
484       }
485     }
486   }
487 public:
488
489   /// EmitAbbrev - This emits an abbreviation to the stream.  Note that this
490   /// method takes ownership of the specified abbrev.
491   unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
492     // Emit the abbreviation as a record.
493     EncodeAbbrev(Abbv);
494     CurAbbrevs.push_back(Abbv);
495     return static_cast<unsigned>(CurAbbrevs.size())-1 +
496       bitc::FIRST_APPLICATION_ABBREV;
497   }
498
499   //===--------------------------------------------------------------------===//
500   // BlockInfo Block Emission
501   //===--------------------------------------------------------------------===//
502
503   /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
504   void EnterBlockInfoBlock(unsigned CodeWidth) {
505     EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
506     BlockInfoCurBID = ~0U;
507   }
508 private:
509   /// SwitchToBlockID - If we aren't already talking about the specified block
510   /// ID, emit a BLOCKINFO_CODE_SETBID record.
511   void SwitchToBlockID(unsigned BlockID) {
512     if (BlockInfoCurBID == BlockID) return;
513     SmallVector<unsigned, 2> V;
514     V.push_back(BlockID);
515     EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
516     BlockInfoCurBID = BlockID;
517   }
518
519   BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
520     if (BlockInfo *BI = getBlockInfo(BlockID))
521       return *BI;
522
523     // Otherwise, add a new record.
524     BlockInfoRecords.push_back(BlockInfo());
525     BlockInfoRecords.back().BlockID = BlockID;
526     return BlockInfoRecords.back();
527   }
528
529 public:
530
531   /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
532   /// BlockID.
533   unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
534     SwitchToBlockID(BlockID);
535     EncodeAbbrev(Abbv);
536
537     // Add the abbrev to the specified block record.
538     BlockInfo &Info = getOrCreateBlockInfo(BlockID);
539     Info.Abbrevs.push_back(Abbv);
540
541     return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
542   }
543 };
544
545
546 } // End llvm namespace
547
548 #endif