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