BitstreamWriter.h 22 KB

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