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