BitstreamWriter.h 22 KB

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