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