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