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