xref: /netbsd-src/external/apache2/llvm/dist/llvm/include/llvm/Bitstream/BitstreamWriter.h (revision 82d56013d7b633d116a93943de88e08335357a7c)
1 //===- BitstreamWriter.h - Low-level bitstream writer interface -*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This header defines the BitstreamWriter class.  This class can be used to
10 // write an arbitrary bitstream, regardless of its contents.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_BITSTREAM_BITSTREAMWRITER_H
15 #define LLVM_BITSTREAM_BITSTREAMWRITER_H
16 
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/Bitstream/BitCodes.h"
22 #include "llvm/Support/Endian.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include <algorithm>
25 #include <vector>
26 
27 namespace llvm {
28 
29 class BitstreamWriter {
30   /// Out - The buffer that keeps unflushed bytes.
31   SmallVectorImpl<char> &Out;
32 
33   /// FS - The file stream that Out flushes to. If FS is nullptr, it does not
34   /// support read or seek, Out cannot be flushed until all data are written.
35   raw_fd_stream *FS;
36 
37   /// FlushThreshold - If FS is valid, this is the threshold (unit B) to flush
38   /// FS.
39   const uint64_t FlushThreshold;
40 
41   /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
42   unsigned CurBit;
43 
44   /// CurValue - The current value. Only bits < CurBit are valid.
45   uint32_t CurValue;
46 
47   /// CurCodeSize - This is the declared size of code values used for the
48   /// current block, in bits.
49   unsigned CurCodeSize;
50 
51   /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
52   /// selected BLOCK ID.
53   unsigned BlockInfoCurBID;
54 
55   /// CurAbbrevs - Abbrevs installed at in this block.
56   std::vector<std::shared_ptr<BitCodeAbbrev>> CurAbbrevs;
57 
58   struct Block {
59     unsigned PrevCodeSize;
60     size_t StartSizeWord;
61     std::vector<std::shared_ptr<BitCodeAbbrev>> PrevAbbrevs;
BlockBlock62     Block(unsigned PCS, size_t SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
63   };
64 
65   /// BlockScope - This tracks the current blocks that we have entered.
66   std::vector<Block> BlockScope;
67 
68   /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
69   /// These describe abbreviations that all blocks of the specified ID inherit.
70   struct BlockInfo {
71     unsigned BlockID;
72     std::vector<std::shared_ptr<BitCodeAbbrev>> Abbrevs;
73   };
74   std::vector<BlockInfo> BlockInfoRecords;
75 
WriteByte(unsigned char Value)76   void WriteByte(unsigned char Value) {
77     Out.push_back(Value);
78     FlushToFile();
79   }
80 
WriteWord(unsigned Value)81   void WriteWord(unsigned Value) {
82     Value = support::endian::byte_swap<uint32_t, support::little>(Value);
83     Out.append(reinterpret_cast<const char *>(&Value),
84                reinterpret_cast<const char *>(&Value + 1));
85     FlushToFile();
86   }
87 
GetNumOfFlushedBytes()88   uint64_t GetNumOfFlushedBytes() const { return FS ? FS->tell() : 0; }
89 
GetBufferOffset()90   size_t GetBufferOffset() const { return Out.size() + GetNumOfFlushedBytes(); }
91 
GetWordIndex()92   size_t GetWordIndex() const {
93     size_t Offset = GetBufferOffset();
94     assert((Offset & 3) == 0 && "Not 32-bit aligned");
95     return Offset / 4;
96   }
97 
98   /// If the related file stream supports reading, seeking and writing, flush
99   /// the buffer if its size is above a threshold.
FlushToFile()100   void FlushToFile() {
101     if (!FS)
102       return;
103     if (Out.size() < FlushThreshold)
104       return;
105     FS->write((char *)&Out.front(), Out.size());
106     Out.clear();
107   }
108 
109 public:
110   /// Create a BitstreamWriter that writes to Buffer \p O.
111   ///
112   /// \p FS is the file stream that \p O flushes to incrementally. If \p FS is
113   /// null, \p O does not flush incrementially, but writes to disk at the end.
114   ///
115   /// \p FlushThreshold is the threshold (unit M) to flush \p O if \p FS is
116   /// valid.
117   BitstreamWriter(SmallVectorImpl<char> &O, raw_fd_stream *FS = nullptr,
118                   uint32_t FlushThreshold = 512)
Out(O)119       : Out(O), FS(FS), FlushThreshold(FlushThreshold << 20), CurBit(0),
120         CurValue(0), CurCodeSize(2) {}
121 
~BitstreamWriter()122   ~BitstreamWriter() {
123     assert(CurBit == 0 && "Unflushed data remaining");
124     assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
125   }
126 
127   /// Retrieve the current position in the stream, in bits.
GetCurrentBitNo()128   uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; }
129 
130   /// Retrieve the number of bits currently used to encode an abbrev ID.
GetAbbrevIDWidth()131   unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
132 
133   //===--------------------------------------------------------------------===//
134   // Basic Primitives for emitting bits to the stream.
135   //===--------------------------------------------------------------------===//
136 
137   /// Backpatch a 32-bit word in the output at the given bit offset
138   /// with the specified value.
BackpatchWord(uint64_t BitNo,unsigned NewWord)139   void BackpatchWord(uint64_t BitNo, unsigned NewWord) {
140     using namespace llvm::support;
141     uint64_t ByteNo = BitNo / 8;
142     uint64_t StartBit = BitNo & 7;
143     uint64_t NumOfFlushedBytes = GetNumOfFlushedBytes();
144 
145     if (ByteNo >= NumOfFlushedBytes) {
146       assert((!endian::readAtBitAlignment<uint32_t, little, unaligned>(
147                  &Out[ByteNo - NumOfFlushedBytes], StartBit)) &&
148              "Expected to be patching over 0-value placeholders");
149       endian::writeAtBitAlignment<uint32_t, little, unaligned>(
150           &Out[ByteNo - NumOfFlushedBytes], NewWord, StartBit);
151       return;
152     }
153 
154     // If the byte offset to backpatch is flushed, use seek to backfill data.
155     // First, save the file position to restore later.
156     uint64_t CurPos = FS->tell();
157 
158     // Copy data to update into Bytes from the file FS and the buffer Out.
159     char Bytes[9]; // Use one more byte to silence a warning from Visual C++.
160     size_t BytesNum = StartBit ? 8 : 4;
161     size_t BytesFromDisk = std::min(static_cast<uint64_t>(BytesNum), NumOfFlushedBytes - ByteNo);
162     size_t BytesFromBuffer = BytesNum - BytesFromDisk;
163 
164     // When unaligned, copy existing data into Bytes from the file FS and the
165     // buffer Out so that it can be updated before writing. For debug builds
166     // read bytes unconditionally in order to check that the existing value is 0
167     // as expected.
168 #ifdef NDEBUG
169     if (StartBit)
170 #endif
171     {
172       FS->seek(ByteNo);
173       ssize_t BytesRead = FS->read(Bytes, BytesFromDisk);
174       (void)BytesRead; // silence warning
175       assert(BytesRead >= 0 && static_cast<size_t>(BytesRead) == BytesFromDisk);
176       for (size_t i = 0; i < BytesFromBuffer; ++i)
177         Bytes[BytesFromDisk + i] = Out[i];
178       assert((!endian::readAtBitAlignment<uint32_t, little, unaligned>(
179                  Bytes, StartBit)) &&
180              "Expected to be patching over 0-value placeholders");
181     }
182 
183     // Update Bytes in terms of bit offset and value.
184     endian::writeAtBitAlignment<uint32_t, little, unaligned>(Bytes, NewWord,
185                                                              StartBit);
186 
187     // Copy updated data back to the file FS and the buffer Out.
188     FS->seek(ByteNo);
189     FS->write(Bytes, BytesFromDisk);
190     for (size_t i = 0; i < BytesFromBuffer; ++i)
191       Out[i] = Bytes[BytesFromDisk + i];
192 
193     // Restore the file position.
194     FS->seek(CurPos);
195   }
196 
BackpatchWord64(uint64_t BitNo,uint64_t Val)197   void BackpatchWord64(uint64_t BitNo, uint64_t Val) {
198     BackpatchWord(BitNo, (uint32_t)Val);
199     BackpatchWord(BitNo + 32, (uint32_t)(Val >> 32));
200   }
201 
Emit(uint32_t Val,unsigned NumBits)202   void Emit(uint32_t Val, unsigned NumBits) {
203     assert(NumBits && NumBits <= 32 && "Invalid value size!");
204     assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
205     CurValue |= Val << CurBit;
206     if (CurBit + NumBits < 32) {
207       CurBit += NumBits;
208       return;
209     }
210 
211     // Add the current word.
212     WriteWord(CurValue);
213 
214     if (CurBit)
215       CurValue = Val >> (32-CurBit);
216     else
217       CurValue = 0;
218     CurBit = (CurBit+NumBits) & 31;
219   }
220 
FlushToWord()221   void FlushToWord() {
222     if (CurBit) {
223       WriteWord(CurValue);
224       CurBit = 0;
225       CurValue = 0;
226     }
227   }
228 
EmitVBR(uint32_t Val,unsigned NumBits)229   void EmitVBR(uint32_t Val, unsigned NumBits) {
230     assert(NumBits <= 32 && "Too many bits to emit!");
231     uint32_t Threshold = 1U << (NumBits-1);
232 
233     // Emit the bits with VBR encoding, NumBits-1 bits at a time.
234     while (Val >= Threshold) {
235       Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
236       Val >>= NumBits-1;
237     }
238 
239     Emit(Val, NumBits);
240   }
241 
EmitVBR64(uint64_t Val,unsigned NumBits)242   void EmitVBR64(uint64_t Val, unsigned NumBits) {
243     assert(NumBits <= 32 && "Too many bits to emit!");
244     if ((uint32_t)Val == Val)
245       return EmitVBR((uint32_t)Val, NumBits);
246 
247     uint32_t Threshold = 1U << (NumBits-1);
248 
249     // Emit the bits with VBR encoding, NumBits-1 bits at a time.
250     while (Val >= Threshold) {
251       Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
252            (1 << (NumBits-1)), NumBits);
253       Val >>= NumBits-1;
254     }
255 
256     Emit((uint32_t)Val, NumBits);
257   }
258 
259   /// EmitCode - Emit the specified code.
EmitCode(unsigned Val)260   void EmitCode(unsigned Val) {
261     Emit(Val, CurCodeSize);
262   }
263 
264   //===--------------------------------------------------------------------===//
265   // Block Manipulation
266   //===--------------------------------------------------------------------===//
267 
268   /// getBlockInfo - If there is block info for the specified ID, return it,
269   /// otherwise return null.
getBlockInfo(unsigned BlockID)270   BlockInfo *getBlockInfo(unsigned BlockID) {
271     // Common case, the most recent entry matches BlockID.
272     if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
273       return &BlockInfoRecords.back();
274 
275     for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
276          i != e; ++i)
277       if (BlockInfoRecords[i].BlockID == BlockID)
278         return &BlockInfoRecords[i];
279     return nullptr;
280   }
281 
EnterSubblock(unsigned BlockID,unsigned CodeLen)282   void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
283     // Block header:
284     //    [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
285     EmitCode(bitc::ENTER_SUBBLOCK);
286     EmitVBR(BlockID, bitc::BlockIDWidth);
287     EmitVBR(CodeLen, bitc::CodeLenWidth);
288     FlushToWord();
289 
290     size_t BlockSizeWordIndex = GetWordIndex();
291     unsigned OldCodeSize = CurCodeSize;
292 
293     // Emit a placeholder, which will be replaced when the block is popped.
294     Emit(0, bitc::BlockSizeWidth);
295 
296     CurCodeSize = CodeLen;
297 
298     // Push the outer block's abbrev set onto the stack, start out with an
299     // empty abbrev set.
300     BlockScope.emplace_back(OldCodeSize, BlockSizeWordIndex);
301     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
302 
303     // If there is a blockinfo for this BlockID, add all the predefined abbrevs
304     // to the abbrev list.
305     if (BlockInfo *Info = getBlockInfo(BlockID))
306       append_range(CurAbbrevs, Info->Abbrevs);
307   }
308 
ExitBlock()309   void ExitBlock() {
310     assert(!BlockScope.empty() && "Block scope imbalance!");
311     const Block &B = BlockScope.back();
312 
313     // Block tail:
314     //    [END_BLOCK, <align4bytes>]
315     EmitCode(bitc::END_BLOCK);
316     FlushToWord();
317 
318     // Compute the size of the block, in words, not counting the size field.
319     size_t SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
320     uint64_t BitNo = uint64_t(B.StartSizeWord) * 32;
321 
322     // Update the block size field in the header of this sub-block.
323     BackpatchWord(BitNo, SizeInWords);
324 
325     // Restore the inner block's code size and abbrev table.
326     CurCodeSize = B.PrevCodeSize;
327     CurAbbrevs = std::move(B.PrevAbbrevs);
328     BlockScope.pop_back();
329   }
330 
331   //===--------------------------------------------------------------------===//
332   // Record Emission
333   //===--------------------------------------------------------------------===//
334 
335 private:
336   /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
337   /// record.  This is a no-op, since the abbrev specifies the literal to use.
338   template<typename uintty>
EmitAbbreviatedLiteral(const BitCodeAbbrevOp & Op,uintty V)339   void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
340     assert(Op.isLiteral() && "Not a literal");
341     // If the abbrev specifies the literal value to use, don't emit
342     // anything.
343     assert(V == Op.getLiteralValue() &&
344            "Invalid abbrev for record!");
345   }
346 
347   /// EmitAbbreviatedField - Emit a single scalar field value with the specified
348   /// encoding.
349   template<typename uintty>
EmitAbbreviatedField(const BitCodeAbbrevOp & Op,uintty V)350   void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
351     assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
352 
353     // Encode the value as we are commanded.
354     switch (Op.getEncoding()) {
355     default: llvm_unreachable("Unknown encoding!");
356     case BitCodeAbbrevOp::Fixed:
357       if (Op.getEncodingData())
358         Emit((unsigned)V, (unsigned)Op.getEncodingData());
359       break;
360     case BitCodeAbbrevOp::VBR:
361       if (Op.getEncodingData())
362         EmitVBR64(V, (unsigned)Op.getEncodingData());
363       break;
364     case BitCodeAbbrevOp::Char6:
365       Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
366       break;
367     }
368   }
369 
370   /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
371   /// emission code.  If BlobData is non-null, then it specifies an array of
372   /// data that should be emitted as part of the Blob or Array operand that is
373   /// known to exist at the end of the record. If Code is specified, then
374   /// it is the record code to emit before the Vals, which must not contain
375   /// the code.
376   template <typename uintty>
EmitRecordWithAbbrevImpl(unsigned Abbrev,ArrayRef<uintty> Vals,StringRef Blob,Optional<unsigned> Code)377   void EmitRecordWithAbbrevImpl(unsigned Abbrev, ArrayRef<uintty> Vals,
378                                 StringRef Blob, Optional<unsigned> Code) {
379     const char *BlobData = Blob.data();
380     unsigned BlobLen = (unsigned) Blob.size();
381     unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
382     assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
383     const BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo].get();
384 
385     EmitCode(Abbrev);
386 
387     unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
388     if (Code) {
389       assert(e && "Expected non-empty abbreviation");
390       const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i++);
391 
392       if (Op.isLiteral())
393         EmitAbbreviatedLiteral(Op, Code.getValue());
394       else {
395         assert(Op.getEncoding() != BitCodeAbbrevOp::Array &&
396                Op.getEncoding() != BitCodeAbbrevOp::Blob &&
397                "Expected literal or scalar");
398         EmitAbbreviatedField(Op, Code.getValue());
399       }
400     }
401 
402     unsigned RecordIdx = 0;
403     for (; i != e; ++i) {
404       const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
405       if (Op.isLiteral()) {
406         assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
407         EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
408         ++RecordIdx;
409       } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
410         // Array case.
411         assert(i + 2 == e && "array op not second to last?");
412         const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
413 
414         // If this record has blob data, emit it, otherwise we must have record
415         // entries to encode this way.
416         if (BlobData) {
417           assert(RecordIdx == Vals.size() &&
418                  "Blob data and record entries specified for array!");
419           // Emit a vbr6 to indicate the number of elements present.
420           EmitVBR(static_cast<uint32_t>(BlobLen), 6);
421 
422           // Emit each field.
423           for (unsigned i = 0; i != BlobLen; ++i)
424             EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
425 
426           // Know that blob data is consumed for assertion below.
427           BlobData = nullptr;
428         } else {
429           // Emit a vbr6 to indicate the number of elements present.
430           EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
431 
432           // Emit each field.
433           for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
434             EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
435         }
436       } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
437         // If this record has blob data, emit it, otherwise we must have record
438         // entries to encode this way.
439 
440         if (BlobData) {
441           assert(RecordIdx == Vals.size() &&
442                  "Blob data and record entries specified for blob operand!");
443 
444           assert(Blob.data() == BlobData && "BlobData got moved");
445           assert(Blob.size() == BlobLen && "BlobLen got changed");
446           emitBlob(Blob);
447           BlobData = nullptr;
448         } else {
449           emitBlob(Vals.slice(RecordIdx));
450         }
451       } else {  // Single scalar field.
452         assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
453         EmitAbbreviatedField(Op, Vals[RecordIdx]);
454         ++RecordIdx;
455       }
456     }
457     assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
458     assert(BlobData == nullptr &&
459            "Blob data specified for record that doesn't use it!");
460   }
461 
462 public:
463   /// Emit a blob, including flushing before and tail-padding.
464   template <class UIntTy>
465   void emitBlob(ArrayRef<UIntTy> Bytes, bool ShouldEmitSize = true) {
466     // Emit a vbr6 to indicate the number of elements present.
467     if (ShouldEmitSize)
468       EmitVBR(static_cast<uint32_t>(Bytes.size()), 6);
469 
470     // Flush to a 32-bit alignment boundary.
471     FlushToWord();
472 
473     // Emit literal bytes.
474     for (const auto &B : Bytes) {
475       assert(isUInt<8>(B) && "Value too large to emit as byte");
476       WriteByte((unsigned char)B);
477     }
478 
479     // Align end to 32-bits.
480     while (GetBufferOffset() & 3)
481       WriteByte(0);
482   }
483   void emitBlob(StringRef Bytes, bool ShouldEmitSize = true) {
484     emitBlob(makeArrayRef((const uint8_t *)Bytes.data(), Bytes.size()),
485              ShouldEmitSize);
486   }
487 
488   /// EmitRecord - Emit the specified record to the stream, using an abbrev if
489   /// we have one to compress the output.
490   template <typename Container>
491   void EmitRecord(unsigned Code, const Container &Vals, unsigned Abbrev = 0) {
492     if (!Abbrev) {
493       // If we don't have an abbrev to use, emit this in its fully unabbreviated
494       // form.
495       auto Count = static_cast<uint32_t>(makeArrayRef(Vals).size());
496       EmitCode(bitc::UNABBREV_RECORD);
497       EmitVBR(Code, 6);
498       EmitVBR(Count, 6);
499       for (unsigned i = 0, e = Count; i != e; ++i)
500         EmitVBR64(Vals[i], 6);
501       return;
502     }
503 
504     EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), StringRef(), Code);
505   }
506 
507   /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
508   /// Unlike EmitRecord, the code for the record should be included in Vals as
509   /// the first entry.
510   template <typename Container>
EmitRecordWithAbbrev(unsigned Abbrev,const Container & Vals)511   void EmitRecordWithAbbrev(unsigned Abbrev, const Container &Vals) {
512     EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), StringRef(), None);
513   }
514 
515   /// EmitRecordWithBlob - Emit the specified record to the stream, using an
516   /// abbrev that includes a blob at the end.  The blob data to emit is
517   /// specified by the pointer and length specified at the end.  In contrast to
518   /// EmitRecord, this routine expects that the first entry in Vals is the code
519   /// of the record.
520   template <typename Container>
EmitRecordWithBlob(unsigned Abbrev,const Container & Vals,StringRef Blob)521   void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
522                           StringRef Blob) {
523     EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Blob, None);
524   }
525   template <typename Container>
EmitRecordWithBlob(unsigned Abbrev,const Container & Vals,const char * BlobData,unsigned BlobLen)526   void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
527                           const char *BlobData, unsigned BlobLen) {
528     return EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals),
529                                     StringRef(BlobData, BlobLen), None);
530   }
531 
532   /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
533   /// that end with an array.
534   template <typename Container>
EmitRecordWithArray(unsigned Abbrev,const Container & Vals,StringRef Array)535   void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
536                            StringRef Array) {
537     EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Array, None);
538   }
539   template <typename Container>
EmitRecordWithArray(unsigned Abbrev,const Container & Vals,const char * ArrayData,unsigned ArrayLen)540   void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
541                            const char *ArrayData, unsigned ArrayLen) {
542     return EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals),
543                                     StringRef(ArrayData, ArrayLen), None);
544   }
545 
546   //===--------------------------------------------------------------------===//
547   // Abbrev Emission
548   //===--------------------------------------------------------------------===//
549 
550 private:
551   // Emit the abbreviation as a DEFINE_ABBREV record.
EncodeAbbrev(const BitCodeAbbrev & Abbv)552   void EncodeAbbrev(const BitCodeAbbrev &Abbv) {
553     EmitCode(bitc::DEFINE_ABBREV);
554     EmitVBR(Abbv.getNumOperandInfos(), 5);
555     for (unsigned i = 0, e = static_cast<unsigned>(Abbv.getNumOperandInfos());
556          i != e; ++i) {
557       const BitCodeAbbrevOp &Op = Abbv.getOperandInfo(i);
558       Emit(Op.isLiteral(), 1);
559       if (Op.isLiteral()) {
560         EmitVBR64(Op.getLiteralValue(), 8);
561       } else {
562         Emit(Op.getEncoding(), 3);
563         if (Op.hasEncodingData())
564           EmitVBR64(Op.getEncodingData(), 5);
565       }
566     }
567   }
568 public:
569 
570   /// Emits the abbreviation \p Abbv to the stream.
EmitAbbrev(std::shared_ptr<BitCodeAbbrev> Abbv)571   unsigned EmitAbbrev(std::shared_ptr<BitCodeAbbrev> Abbv) {
572     EncodeAbbrev(*Abbv);
573     CurAbbrevs.push_back(std::move(Abbv));
574     return static_cast<unsigned>(CurAbbrevs.size())-1 +
575       bitc::FIRST_APPLICATION_ABBREV;
576   }
577 
578   //===--------------------------------------------------------------------===//
579   // BlockInfo Block Emission
580   //===--------------------------------------------------------------------===//
581 
582   /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
EnterBlockInfoBlock()583   void EnterBlockInfoBlock() {
584     EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, 2);
585     BlockInfoCurBID = ~0U;
586     BlockInfoRecords.clear();
587   }
588 private:
589   /// SwitchToBlockID - If we aren't already talking about the specified block
590   /// ID, emit a BLOCKINFO_CODE_SETBID record.
SwitchToBlockID(unsigned BlockID)591   void SwitchToBlockID(unsigned BlockID) {
592     if (BlockInfoCurBID == BlockID) return;
593     SmallVector<unsigned, 2> V;
594     V.push_back(BlockID);
595     EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
596     BlockInfoCurBID = BlockID;
597   }
598 
getOrCreateBlockInfo(unsigned BlockID)599   BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
600     if (BlockInfo *BI = getBlockInfo(BlockID))
601       return *BI;
602 
603     // Otherwise, add a new record.
604     BlockInfoRecords.emplace_back();
605     BlockInfoRecords.back().BlockID = BlockID;
606     return BlockInfoRecords.back();
607   }
608 
609 public:
610 
611   /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
612   /// BlockID.
EmitBlockInfoAbbrev(unsigned BlockID,std::shared_ptr<BitCodeAbbrev> Abbv)613   unsigned EmitBlockInfoAbbrev(unsigned BlockID, std::shared_ptr<BitCodeAbbrev> Abbv) {
614     SwitchToBlockID(BlockID);
615     EncodeAbbrev(*Abbv);
616 
617     // Add the abbrev to the specified block record.
618     BlockInfo &Info = getOrCreateBlockInfo(BlockID);
619     Info.Abbrevs.push_back(std::move(Abbv));
620 
621     return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
622   }
623 };
624 
625 
626 } // End llvm namespace
627 
628 #endif
629