25static std::optional<const char *>
31 return "BLOCKINFO_BLOCK";
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";
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: \
227 return "CST_CODE_BLOCKADDRESS";
396 return "USELIST_CODE_DEFAULT";
398 return "USELIST_CODE_BB";
406 return "OPERAND_BUNDLE_TAG";
427 OS <<
format(
"%.2f/%.2fB/%luW", Bits, Bits / 8, (
unsigned long)(Bits / 32));
430 OS <<
format(
"%lub/%.2fB/%luW", (
unsigned long)Bits, (
double)Bits / 8,
431 (
unsigned long)(Bits / 32));
435 auto tryRead = [&Stream](
char &Dest,
size_t size) ->
Error {
437 Dest = MaybeWord.get();
439 return MaybeWord.takeError();
444 if (
Error Err = tryRead(Signature[0], 8))
445 return std::move(Err);
446 if (
Error Err = tryRead(Signature[1], 8))
447 return std::move(Err);
450 if (Signature[0] ==
'C' && Signature[1] ==
'P') {
451 if (
Error Err = tryRead(Signature[2], 8))
452 return std::move(Err);
453 if (
Error Err = tryRead(Signature[3], 8))
454 return std::move(Err);
455 if (Signature[2] ==
'C' && Signature[3] ==
'H')
457 }
else if (Signature[0] ==
'D' && Signature[1] ==
'I') {
458 if (
Error Err = tryRead(Signature[2], 8))
459 return std::move(Err);
460 if (
Error Err = tryRead(Signature[3], 8))
461 return std::move(Err);
462 if (Signature[2] ==
'A' && Signature[3] ==
'G')
464 }
else if (Signature[0] ==
'R' && Signature[1] ==
'M') {
465 if (
Error Err = tryRead(Signature[2], 8))
466 return std::move(Err);
467 if (
Error Err = tryRead(Signature[3], 8))
468 return std::move(Err);
469 if (Signature[2] ==
'R' && Signature[3] ==
'K')
472 if (
Error Err = tryRead(Signature[2], 4))
473 return std::move(Err);
474 if (
Error Err = tryRead(Signature[3], 4))
475 return std::move(Err);
476 if (
Error Err = tryRead(Signature[4], 4))
477 return std::move(Err);
478 if (
Error Err = tryRead(Signature[5], 4))
479 return std::move(Err);
480 if (Signature[0] ==
'B' && Signature[1] ==
'C' && Signature[2] == 0x0 &&
481 Signature[3] == 0xC && Signature[4] == 0xE && Signature[5] == 0xD)
490 const unsigned char *BufPtr = (
const unsigned char *)Bytes.
data();
491 const unsigned char *EndBufPtr = BufPtr + Bytes.
size();
497 return reportError(
"Invalid bitcode wrapper header");
506 O->OS <<
"<BITCODE_WRAPPER_HEADER"
511 <<
" CPUType=" <<
format_hex(CPUType, 10) <<
"/>\n";
515 return reportError(
"Invalid bitcode wrapper header");
537 "Decoding metadata strings blob needs two record entries.");
539 unsigned NumStrings =
Record[0];
540 unsigned StringsOffset =
Record[1];
541 OS <<
" num-strings = " << NumStrings <<
" {\n";
547 if (
R.AtEndOfStream())
553 if (Strings.size() <
Size)
556 OS << Indent <<
" '";
559 Strings = Strings.drop_front(
Size);
560 }
while (--NumStrings);
562 OS << Indent <<
" }";
567 std::optional<StringRef> BlockInfoBuffer)
570 BlockInfoStream.emplace(*BlockInfoBuffer);
574 std::optional<StringRef> CheckHash) {
582 if (BlockInfoStream) {
592 return reportError(
"Invalid record at top-level in block info file");
598 std::optional<BitstreamBlockInfo> NewBlockInfo;
601 .moveInto(NewBlockInfo))
604 return reportError(
"Malformed BlockInfoBlock in block info file");
605 BlockInfo = std::move(*NewBlockInfo);
626 if (
Error E = parseBlock(MaybeBlockID.
get(), 0, O, CheckHash))
635 std::optional<StringRef> Filename) {
640 O.OS <<
"of " << Filename->data() <<
":\n";
641 O.OS <<
" Total size: ";
644 O.OS <<
" Stream type: ";
645 switch (CurStreamType) {
653 O.OS <<
"Clang Serialized AST\n";
656 O.OS <<
"Clang Serialized Diagnostics\n";
659 O.OS <<
"LLVM Remarks\n";
662 O.OS <<
" # Toplevel Blocks: " << NumTopBlocks <<
"\n";
666 O.OS <<
"Per-block Summary:\n";
667 for (
const auto &Stat : BlockIDStats) {
668 O.OS <<
" Block ID #" << Stat.first;
669 if (std::optional<const char *> BlockName =
671 O.OS <<
" (" << *BlockName <<
")";
674 const PerBlockIDStats &
Stats = Stat.second;
675 O.OS <<
" Num Instances: " <<
Stats.NumInstances <<
"\n";
676 O.OS <<
" Total Size: ";
679 double pct = (
Stats.NumBits * 100.0) / BufferSizeBits;
680 O.OS <<
" Percent of file: " <<
format(
"%2.4f%%", pct) <<
"\n";
681 if (
Stats.NumInstances > 1) {
682 O.OS <<
" Average Size: ";
685 O.OS <<
" Tot/Avg SubBlocks: " <<
Stats.NumSubBlocks <<
"/"
686 <<
Stats.NumSubBlocks / (double)
Stats.NumInstances <<
"\n";
687 O.OS <<
" Tot/Avg Abbrevs: " <<
Stats.NumAbbrevs <<
"/"
688 <<
Stats.NumAbbrevs / (
double)
Stats.NumInstances <<
"\n";
689 O.OS <<
" Tot/Avg Records: " <<
Stats.NumRecords <<
"/"
690 <<
Stats.NumRecords / (double)
Stats.NumInstances <<
"\n";
692 O.OS <<
" Num SubBlocks: " <<
Stats.NumSubBlocks <<
"\n";
693 O.OS <<
" Num Abbrevs: " <<
Stats.NumAbbrevs <<
"\n";
694 O.OS <<
" Num Records: " <<
Stats.NumRecords <<
"\n";
696 if (
Stats.NumRecords) {
697 double pct = (
Stats.NumAbbreviatedRecords * 100.0) /
Stats.NumRecords;
698 O.OS <<
" Percent Abbrevs: " <<
format(
"%2.4f%%", pct) <<
"\n";
703 if (O.Histogram && !
Stats.CodeFreq.empty()) {
704 std::vector<std::pair<unsigned, unsigned>> FreqPairs;
705 for (
unsigned i = 0, e =
Stats.CodeFreq.size(); i != e; ++i)
706 if (
unsigned Freq =
Stats.CodeFreq[i].NumInstances)
707 FreqPairs.push_back(std::make_pair(Freq, i));
709 std::reverse(FreqPairs.begin(), FreqPairs.end());
711 O.OS <<
"\tRecord Histogram:\n";
712 O.OS <<
"\t\t Count # Bits b/Rec % Abv Record Kind\n";
713 for (
const auto &FreqPair : FreqPairs) {
714 const PerRecordStats &RecStats =
Stats.CodeFreq[FreqPair.second];
716 O.OS <<
format(
"\t\t%7d %9lu", RecStats.NumInstances,
717 (
unsigned long)RecStats.TotalBits);
719 if (RecStats.NumInstances > 1)
721 (
double)RecStats.TotalBits / RecStats.NumInstances);
725 if (RecStats.NumAbbrev)
726 O.OS <<
format(
" %7.2f", (
double)RecStats.NumAbbrev /
727 RecStats.NumInstances * 100);
732 if (std::optional<const char *> CodeName =
GetCodeName(
733 FreqPair.second, Stat.first, BlockInfo, CurStreamType))
734 O.OS << *CodeName <<
"\n";
736 O.OS <<
"UnknownCode" << FreqPair.second <<
"\n";
743Error BitcodeAnalyzer::parseBlock(
unsigned BlockID,
unsigned IndentLevel,
744 std::optional<BCDumpOptions> O,
745 std::optional<StringRef> CheckHash) {
746 std::string Indent(IndentLevel * 2,
' ');
750 PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
752 BlockStats.NumInstances++;
755 bool DumpRecords = O.has_value();
757 if (O && !O->DumpBlockinfo)
758 O->OS << Indent <<
"<BLOCKINFO_BLOCK/>\n";
759 std::optional<BitstreamBlockInfo> NewBlockInfo;
761 .moveInto(NewBlockInfo))
765 BlockInfo = std::move(*NewBlockInfo);
770 DumpRecords = O && O->DumpBlockinfo;
773 unsigned NumWords = 0;
780 std::optional<const char *> BlockName;
782 O->OS << Indent <<
"<";
783 if ((BlockName =
GetBlockName(BlockID, BlockInfo, CurStreamType)))
786 O->OS <<
"UnknownBlock" << BlockID;
788 if (!O->Symbolic && BlockName)
789 O->OS <<
" BlockID=" << BlockID;
791 O->OS <<
" NumWords=" << NumWords
812 switch (
Entry.Kind) {
817 BlockStats.NumBits += BlockBitEnd - BlockBitStart;
819 O->OS << Indent <<
"</";
821 O->OS << *BlockName <<
">\n";
823 O->OS <<
"UnknownBlock" << BlockID <<
">\n";
830 if (
Error E = parseBlock(
Entry.ID, IndentLevel + 1, O, CheckHash))
832 ++BlockStats.NumSubBlocks;
836 BlockBitStart += SubBlockBitEnd - SubBlockBitStart;
847 ++BlockStats.NumAbbrevs;
853 ++BlockStats.NumRecords;
862 if (BlockStats.CodeFreq.size() <= Code)
863 BlockStats.CodeFreq.resize(Code + 1);
864 BlockStats.CodeFreq[
Code].NumInstances++;
865 BlockStats.CodeFreq[
Code].TotalBits +=
868 BlockStats.CodeFreq[
Code].NumAbbrev++;
869 ++BlockStats.NumAbbreviatedRecords;
873 O->OS << Indent <<
" <";
874 std::optional<const char *> CodeName =
875 GetCodeName(Code, BlockID, BlockInfo, CurStreamType);
879 O->OS <<
"UnknownCode" <<
Code;
880 if (!
O->Symbolic && CodeName)
881 O->OS <<
" codeid=" <<
Code;
887 Abbv = MaybeAbbv.
get();
888 O->OS <<
" abbrevid=" <<
Entry.ID;
891 for (
unsigned i = 0, e =
Record.size(); i != e; ++i)
892 O->OS <<
" op" << i <<
"=" << (int64_t)
Record[i];
899 O->OS <<
"(Invalid record)";
906 O->OS <<
" (offset ";
907 if (MetadataIndexOffset == RecordStartBit)
910 O->OS <<
"mismatch: " << MetadataIndexOffset <<
" vs "
911 << RecordStartBit <<
")";
919 O->OS <<
" (invalid)";
923 std::array<uint8_t, 20> Hash;
924 Hasher.
update(*CheckHash);
926 int BlockSize = (CurrentRecordPos / 8) - BlockEntryPos;
929 Hash = Hasher.result();
931 std::array<uint8_t, 20> RecordedHash;
933 for (
auto &Val :
Record) {
934 assert(!(Val >> 32) &&
"Unexpected high bits set");
938 if (Hash == RecordedHash)
941 O->OS <<
" (!mismatch!)";
952 assert(i + 2 == e &&
"Array op not second to last");
954 bool ArrayIsPrintable =
true;
955 for (
unsigned j = i - 1, je =
Record.size(); j != je; ++j) {
957 ArrayIsPrintable =
false;
962 if (ArrayIsPrintable)
963 O->OS <<
" record string = '" << Str <<
"'";
970 if (
Error E = decodeMetadataStringsBlob(Indent,
Record, Blob,
O->OS))
973 O->OS <<
" blob data = ";
974 if (
O->ShowBinaryBlobs) {
976 O->OS.write_escaped(Blob,
true) <<
"'";
978 bool BlobIsPrintable =
true;
980 if (!
isPrint(
static_cast<unsigned char>(
C))) {
981 BlobIsPrintable =
false;
986 O->OS <<
"'" << Blob <<
"'";
988 O->OS <<
"unprintable, " << Blob.size() <<
" bytes.";
997 if (
Error Err = Stream.JumpToBit(CurrentRecordPos))
1002 return Skipped.takeError();
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)
Analysis containing CSE Info
#define FUNCTION(NAME, NARG, ROUND_MODE, INTRINSIC)
#define KIND(ENUM, FIELD)
#define ENTRY(ASMNAME, ENUM)
block placement Basic Block Placement Stats
static const int BlockSize
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
BitCodeAbbrevOp - This describes one or more operands in an abbreviation.
BitCodeAbbrev - This class represents an abbreviation record.
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.
const BlockInfo * getBlockInfo(unsigned BlockID) const
If there is block info for the specified ID, return it, otherwise return null.
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.
LLVM_ABI Error ReadAbbrevRecord()
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)
@ AF_DontAutoprocessAbbrevs
If this flag is used, abbrev entries are returned just like normal records.
Expected< BitstreamEntry > advance(unsigned Flags=0)
Advance the current bitstream, returning the next entry in the stream.
Expected< const BitCodeAbbrev * > getAbbrev(unsigned AbbrevID)
Return the abbreviation for the specified AbbrevId.
void setBlockInfo(BitstreamBlockInfo *BI)
Set the block info to be used by this BitstreamCursor to interpret abbreviated records.
const uint8_t * getPointerToByte(uint64_t ByteNo, uint64_t NumBytes)
Get a pointer into the bitstream at the specified byte offset.
LLVM_ABI Expected< unsigned > readRecord(unsigned AbbrevID, SmallVectorImpl< uint64_t > &Vals, StringRef *Blob=nullptr)
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
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 #.
This class represents an Operation in the Expression.
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.
A class that wrap the SHA1 algorithm.
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Digest more data.
This represents a position within a bitstream.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
constexpr bool empty() const
empty - 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 const char * data() const
data - 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
NodeAddr< CodeNode * > Code
void write32be(void *P, uint32_t V)
uint32_t read32le(const void *P)
LLVM_ABI bool isPrint(int c)
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
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 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.
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...