Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

548 lines
18 KiB

  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. #ifndef LLVM_BITCODE_BITSTREAMWRITER_H
  15. #define LLVM_BITCODE_BITSTREAMWRITER_H
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/StringRef.h"
  18. #include "llvm/Bitcode/BitCodes.h"
  19. #include <vector>
  20. namespace llvm {
  21. class BitstreamWriter {
  22. SmallVectorImpl<char> &Out;
  23. /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
  24. unsigned CurBit;
  25. /// CurValue - The current value. Only bits < CurBit are valid.
  26. uint32_t CurValue;
  27. /// CurCodeSize - This is the declared size of code values used for the
  28. /// current block, in bits.
  29. unsigned CurCodeSize;
  30. /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
  31. /// selected BLOCK ID.
  32. unsigned BlockInfoCurBID;
  33. /// CurAbbrevs - Abbrevs installed at in this block.
  34. std::vector<BitCodeAbbrev*> CurAbbrevs;
  35. struct Block {
  36. unsigned PrevCodeSize;
  37. unsigned StartSizeWord;
  38. std::vector<BitCodeAbbrev*> PrevAbbrevs;
  39. Block(unsigned PCS, unsigned SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
  40. };
  41. /// BlockScope - This tracks the current blocks that we have entered.
  42. std::vector<Block> BlockScope;
  43. /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
  44. /// These describe abbreviations that all blocks of the specified ID inherit.
  45. struct BlockInfo {
  46. unsigned BlockID;
  47. std::vector<BitCodeAbbrev*> Abbrevs;
  48. };
  49. std::vector<BlockInfo> BlockInfoRecords;
  50. // BackpatchWord - Backpatch a 32-bit word in the output with the specified
  51. // value.
  52. void BackpatchWord(unsigned ByteNo, unsigned NewWord) {
  53. Out[ByteNo++] = (unsigned char)(NewWord >> 0);
  54. Out[ByteNo++] = (unsigned char)(NewWord >> 8);
  55. Out[ByteNo++] = (unsigned char)(NewWord >> 16);
  56. Out[ByteNo ] = (unsigned char)(NewWord >> 24);
  57. }
  58. void WriteByte(unsigned char Value) {
  59. Out.push_back(Value);
  60. }
  61. void WriteWord(unsigned Value) {
  62. unsigned char Bytes[4] = {
  63. (unsigned char)(Value >> 0),
  64. (unsigned char)(Value >> 8),
  65. (unsigned char)(Value >> 16),
  66. (unsigned char)(Value >> 24) };
  67. Out.append(&Bytes[0], &Bytes[4]);
  68. }
  69. unsigned GetBufferOffset() const {
  70. return Out.size();
  71. }
  72. unsigned GetWordIndex() const {
  73. unsigned Offset = GetBufferOffset();
  74. assert((Offset & 3) == 0 && "Not 32-bit aligned");
  75. return Offset / 4;
  76. }
  77. public:
  78. explicit BitstreamWriter(SmallVectorImpl<char> &O)
  79. : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
  80. ~BitstreamWriter() {
  81. assert(CurBit == 0 && "Unflused data remaining");
  82. assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
  83. // Free the BlockInfoRecords.
  84. while (!BlockInfoRecords.empty()) {
  85. BlockInfo &Info = BlockInfoRecords.back();
  86. // Free blockinfo abbrev info.
  87. for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
  88. i != e; ++i)
  89. Info.Abbrevs[i]->dropRef();
  90. BlockInfoRecords.pop_back();
  91. }
  92. }
  93. /// \brief Retrieve the current position in the stream, in bits.
  94. uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; }
  95. //===--------------------------------------------------------------------===//
  96. // Basic Primitives for emitting bits to the stream.
  97. //===--------------------------------------------------------------------===//
  98. void Emit(uint32_t Val, unsigned NumBits) {
  99. assert(NumBits && NumBits <= 32 && "Invalid value size!");
  100. assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
  101. CurValue |= Val << CurBit;
  102. if (CurBit + NumBits < 32) {
  103. CurBit += NumBits;
  104. return;
  105. }
  106. // Add the current word.
  107. WriteWord(CurValue);
  108. if (CurBit)
  109. CurValue = Val >> (32-CurBit);
  110. else
  111. CurValue = 0;
  112. CurBit = (CurBit+NumBits) & 31;
  113. }
  114. void Emit64(uint64_t Val, unsigned NumBits) {
  115. if (NumBits <= 32)
  116. Emit((uint32_t)Val, NumBits);
  117. else {
  118. Emit((uint32_t)Val, 32);
  119. Emit((uint32_t)(Val >> 32), NumBits-32);
  120. }
  121. }
  122. void FlushToWord() {
  123. if (CurBit) {
  124. WriteWord(CurValue);
  125. CurBit = 0;
  126. CurValue = 0;
  127. }
  128. }
  129. void EmitVBR(uint32_t Val, unsigned NumBits) {
  130. assert(NumBits <= 32 && "Too many bits to emit!");
  131. uint32_t Threshold = 1U << (NumBits-1);
  132. // Emit the bits with VBR encoding, NumBits-1 bits at a time.
  133. while (Val >= Threshold) {
  134. Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
  135. Val >>= NumBits-1;
  136. }
  137. Emit(Val, NumBits);
  138. }
  139. void EmitVBR64(uint64_t Val, unsigned NumBits) {
  140. assert(NumBits <= 32 && "Too many bits to emit!");
  141. if ((uint32_t)Val == Val)
  142. return EmitVBR((uint32_t)Val, NumBits);
  143. uint32_t Threshold = 1U << (NumBits-1);
  144. // Emit the bits with VBR encoding, NumBits-1 bits at a time.
  145. while (Val >= Threshold) {
  146. Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
  147. (1 << (NumBits-1)), NumBits);
  148. Val >>= NumBits-1;
  149. }
  150. Emit((uint32_t)Val, NumBits);
  151. }
  152. /// EmitCode - Emit the specified code.
  153. void EmitCode(unsigned Val) {
  154. Emit(Val, CurCodeSize);
  155. }
  156. //===--------------------------------------------------------------------===//
  157. // Block Manipulation
  158. //===--------------------------------------------------------------------===//
  159. /// getBlockInfo - If there is block info for the specified ID, return it,
  160. /// otherwise return null.
  161. BlockInfo *getBlockInfo(unsigned BlockID) {
  162. // Common case, the most recent entry matches BlockID.
  163. if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
  164. return &BlockInfoRecords.back();
  165. for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
  166. i != e; ++i)
  167. if (BlockInfoRecords[i].BlockID == BlockID)
  168. return &BlockInfoRecords[i];
  169. return 0;
  170. }
  171. void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
  172. // Block header:
  173. // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
  174. EmitCode(bitc::ENTER_SUBBLOCK);
  175. EmitVBR(BlockID, bitc::BlockIDWidth);
  176. EmitVBR(CodeLen, bitc::CodeLenWidth);
  177. FlushToWord();
  178. unsigned BlockSizeWordIndex = GetWordIndex();
  179. unsigned OldCodeSize = CurCodeSize;
  180. // Emit a placeholder, which will be replaced when the block is popped.
  181. Emit(0, bitc::BlockSizeWidth);
  182. CurCodeSize = CodeLen;
  183. // Push the outer block's abbrev set onto the stack, start out with an
  184. // empty abbrev set.
  185. BlockScope.push_back(Block(OldCodeSize, BlockSizeWordIndex));
  186. BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
  187. // If there is a blockinfo for this BlockID, add all the predefined abbrevs
  188. // to the abbrev list.
  189. if (BlockInfo *Info = getBlockInfo(BlockID)) {
  190. for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
  191. i != e; ++i) {
  192. CurAbbrevs.push_back(Info->Abbrevs[i]);
  193. Info->Abbrevs[i]->addRef();
  194. }
  195. }
  196. }
  197. void ExitBlock() {
  198. assert(!BlockScope.empty() && "Block scope imbalance!");
  199. // Delete all abbrevs.
  200. for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
  201. i != e; ++i)
  202. CurAbbrevs[i]->dropRef();
  203. const Block &B = BlockScope.back();
  204. // Block tail:
  205. // [END_BLOCK, <align4bytes>]
  206. EmitCode(bitc::END_BLOCK);
  207. FlushToWord();
  208. // Compute the size of the block, in words, not counting the size field.
  209. unsigned SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
  210. unsigned ByteNo = B.StartSizeWord*4;
  211. // Update the block size field in the header of this sub-block.
  212. BackpatchWord(ByteNo, SizeInWords);
  213. // Restore the inner block's code size and abbrev table.
  214. CurCodeSize = B.PrevCodeSize;
  215. BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
  216. BlockScope.pop_back();
  217. }
  218. //===--------------------------------------------------------------------===//
  219. // Record Emission
  220. //===--------------------------------------------------------------------===//
  221. private:
  222. /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
  223. /// record. This is a no-op, since the abbrev specifies the literal to use.
  224. template<typename uintty>
  225. void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
  226. assert(Op.isLiteral() && "Not a literal");
  227. // If the abbrev specifies the literal value to use, don't emit
  228. // anything.
  229. assert(V == Op.getLiteralValue() &&
  230. "Invalid abbrev for record!");
  231. }
  232. /// EmitAbbreviatedField - Emit a single scalar field value with the specified
  233. /// encoding.
  234. template<typename uintty>
  235. void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
  236. assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
  237. // Encode the value as we are commanded.
  238. switch (Op.getEncoding()) {
  239. default: llvm_unreachable("Unknown encoding!");
  240. case BitCodeAbbrevOp::Fixed:
  241. if (Op.getEncodingData())
  242. Emit((unsigned)V, (unsigned)Op.getEncodingData());
  243. break;
  244. case BitCodeAbbrevOp::VBR:
  245. if (Op.getEncodingData())
  246. EmitVBR64(V, (unsigned)Op.getEncodingData());
  247. break;
  248. case BitCodeAbbrevOp::Char6:
  249. Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
  250. break;
  251. }
  252. }
  253. /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
  254. /// emission code. If BlobData is non-null, then it specifies an array of
  255. /// data that should be emitted as part of the Blob or Array operand that is
  256. /// known to exist at the end of the record.
  257. template<typename uintty>
  258. void EmitRecordWithAbbrevImpl(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
  259. StringRef Blob) {
  260. const char *BlobData = Blob.data();
  261. unsigned BlobLen = (unsigned) Blob.size();
  262. unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
  263. assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
  264. BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
  265. EmitCode(Abbrev);
  266. unsigned RecordIdx = 0;
  267. for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
  268. i != e; ++i) {
  269. const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
  270. if (Op.isLiteral()) {
  271. assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
  272. EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
  273. ++RecordIdx;
  274. } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
  275. // Array case.
  276. assert(i+2 == e && "array op not second to last?");
  277. const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
  278. // If this record has blob data, emit it, otherwise we must have record
  279. // entries to encode this way.
  280. if (BlobData) {
  281. assert(RecordIdx == Vals.size() &&
  282. "Blob data and record entries specified for array!");
  283. // Emit a vbr6 to indicate the number of elements present.
  284. EmitVBR(static_cast<uint32_t>(BlobLen), 6);
  285. // Emit each field.
  286. for (unsigned i = 0; i != BlobLen; ++i)
  287. EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
  288. // Know that blob data is consumed for assertion below.
  289. BlobData = 0;
  290. } else {
  291. // Emit a vbr6 to indicate the number of elements present.
  292. EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
  293. // Emit each field.
  294. for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
  295. EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
  296. }
  297. } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
  298. // If this record has blob data, emit it, otherwise we must have record
  299. // entries to encode this way.
  300. // Emit a vbr6 to indicate the number of elements present.
  301. if (BlobData) {
  302. EmitVBR(static_cast<uint32_t>(BlobLen), 6);
  303. assert(RecordIdx == Vals.size() &&
  304. "Blob data and record entries specified for blob operand!");
  305. } else {
  306. EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
  307. }
  308. // Flush to a 32-bit alignment boundary.
  309. FlushToWord();
  310. // Emit each field as a literal byte.
  311. if (BlobData) {
  312. for (unsigned i = 0; i != BlobLen; ++i)
  313. WriteByte((unsigned char)BlobData[i]);
  314. // Know that blob data is consumed for assertion below.
  315. BlobData = 0;
  316. } else {
  317. for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx) {
  318. assert(Vals[RecordIdx] < 256 && "Value too large to emit as blob");
  319. WriteByte((unsigned char)Vals[RecordIdx]);
  320. }
  321. }
  322. // Align end to 32-bits.
  323. while (GetBufferOffset() & 3)
  324. WriteByte(0);
  325. } else { // Single scalar field.
  326. assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
  327. EmitAbbreviatedField(Op, Vals[RecordIdx]);
  328. ++RecordIdx;
  329. }
  330. }
  331. assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
  332. assert(BlobData == 0 &&
  333. "Blob data specified for record that doesn't use it!");
  334. }
  335. public:
  336. /// EmitRecord - Emit the specified record to the stream, using an abbrev if
  337. /// we have one to compress the output.
  338. template<typename uintty>
  339. void EmitRecord(unsigned Code, SmallVectorImpl<uintty> &Vals,
  340. unsigned Abbrev = 0) {
  341. if (!Abbrev) {
  342. // If we don't have an abbrev to use, emit this in its fully unabbreviated
  343. // form.
  344. EmitCode(bitc::UNABBREV_RECORD);
  345. EmitVBR(Code, 6);
  346. EmitVBR(static_cast<uint32_t>(Vals.size()), 6);
  347. for (unsigned i = 0, e = static_cast<unsigned>(Vals.size()); i != e; ++i)
  348. EmitVBR64(Vals[i], 6);
  349. return;
  350. }
  351. // Insert the code into Vals to treat it uniformly.
  352. Vals.insert(Vals.begin(), Code);
  353. EmitRecordWithAbbrev(Abbrev, Vals);
  354. }
  355. /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
  356. /// Unlike EmitRecord, the code for the record should be included in Vals as
  357. /// the first entry.
  358. template<typename uintty>
  359. void EmitRecordWithAbbrev(unsigned Abbrev, SmallVectorImpl<uintty> &Vals) {
  360. EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef());
  361. }
  362. /// EmitRecordWithBlob - Emit the specified record to the stream, using an
  363. /// abbrev that includes a blob at the end. The blob data to emit is
  364. /// specified by the pointer and length specified at the end. In contrast to
  365. /// EmitRecord, this routine expects that the first entry in Vals is the code
  366. /// of the record.
  367. template<typename uintty>
  368. void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
  369. StringRef Blob) {
  370. EmitRecordWithAbbrevImpl(Abbrev, Vals, Blob);
  371. }
  372. template<typename uintty>
  373. void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
  374. const char *BlobData, unsigned BlobLen) {
  375. return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(BlobData, BlobLen));
  376. }
  377. /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
  378. /// that end with an array.
  379. template<typename uintty>
  380. void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
  381. StringRef Array) {
  382. EmitRecordWithAbbrevImpl(Abbrev, Vals, Array);
  383. }
  384. template<typename uintty>
  385. void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
  386. const char *ArrayData, unsigned ArrayLen) {
  387. return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(ArrayData,
  388. ArrayLen));
  389. }
  390. //===--------------------------------------------------------------------===//
  391. // Abbrev Emission
  392. //===--------------------------------------------------------------------===//
  393. private:
  394. // Emit the abbreviation as a DEFINE_ABBREV record.
  395. void EncodeAbbrev(BitCodeAbbrev *Abbv) {
  396. EmitCode(bitc::DEFINE_ABBREV);
  397. EmitVBR(Abbv->getNumOperandInfos(), 5);
  398. for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
  399. i != e; ++i) {
  400. const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
  401. Emit(Op.isLiteral(), 1);
  402. if (Op.isLiteral()) {
  403. EmitVBR64(Op.getLiteralValue(), 8);
  404. } else {
  405. Emit(Op.getEncoding(), 3);
  406. if (Op.hasEncodingData())
  407. EmitVBR64(Op.getEncodingData(), 5);
  408. }
  409. }
  410. }
  411. public:
  412. /// EmitAbbrev - This emits an abbreviation to the stream. Note that this
  413. /// method takes ownership of the specified abbrev.
  414. unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
  415. // Emit the abbreviation as a record.
  416. EncodeAbbrev(Abbv);
  417. CurAbbrevs.push_back(Abbv);
  418. return static_cast<unsigned>(CurAbbrevs.size())-1 +
  419. bitc::FIRST_APPLICATION_ABBREV;
  420. }
  421. //===--------------------------------------------------------------------===//
  422. // BlockInfo Block Emission
  423. //===--------------------------------------------------------------------===//
  424. /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
  425. void EnterBlockInfoBlock(unsigned CodeWidth) {
  426. EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
  427. BlockInfoCurBID = ~0U;
  428. }
  429. private:
  430. /// SwitchToBlockID - If we aren't already talking about the specified block
  431. /// ID, emit a BLOCKINFO_CODE_SETBID record.
  432. void SwitchToBlockID(unsigned BlockID) {
  433. if (BlockInfoCurBID == BlockID) return;
  434. SmallVector<unsigned, 2> V;
  435. V.push_back(BlockID);
  436. EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
  437. BlockInfoCurBID = BlockID;
  438. }
  439. BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
  440. if (BlockInfo *BI = getBlockInfo(BlockID))
  441. return *BI;
  442. // Otherwise, add a new record.
  443. BlockInfoRecords.push_back(BlockInfo());
  444. BlockInfoRecords.back().BlockID = BlockID;
  445. return BlockInfoRecords.back();
  446. }
  447. public:
  448. /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
  449. /// BlockID.
  450. unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
  451. SwitchToBlockID(BlockID);
  452. EncodeAbbrev(Abbv);
  453. // Add the abbrev to the specified block record.
  454. BlockInfo &Info = getOrCreateBlockInfo(BlockID);
  455. Info.Abbrevs.push_back(Abbv);
  456. return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
  457. }
  458. };
  459. } // End llvm namespace
  460. #endif