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