25static std::optional<const char *>
31 return "BLOCKINFO_BLOCK";
37 BlockInfo.getBlockInfo(BlockID)) {
38 if (!Info->Name.empty())
39 return Info->Name.c_str();
49 return "OPERAND_BUNDLE_TAGS_BLOCK";
51 return "MODULE_BLOCK";
53 return "PARAMATTR_BLOCK";
55 return "PARAMATTR_GROUP_BLOCK_ID";
57 return "TYPE_BLOCK_ID";
59 return "CONSTANTS_BLOCK";
61 return "FUNCTION_BLOCK";
63 return "IDENTIFICATION_BLOCK_ID";
65 return "VALUE_SYMTAB";
67 return "METADATA_BLOCK";
69 return "METADATA_KIND_BLOCK";
71 return "METADATA_ATTACHMENT_BLOCK";
73 return "USELIST_BLOCK_ID";
75 return "GLOBALVAL_SUMMARY_BLOCK";
77 return "FULL_LTO_GLOBALVAL_SUMMARY_BLOCK";
79 return "MODULE_STRTAB_BLOCK";
81 return "STRTAB_BLOCK";
83 return "SYMTAB_BLOCK";
88static std::optional<const char *>
103 return "SETRECORDNAME";
111 BlockInfo.getBlockInfo(BlockID)) {
112 for (
const std::pair<unsigned, std::string> &RN : Info->RecordNames)
113 if (RN.first == CodeID)
114 return RN.second.c_str();
120#define STRINGIFY_CODE(PREFIX, CODE) \
121 case bitc::PREFIX##_##CODE: \
228 return "CST_CODE_BLOCKADDRESS";
398 return "USELIST_CODE_DEFAULT";
400 return "USELIST_CODE_BB";
408 return "OPERAND_BUNDLE_TAG";
429 OS <<
format(
"%.2f/%.2fB/%luW", Bits, Bits / 8, (
unsigned long)(Bits / 32));
432 OS <<
format(
"%lub/%.2fB/%luW", (
unsigned long)Bits, (
double)Bits / 8,
433 (
unsigned long)(Bits / 32));
437 auto tryRead = [&Stream](
char &Dest,
size_t size) ->
Error {
439 Dest = MaybeWord.get();
441 return MaybeWord.takeError();
446 if (
Error Err = tryRead(Signature[0], 8))
447 return std::move(Err);
448 if (
Error Err = tryRead(Signature[1], 8))
449 return std::move(Err);
452 if (Signature[0] ==
'C' && Signature[1] ==
'P') {
453 if (
Error Err = tryRead(Signature[2], 8))
454 return std::move(Err);
455 if (
Error Err = tryRead(Signature[3], 8))
456 return std::move(Err);
457 if (Signature[2] ==
'C' && Signature[3] ==
'H')
459 }
else if (Signature[0] ==
'D' && Signature[1] ==
'I') {
460 if (
Error Err = tryRead(Signature[2], 8))
461 return std::move(Err);
462 if (
Error Err = tryRead(Signature[3], 8))
463 return std::move(Err);
464 if (Signature[2] ==
'A' && Signature[3] ==
'G')
466 }
else if (Signature[0] ==
'R' && Signature[1] ==
'M') {
467 if (
Error Err = tryRead(Signature[2], 8))
468 return std::move(Err);
469 if (
Error Err = tryRead(Signature[3], 8))
470 return std::move(Err);
471 if (Signature[2] ==
'R' && Signature[3] ==
'K')
474 if (
Error Err = tryRead(Signature[2], 4))
475 return std::move(Err);
476 if (
Error Err = tryRead(Signature[3], 4))
477 return std::move(Err);
478 if (
Error Err = tryRead(Signature[4], 4))
479 return std::move(Err);
480 if (
Error Err = tryRead(Signature[5], 4))
481 return std::move(Err);
482 if (Signature[0] ==
'B' && Signature[1] ==
'C' && Signature[2] == 0x0 &&
483 Signature[3] == 0xC && Signature[4] == 0xE && Signature[5] == 0xD)
492 const unsigned char *BufPtr = (
const unsigned char *)Bytes.
data();
493 const unsigned char *EndBufPtr = BufPtr + Bytes.
size();
499 return reportError(
"Invalid bitcode wrapper header");
508 O->OS <<
"<BITCODE_WRAPPER_HEADER"
513 <<
" CPUType=" <<
format_hex(CPUType, 10) <<
"/>\n";
517 return reportError(
"Invalid bitcode wrapper header");
539 "Decoding metadata strings blob needs two record entries.");
541 unsigned NumStrings =
Record[0];
542 unsigned StringsOffset =
Record[1];
543 OS <<
" num-strings = " << NumStrings <<
" {\n";
545 StringRef Lengths = Blob.
slice(0, StringsOffset);
546 SimpleBitstreamCursor
R(Lengths);
547 StringRef Strings = Blob.
drop_front(StringsOffset);
549 if (
R.AtEndOfStream())
558 OS << Indent <<
" '";
562 }
while (--NumStrings);
564 OS << Indent <<
" }";
569 std::optional<StringRef> BlockInfoBuffer)
572 BlockInfoStream.emplace(*BlockInfoBuffer);
576 std::optional<StringRef> CheckHash) {
580 Stream.setBlockInfo(&BlockInfo);
584 if (BlockInfoStream) {
594 return reportError(
"Invalid record at top-level in block info file");
600 std::optional<BitstreamBlockInfo> NewBlockInfo;
603 .moveInto(NewBlockInfo))
606 return reportError(
"Malformed BlockInfoBlock in block info file");
607 BlockInfo = std::move(*NewBlockInfo);
617 while (!Stream.AtEndOfStream()) {
628 if (
Error E = parseBlock(MaybeBlockID.
get(), 0, O, CheckHash))
637 std::optional<StringRef>
Filename) {
638 uint64_t BufferSizeBits = Stream.getBitcodeBytes().size() * CHAR_BIT;
642 O.OS <<
"of " <<
Filename->data() <<
":\n";
643 O.OS <<
" Total size: ";
646 O.OS <<
" Stream type: ";
647 switch (CurStreamType) {
655 O.OS <<
"Clang Serialized AST\n";
658 O.OS <<
"Clang Serialized Diagnostics\n";
661 O.OS <<
"LLVM Remarks\n";
664 O.OS <<
" # Toplevel Blocks: " << NumTopBlocks <<
"\n";
668 O.OS <<
"Per-block Summary:\n";
669 for (
const auto &Stat : BlockIDStats) {
670 O.OS <<
" Block ID #" << Stat.first;
671 if (std::optional<const char *> BlockName =
673 O.OS <<
" (" << *BlockName <<
")";
676 const PerBlockIDStats &
Stats = Stat.second;
677 O.OS <<
" Num Instances: " <<
Stats.NumInstances <<
"\n";
678 O.OS <<
" Total Size: ";
681 double pct = (
Stats.NumBits * 100.0) / BufferSizeBits;
682 O.OS <<
" Percent of file: " <<
format(
"%2.4f%%", pct) <<
"\n";
683 if (
Stats.NumInstances > 1) {
684 O.OS <<
" Average Size: ";
687 O.OS <<
" Tot/Avg SubBlocks: " <<
Stats.NumSubBlocks <<
"/"
688 <<
Stats.NumSubBlocks / (double)
Stats.NumInstances <<
"\n";
689 O.OS <<
" Tot/Avg Abbrevs: " <<
Stats.NumAbbrevs <<
"/"
690 <<
Stats.NumAbbrevs / (double)
Stats.NumInstances <<
"\n";
691 O.OS <<
" Tot/Avg Records: " <<
Stats.NumRecords <<
"/"
692 <<
Stats.NumRecords / (double)
Stats.NumInstances <<
"\n";
694 O.OS <<
" Num SubBlocks: " <<
Stats.NumSubBlocks <<
"\n";
695 O.OS <<
" Num Abbrevs: " <<
Stats.NumAbbrevs <<
"\n";
696 O.OS <<
" Num Records: " <<
Stats.NumRecords <<
"\n";
698 if (
Stats.NumRecords) {
699 double pct = (
Stats.NumAbbreviatedRecords * 100.0) /
Stats.NumRecords;
700 O.OS <<
" Percent Abbrevs: " <<
format(
"%2.4f%%", pct) <<
"\n";
705 if (O.Histogram && !
Stats.CodeFreq.empty()) {
706 std::vector<std::pair<unsigned, unsigned>> FreqPairs;
707 for (
unsigned i = 0, e =
Stats.CodeFreq.size(); i != e; ++i)
708 if (
unsigned Freq =
Stats.CodeFreq[i].NumInstances)
709 FreqPairs.push_back(std::make_pair(Freq, i));
711 std::reverse(FreqPairs.begin(), FreqPairs.end());
713 O.OS <<
"\tRecord Histogram:\n";
714 O.OS <<
"\t\t Count # Bits b/Rec % Abv Record Kind\n";
715 for (
const auto &FreqPair : FreqPairs) {
716 const PerRecordStats &RecStats =
Stats.CodeFreq[FreqPair.second];
718 O.OS <<
format(
"\t\t%7d %9lu", RecStats.NumInstances,
719 (
unsigned long)RecStats.TotalBits);
721 if (RecStats.NumInstances > 1)
723 (
double)RecStats.TotalBits / RecStats.NumInstances);
727 if (RecStats.NumAbbrev)
728 O.OS <<
format(
" %7.2f", (
double)RecStats.NumAbbrev /
729 RecStats.NumInstances * 100);
734 if (std::optional<const char *> CodeName =
GetCodeName(
735 FreqPair.second, Stat.first, BlockInfo, CurStreamType))
736 O.OS << *CodeName <<
"\n";
738 O.OS <<
"UnknownCode" << FreqPair.second <<
"\n";
745Error BitcodeAnalyzer::parseBlock(
unsigned BlockID,
unsigned IndentLevel,
746 std::optional<BCDumpOptions> O,
747 std::optional<StringRef> CheckHash) {
748 std::string Indent(IndentLevel * 2,
' ');
752 PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
754 BlockStats.NumInstances++;
757 bool DumpRecords = O.has_value();
759 if (O && !O->DumpBlockinfo)
760 O->OS << Indent <<
"<BLOCKINFO_BLOCK/>\n";
761 std::optional<BitstreamBlockInfo> NewBlockInfo;
763 .moveInto(NewBlockInfo))
767 BlockInfo = std::move(*NewBlockInfo);
772 DumpRecords = O && O->DumpBlockinfo;
775 unsigned NumWords = 0;
782 std::optional<const char *> BlockName;
784 O->OS << Indent <<
"<";
785 if ((BlockName =
GetBlockName(BlockID, BlockInfo, CurStreamType)))
788 O->OS <<
"UnknownBlock" << BlockID;
790 if (!O->Symbolic && BlockName)
791 O->OS <<
" BlockID=" << BlockID;
793 O->OS <<
" NumWords=" << NumWords
797 SmallVector<uint64_t, 64>
Record;
800 uint64_t MetadataIndexOffset = 0;
804 if (Stream.AtEndOfStream())
807 uint64_t RecordStartBit = Stream.GetCurrentBitNo();
809 BitstreamEntry
Entry;
814 switch (
Entry.Kind) {
818 uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
819 BlockStats.NumBits += BlockBitEnd - BlockBitStart;
821 O->OS << Indent <<
"</";
823 O->OS << *BlockName <<
">\n";
825 O->OS <<
"UnknownBlock" << BlockID <<
">\n";
831 uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
832 if (
Error E = parseBlock(
Entry.ID, IndentLevel + 1, O, CheckHash))
834 ++BlockStats.NumSubBlocks;
835 uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
838 BlockBitStart += SubBlockBitEnd - SubBlockBitStart;
847 if (
Error Err = Stream.ReadAbbrevRecord())
849 ++BlockStats.NumAbbrevs;
855 ++BlockStats.NumRecords;
858 uint64_t CurrentRecordPos = Stream.GetCurrentBitNo();
860 if (
Error E = Stream.readRecord(
Entry.ID, Record, &Blob).moveInto(Code))
864 if (BlockStats.CodeFreq.size() <= Code)
865 BlockStats.CodeFreq.resize(Code + 1);
866 BlockStats.CodeFreq[
Code].NumInstances++;
867 BlockStats.CodeFreq[
Code].TotalBits +=
868 Stream.GetCurrentBitNo() - RecordStartBit;
870 BlockStats.CodeFreq[
Code].NumAbbrev++;
871 ++BlockStats.NumAbbreviatedRecords;
875 O->OS << Indent <<
" <";
876 std::optional<const char *> CodeName =
877 GetCodeName(Code, BlockID, BlockInfo, CurStreamType);
881 O->OS <<
"UnknownCode" <<
Code;
882 if (!
O->Symbolic && CodeName)
883 O->OS <<
" codeid=" <<
Code;
884 const BitCodeAbbrev *Abbv =
nullptr;
886 Expected<const BitCodeAbbrev *> MaybeAbbv = Stream.getAbbrev(
Entry.ID);
889 Abbv = MaybeAbbv.
get();
890 O->OS <<
" abbrevid=" <<
Entry.ID;
893 for (
unsigned i = 0, e =
Record.size(); i != e; ++i)
894 O->OS <<
" op" << i <<
"=" << (int64_t)Record[i];
901 O->OS <<
"(Invalid record)";
904 MetadataIndexOffset = Stream.GetCurrentBitNo() +
Offset;
908 O->OS <<
" (offset ";
909 if (MetadataIndexOffset == RecordStartBit)
912 O->OS <<
"mismatch: " << MetadataIndexOffset <<
" vs "
913 << RecordStartBit <<
")";
921 O->OS <<
" (invalid)";
925 std::array<uint8_t, 20> Hash;
926 Hasher.
update(*CheckHash);
928 int BlockSize = (CurrentRecordPos / 8) - BlockEntryPos;
929 auto Ptr = Stream.getPointerToByte(BlockEntryPos,
BlockSize);
933 std::array<uint8_t, 20> RecordedHash;
935 for (
auto &Val : Record) {
936 assert(!(Val >> 32) &&
"Unexpected high bits set");
940 if (Hash == RecordedHash)
943 O->OS <<
" (!mismatch!)";
954 assert(i + 2 == e &&
"Array op not second to last");
956 bool ArrayIsPrintable =
true;
957 for (
unsigned j = i - 1, je =
Record.size(); j != je; ++j) {
958 if (!
isPrint(
static_cast<unsigned char>(Record[j]))) {
959 ArrayIsPrintable =
false;
962 Str += (char)Record[j];
964 if (ArrayIsPrintable)
965 O->OS <<
" record string = '" << Str <<
"'";
972 if (
Error E = decodeMetadataStringsBlob(Indent, Record, Blob,
O->OS))
975 O->OS <<
" blob data = ";
976 if (
O->ShowBinaryBlobs) {
978 O->OS.write_escaped(Blob,
true) <<
"'";
980 bool BlobIsPrintable =
true;
982 if (!
isPrint(
static_cast<unsigned char>(
C))) {
983 BlobIsPrintable =
false;
988 O->OS <<
"'" << Blob <<
"'";
990 O->OS <<
"unprintable, " << Blob.size() <<
" bytes.";
999 if (
Error Err = Stream.JumpToBit(CurrentRecordPos))
1001 if (Expected<unsigned> Skipped = Stream.skipRecord(
Entry.ID))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define STRINGIFY_CODE(PREFIX, CODE)
static bool canDecodeBlob(unsigned Code, unsigned BlockID)
static std::optional< const char * > GetBlockName(unsigned BlockID, const BitstreamBlockInfo &BlockInfo, CurStreamTypeType CurStreamType)
Return a symbolic block name if known, otherwise return null.
static Expected< CurStreamTypeType > ReadSignature(BitstreamCursor &Stream)
static std::optional< const char * > GetCodeName(unsigned CodeID, unsigned BlockID, const BitstreamBlockInfo &BlockInfo, CurStreamTypeType CurStreamType)
Return a symbolic code name if known, otherwise return null.
static void printSize(raw_ostream &OS, double Bits)
static Expected< CurStreamTypeType > analyzeHeader(std::optional< BCDumpOptions > O, BitstreamCursor &Stream)
static Error reportError(StringRef Message)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define FUNCTION(NAME, NARG, ROUND_MODE, INTRINSIC)
#define KIND(ENUM, FIELD)
#define ENTRY(ASMNAME, ENUM)
block placement Basic Block Placement Stats
static constexpr StringLiteral Filename
static const int BlockSize
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
unsigned getNumOperandInfos() const
const BitCodeAbbrevOp & getOperandInfo(unsigned N) const
LLVM_ABI BitcodeAnalyzer(StringRef Buffer, std::optional< StringRef > BlockInfoBuffer=std::nullopt)
LLVM_ABI Error analyze(std::optional< BCDumpOptions > O=std::nullopt, std::optional< StringRef > CheckHash=std::nullopt)
Analyze the bitcode file.
LLVM_ABI void printStats(BCDumpOptions O, std::optional< StringRef > Filename=std::nullopt)
Print stats about the bitcode file.
This class maintains the abbreviations read from a block info block.
This represents a position within a bitcode file, implemented on top of a SimpleBitstreamCursor.
Error JumpToBit(uint64_t BitNo)
Reset the stream to the specified bit number.
uint64_t GetCurrentBitNo() const
Return the bit # of the bit we are reading.
Expected< unsigned > ReadSubBlockID()
Having read the ENTER_SUBBLOCK code, read the BlockID for the block.
ArrayRef< uint8_t > getBitcodeBytes() const
Expected< word_t > Read(unsigned NumBits)
LLVM_ABI Error EnterSubBlock(unsigned BlockID, unsigned *NumWordsP=nullptr)
Having read the ENTER_SUBBLOCK abbrevid, and enter the block.
Error SkipBlock()
Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body of this block.
uint64_t getCurrentByteNo() const
@ AF_DontAutoprocessAbbrevs
If this flag is used, abbrev entries are returned just like normal records.
Expected< unsigned > ReadCode()
LLVM_ABI Expected< std::optional< BitstreamBlockInfo > > ReadBlockInfoBlock(bool ReadBlockInfoNames=false)
Read and return a block info block from the bitstream.
unsigned getAbbrevIDWidth() const
Return the number of bits used to encode an abbrev #.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Digest more data.
LLVM_ABI std::array< uint8_t, 20 > result()
Return the current raw 160-bits SHA1 for the digested data since the last call to init().
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
constexpr size_t size() const
Get the string size.
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
This class implements an extremely fast bulk output stream that can only output to a stream.
raw_ostream & write_escaped(StringRef Str, bool UseHexEscapes=false)
Output Str, turning '\', '\t', ' ', '"', and anything that doesn't satisfy llvm::isPrint into an esca...
@ C
The default llvm calling convention, compatible with C.
@ BLOCKINFO_CODE_BLOCKNAME
@ BLOCKINFO_CODE_SETRECORDNAME
@ PARAMATTR_GROUP_BLOCK_ID
@ IDENTIFICATION_BLOCK_ID
@ GLOBALVAL_SUMMARY_BLOCK_ID
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
@ BLOCKINFO_BLOCK_ID
BLOCKINFO_BLOCK is used to define metadata about blocks, for example, standard abbrevs that should be...
@ FIRST_APPLICATION_BLOCKID
@ DEFINE_ABBREV
DEFINE_ABBREV - Defines an abbrev for the current block.
@ PARAMATTR_CODE_ENTRY_OLD
@ PARAMATTR_GRP_CODE_ENTRY
@ Skipped
Validation was skipped, as it was not needed.
NodeAddr< CodeNode * > Code
void write32be(void *P, uint32_t V)
uint32_t read32le(const void *P)
This is an optimization pass for GlobalISel generic memory operations.
void stable_sort(R &&Range)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
FormattedNumber format_hex(uint64_t N, unsigned Width, bool Upper=false)
format_hex - Output N as a fixed width hexadecimal.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
CurStreamTypeType
CurStreamTypeType - A type for CurStreamType.
@ ClangSerializedDiagnosticsBitstream
@ ClangSerializedASTBitstream
DWARFExpression::Operation Op
bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr, const unsigned char *&BufEnd, bool VerifyBufferSize)
SkipBitcodeWrapperHeader - Some systems wrap bc files with a special header for padding or other reas...
bool isPrint(char C)
Checks whether character C is printable.
bool isBitcodeWrapper(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcodeWrapper - Return true if the given bytes are the magic bytes for an LLVM IR bitcode wrapper.
This contains information emitted to BLOCKINFO_BLOCK blocks.