1 //===-- llvm-bcanalyzer.cpp - Bitcode Analyzer --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tool may be invoked in the following manner:
11 // llvm-bcanalyzer [options] - Read LLVM bitcode from stdin
12 // llvm-bcanalyzer [options] x.bc - Read LLVM bitcode from the x.bc file
15 // --help - Output information about command line switches
16 // --dump - Dump low-level bitcode structure in readable format
18 // This tool provides analytical information about a bitcode file. It is
19 // intended as an aid to developers of bitcode reading and writing software. It
20 // produces on std::out a summary of the bitcode file that shows various
21 // statistics about the contents of the file. By default this information is
22 // detailed and contains information about individual bitcode blocks and the
23 // functions in the module.
24 // The tool is also able to print a bitcode file in a straight forward text
25 // format that shows the containment and relationships of the information in
26 // the bitcode file (-dump option).
28 //===----------------------------------------------------------------------===//
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/Bitcode/BitcodeReader.h"
32 #include "llvm/Bitcode/BitstreamReader.h"
33 #include "llvm/Bitcode/LLVMBitCodes.h"
34 #include "llvm/IR/Verifier.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/ManagedStatic.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/PrettyStackTrace.h"
40 #include "llvm/Support/SHA1.h"
41 #include "llvm/Support/Signals.h"
42 #include "llvm/Support/raw_ostream.h"
46 #include <system_error>
49 static cl::opt<std::string>
50 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
52 static cl::opt<bool> Dump("dump", cl::desc("Dump low level bitcode trace"));
54 //===----------------------------------------------------------------------===//
55 // Bitcode specific analysis.
56 //===----------------------------------------------------------------------===//
58 static cl::opt<bool> NoHistogram("disable-histogram",
59 cl::desc("Do not print per-code histogram"));
62 NonSymbolic("non-symbolic",
63 cl::desc("Emit numeric info in dump even if"
64 " symbolic info is available"));
66 static cl::opt<std::string>
67 BlockInfoFilename("block-info",
68 cl::desc("Use the BLOCK_INFO from the given file"));
71 ShowBinaryBlobs("show-binary-blobs",
72 cl::desc("Print binary blobs using hex escapes"));
76 /// CurStreamTypeType - A type for CurStreamType
77 enum CurStreamTypeType {
84 /// GetBlockName - Return a symbolic block name if known, otherwise return
86 static const char *GetBlockName(unsigned BlockID,
87 const BitstreamBlockInfo &BlockInfo,
88 CurStreamTypeType CurStreamType) {
89 // Standard blocks for all bitcode files.
90 if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
91 if (BlockID == bitc::BLOCKINFO_BLOCK_ID)
92 return "BLOCKINFO_BLOCK";
96 // Check to see if we have a blockinfo record for this block, with a name.
97 if (const BitstreamBlockInfo::BlockInfo *Info =
98 BlockInfo.getBlockInfo(BlockID)) {
99 if (!Info->Name.empty())
100 return Info->Name.c_str();
104 if (CurStreamType != LLVMIRBitstream) return nullptr;
107 default: return nullptr;
108 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID: return "OPERAND_BUNDLE_TAGS_BLOCK";
109 case bitc::MODULE_BLOCK_ID: return "MODULE_BLOCK";
110 case bitc::PARAMATTR_BLOCK_ID: return "PARAMATTR_BLOCK";
111 case bitc::PARAMATTR_GROUP_BLOCK_ID: return "PARAMATTR_GROUP_BLOCK_ID";
112 case bitc::TYPE_BLOCK_ID_NEW: return "TYPE_BLOCK_ID";
113 case bitc::CONSTANTS_BLOCK_ID: return "CONSTANTS_BLOCK";
114 case bitc::FUNCTION_BLOCK_ID: return "FUNCTION_BLOCK";
115 case bitc::IDENTIFICATION_BLOCK_ID:
116 return "IDENTIFICATION_BLOCK_ID";
117 case bitc::VALUE_SYMTAB_BLOCK_ID: return "VALUE_SYMTAB";
118 case bitc::METADATA_BLOCK_ID: return "METADATA_BLOCK";
119 case bitc::METADATA_KIND_BLOCK_ID: return "METADATA_KIND_BLOCK";
120 case bitc::METADATA_ATTACHMENT_ID: return "METADATA_ATTACHMENT_BLOCK";
121 case bitc::USELIST_BLOCK_ID: return "USELIST_BLOCK_ID";
122 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
123 return "GLOBALVAL_SUMMARY_BLOCK";
124 case bitc::MODULE_STRTAB_BLOCK_ID: return "MODULE_STRTAB_BLOCK";
125 case bitc::STRTAB_BLOCK_ID: return "STRTAB_BLOCK";
129 /// GetCodeName - Return a symbolic code name if known, otherwise return
131 static const char *GetCodeName(unsigned CodeID, unsigned BlockID,
132 const BitstreamBlockInfo &BlockInfo,
133 CurStreamTypeType CurStreamType) {
134 // Standard blocks for all bitcode files.
135 if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
136 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
138 default: return nullptr;
139 case bitc::BLOCKINFO_CODE_SETBID: return "SETBID";
140 case bitc::BLOCKINFO_CODE_BLOCKNAME: return "BLOCKNAME";
141 case bitc::BLOCKINFO_CODE_SETRECORDNAME: return "SETRECORDNAME";
147 // Check to see if we have a blockinfo record for this record, with a name.
148 if (const BitstreamBlockInfo::BlockInfo *Info =
149 BlockInfo.getBlockInfo(BlockID)) {
150 for (unsigned i = 0, e = Info->RecordNames.size(); i != e; ++i)
151 if (Info->RecordNames[i].first == CodeID)
152 return Info->RecordNames[i].second.c_str();
156 if (CurStreamType != LLVMIRBitstream) return nullptr;
158 #define STRINGIFY_CODE(PREFIX, CODE) \
159 case bitc::PREFIX##_##CODE: \
162 default: return nullptr;
163 case bitc::MODULE_BLOCK_ID:
165 default: return nullptr;
166 STRINGIFY_CODE(MODULE_CODE, VERSION)
167 STRINGIFY_CODE(MODULE_CODE, TRIPLE)
168 STRINGIFY_CODE(MODULE_CODE, DATALAYOUT)
169 STRINGIFY_CODE(MODULE_CODE, ASM)
170 STRINGIFY_CODE(MODULE_CODE, SECTIONNAME)
171 STRINGIFY_CODE(MODULE_CODE, DEPLIB) // FIXME: Remove in 4.0
172 STRINGIFY_CODE(MODULE_CODE, GLOBALVAR)
173 STRINGIFY_CODE(MODULE_CODE, FUNCTION)
174 STRINGIFY_CODE(MODULE_CODE, ALIAS)
175 STRINGIFY_CODE(MODULE_CODE, GCNAME)
176 STRINGIFY_CODE(MODULE_CODE, VSTOFFSET)
177 STRINGIFY_CODE(MODULE_CODE, METADATA_VALUES_UNUSED)
178 STRINGIFY_CODE(MODULE_CODE, SOURCE_FILENAME)
179 STRINGIFY_CODE(MODULE_CODE, HASH)
181 case bitc::IDENTIFICATION_BLOCK_ID:
185 STRINGIFY_CODE(IDENTIFICATION_CODE, STRING)
186 STRINGIFY_CODE(IDENTIFICATION_CODE, EPOCH)
188 case bitc::PARAMATTR_BLOCK_ID:
190 default: return nullptr;
191 // FIXME: Should these be different?
192 case bitc::PARAMATTR_CODE_ENTRY_OLD: return "ENTRY";
193 case bitc::PARAMATTR_CODE_ENTRY: return "ENTRY";
195 case bitc::PARAMATTR_GROUP_BLOCK_ID:
197 default: return nullptr;
198 case bitc::PARAMATTR_GRP_CODE_ENTRY: return "ENTRY";
200 case bitc::TYPE_BLOCK_ID_NEW:
202 default: return nullptr;
203 STRINGIFY_CODE(TYPE_CODE, NUMENTRY)
204 STRINGIFY_CODE(TYPE_CODE, VOID)
205 STRINGIFY_CODE(TYPE_CODE, FLOAT)
206 STRINGIFY_CODE(TYPE_CODE, DOUBLE)
207 STRINGIFY_CODE(TYPE_CODE, LABEL)
208 STRINGIFY_CODE(TYPE_CODE, OPAQUE)
209 STRINGIFY_CODE(TYPE_CODE, INTEGER)
210 STRINGIFY_CODE(TYPE_CODE, POINTER)
211 STRINGIFY_CODE(TYPE_CODE, ARRAY)
212 STRINGIFY_CODE(TYPE_CODE, VECTOR)
213 STRINGIFY_CODE(TYPE_CODE, X86_FP80)
214 STRINGIFY_CODE(TYPE_CODE, FP128)
215 STRINGIFY_CODE(TYPE_CODE, PPC_FP128)
216 STRINGIFY_CODE(TYPE_CODE, METADATA)
217 STRINGIFY_CODE(TYPE_CODE, STRUCT_ANON)
218 STRINGIFY_CODE(TYPE_CODE, STRUCT_NAME)
219 STRINGIFY_CODE(TYPE_CODE, STRUCT_NAMED)
220 STRINGIFY_CODE(TYPE_CODE, FUNCTION)
223 case bitc::CONSTANTS_BLOCK_ID:
225 default: return nullptr;
226 STRINGIFY_CODE(CST_CODE, SETTYPE)
227 STRINGIFY_CODE(CST_CODE, NULL)
228 STRINGIFY_CODE(CST_CODE, UNDEF)
229 STRINGIFY_CODE(CST_CODE, INTEGER)
230 STRINGIFY_CODE(CST_CODE, WIDE_INTEGER)
231 STRINGIFY_CODE(CST_CODE, FLOAT)
232 STRINGIFY_CODE(CST_CODE, AGGREGATE)
233 STRINGIFY_CODE(CST_CODE, STRING)
234 STRINGIFY_CODE(CST_CODE, CSTRING)
235 STRINGIFY_CODE(CST_CODE, CE_BINOP)
236 STRINGIFY_CODE(CST_CODE, CE_CAST)
237 STRINGIFY_CODE(CST_CODE, CE_GEP)
238 STRINGIFY_CODE(CST_CODE, CE_INBOUNDS_GEP)
239 STRINGIFY_CODE(CST_CODE, CE_SELECT)
240 STRINGIFY_CODE(CST_CODE, CE_EXTRACTELT)
241 STRINGIFY_CODE(CST_CODE, CE_INSERTELT)
242 STRINGIFY_CODE(CST_CODE, CE_SHUFFLEVEC)
243 STRINGIFY_CODE(CST_CODE, CE_CMP)
244 STRINGIFY_CODE(CST_CODE, INLINEASM)
245 STRINGIFY_CODE(CST_CODE, CE_SHUFVEC_EX)
246 case bitc::CST_CODE_BLOCKADDRESS: return "CST_CODE_BLOCKADDRESS";
247 STRINGIFY_CODE(CST_CODE, DATA)
249 case bitc::FUNCTION_BLOCK_ID:
251 default: return nullptr;
252 STRINGIFY_CODE(FUNC_CODE, DECLAREBLOCKS)
253 STRINGIFY_CODE(FUNC_CODE, INST_BINOP)
254 STRINGIFY_CODE(FUNC_CODE, INST_CAST)
255 STRINGIFY_CODE(FUNC_CODE, INST_GEP_OLD)
256 STRINGIFY_CODE(FUNC_CODE, INST_INBOUNDS_GEP_OLD)
257 STRINGIFY_CODE(FUNC_CODE, INST_SELECT)
258 STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTELT)
259 STRINGIFY_CODE(FUNC_CODE, INST_INSERTELT)
260 STRINGIFY_CODE(FUNC_CODE, INST_SHUFFLEVEC)
261 STRINGIFY_CODE(FUNC_CODE, INST_CMP)
262 STRINGIFY_CODE(FUNC_CODE, INST_RET)
263 STRINGIFY_CODE(FUNC_CODE, INST_BR)
264 STRINGIFY_CODE(FUNC_CODE, INST_SWITCH)
265 STRINGIFY_CODE(FUNC_CODE, INST_INVOKE)
266 STRINGIFY_CODE(FUNC_CODE, INST_UNREACHABLE)
267 STRINGIFY_CODE(FUNC_CODE, INST_CLEANUPRET)
268 STRINGIFY_CODE(FUNC_CODE, INST_CATCHRET)
269 STRINGIFY_CODE(FUNC_CODE, INST_CATCHPAD)
270 STRINGIFY_CODE(FUNC_CODE, INST_PHI)
271 STRINGIFY_CODE(FUNC_CODE, INST_ALLOCA)
272 STRINGIFY_CODE(FUNC_CODE, INST_LOAD)
273 STRINGIFY_CODE(FUNC_CODE, INST_VAARG)
274 STRINGIFY_CODE(FUNC_CODE, INST_STORE)
275 STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTVAL)
276 STRINGIFY_CODE(FUNC_CODE, INST_INSERTVAL)
277 STRINGIFY_CODE(FUNC_CODE, INST_CMP2)
278 STRINGIFY_CODE(FUNC_CODE, INST_VSELECT)
279 STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC_AGAIN)
280 STRINGIFY_CODE(FUNC_CODE, INST_CALL)
281 STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC)
282 STRINGIFY_CODE(FUNC_CODE, INST_GEP)
283 STRINGIFY_CODE(FUNC_CODE, OPERAND_BUNDLE)
285 case bitc::VALUE_SYMTAB_BLOCK_ID:
287 default: return nullptr;
288 STRINGIFY_CODE(VST_CODE, ENTRY)
289 STRINGIFY_CODE(VST_CODE, BBENTRY)
290 STRINGIFY_CODE(VST_CODE, FNENTRY)
291 STRINGIFY_CODE(VST_CODE, COMBINED_ENTRY)
293 case bitc::MODULE_STRTAB_BLOCK_ID:
297 STRINGIFY_CODE(MST_CODE, ENTRY)
298 STRINGIFY_CODE(MST_CODE, HASH)
300 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
304 STRINGIFY_CODE(FS, PERMODULE)
305 STRINGIFY_CODE(FS, PERMODULE_PROFILE)
306 STRINGIFY_CODE(FS, PERMODULE_GLOBALVAR_INIT_REFS)
307 STRINGIFY_CODE(FS, COMBINED)
308 STRINGIFY_CODE(FS, COMBINED_PROFILE)
309 STRINGIFY_CODE(FS, COMBINED_GLOBALVAR_INIT_REFS)
310 STRINGIFY_CODE(FS, ALIAS)
311 STRINGIFY_CODE(FS, COMBINED_ALIAS)
312 STRINGIFY_CODE(FS, COMBINED_ORIGINAL_NAME)
313 STRINGIFY_CODE(FS, VERSION)
314 STRINGIFY_CODE(FS, TYPE_TESTS)
315 STRINGIFY_CODE(FS, TYPE_TEST_ASSUME_VCALLS)
316 STRINGIFY_CODE(FS, TYPE_CHECKED_LOAD_VCALLS)
317 STRINGIFY_CODE(FS, TYPE_TEST_ASSUME_CONST_VCALL)
318 STRINGIFY_CODE(FS, TYPE_CHECKED_LOAD_CONST_VCALL)
319 STRINGIFY_CODE(FS, VALUE_GUID)
321 case bitc::METADATA_ATTACHMENT_ID:
323 default:return nullptr;
324 STRINGIFY_CODE(METADATA, ATTACHMENT)
326 case bitc::METADATA_BLOCK_ID:
328 default:return nullptr;
329 STRINGIFY_CODE(METADATA, STRING_OLD)
330 STRINGIFY_CODE(METADATA, VALUE)
331 STRINGIFY_CODE(METADATA, NODE)
332 STRINGIFY_CODE(METADATA, NAME)
333 STRINGIFY_CODE(METADATA, DISTINCT_NODE)
334 STRINGIFY_CODE(METADATA, KIND) // Older bitcode has it in a MODULE_BLOCK
335 STRINGIFY_CODE(METADATA, LOCATION)
336 STRINGIFY_CODE(METADATA, OLD_NODE)
337 STRINGIFY_CODE(METADATA, OLD_FN_NODE)
338 STRINGIFY_CODE(METADATA, NAMED_NODE)
339 STRINGIFY_CODE(METADATA, GENERIC_DEBUG)
340 STRINGIFY_CODE(METADATA, SUBRANGE)
341 STRINGIFY_CODE(METADATA, ENUMERATOR)
342 STRINGIFY_CODE(METADATA, BASIC_TYPE)
343 STRINGIFY_CODE(METADATA, FILE)
344 STRINGIFY_CODE(METADATA, DERIVED_TYPE)
345 STRINGIFY_CODE(METADATA, COMPOSITE_TYPE)
346 STRINGIFY_CODE(METADATA, SUBROUTINE_TYPE)
347 STRINGIFY_CODE(METADATA, COMPILE_UNIT)
348 STRINGIFY_CODE(METADATA, SUBPROGRAM)
349 STRINGIFY_CODE(METADATA, LEXICAL_BLOCK)
350 STRINGIFY_CODE(METADATA, LEXICAL_BLOCK_FILE)
351 STRINGIFY_CODE(METADATA, NAMESPACE)
352 STRINGIFY_CODE(METADATA, TEMPLATE_TYPE)
353 STRINGIFY_CODE(METADATA, TEMPLATE_VALUE)
354 STRINGIFY_CODE(METADATA, GLOBAL_VAR)
355 STRINGIFY_CODE(METADATA, LOCAL_VAR)
356 STRINGIFY_CODE(METADATA, EXPRESSION)
357 STRINGIFY_CODE(METADATA, OBJC_PROPERTY)
358 STRINGIFY_CODE(METADATA, IMPORTED_ENTITY)
359 STRINGIFY_CODE(METADATA, MODULE)
360 STRINGIFY_CODE(METADATA, MACRO)
361 STRINGIFY_CODE(METADATA, MACRO_FILE)
362 STRINGIFY_CODE(METADATA, STRINGS)
363 STRINGIFY_CODE(METADATA, GLOBAL_DECL_ATTACHMENT)
364 STRINGIFY_CODE(METADATA, GLOBAL_VAR_EXPR)
365 STRINGIFY_CODE(METADATA, INDEX_OFFSET)
366 STRINGIFY_CODE(METADATA, INDEX)
368 case bitc::METADATA_KIND_BLOCK_ID:
372 STRINGIFY_CODE(METADATA, KIND)
374 case bitc::USELIST_BLOCK_ID:
376 default:return nullptr;
377 case bitc::USELIST_CODE_DEFAULT: return "USELIST_CODE_DEFAULT";
378 case bitc::USELIST_CODE_BB: return "USELIST_CODE_BB";
381 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
383 default: return nullptr;
384 case bitc::OPERAND_BUNDLE_TAG: return "OPERAND_BUNDLE_TAG";
386 case bitc::STRTAB_BLOCK_ID:
388 default: return nullptr;
389 case bitc::STRTAB_BLOB: return "BLOB";
392 #undef STRINGIFY_CODE
395 struct PerRecordStats {
396 unsigned NumInstances;
400 PerRecordStats() : NumInstances(0), NumAbbrev(0), TotalBits(0) {}
403 struct PerBlockIDStats {
404 /// NumInstances - This the number of times this block ID has been seen.
405 unsigned NumInstances;
407 /// NumBits - The total size in bits of all of these blocks.
410 /// NumSubBlocks - The total number of blocks these blocks contain.
411 unsigned NumSubBlocks;
413 /// NumAbbrevs - The total number of abbreviations.
416 /// NumRecords - The total number of records these blocks contain, and the
417 /// number that are abbreviated.
418 unsigned NumRecords, NumAbbreviatedRecords;
420 /// CodeFreq - Keep track of the number of times we see each code.
421 std::vector<PerRecordStats> CodeFreq;
424 : NumInstances(0), NumBits(0),
425 NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {}
428 static std::map<unsigned, PerBlockIDStats> BlockIDStats;
432 /// ReportError - All bitcode analysis errors go through this function, making this a
433 /// good place to breakpoint if debugging.
434 static bool ReportError(const Twine &Err) {
435 errs() << Err << "\n";
439 static bool decodeMetadataStringsBlob(StringRef Indent,
440 ArrayRef<uint64_t> Record,
445 if (Record.size() != 2)
448 unsigned NumStrings = Record[0];
449 unsigned StringsOffset = Record[1];
450 outs() << " num-strings = " << NumStrings << " {\n";
452 StringRef Lengths = Blob.slice(0, StringsOffset);
453 SimpleBitstreamCursor R(Lengths);
454 StringRef Strings = Blob.drop_front(StringsOffset);
456 if (R.AtEndOfStream())
457 return ReportError("bad length");
459 unsigned Size = R.ReadVBR(6);
460 if (Strings.size() < Size)
461 return ReportError("truncated chars");
463 outs() << Indent << " '";
464 outs().write_escaped(Strings.slice(0, Size), /*hex=*/true);
466 Strings = Strings.drop_front(Size);
467 } while (--NumStrings);
469 outs() << Indent << " }";
473 static bool decodeBlob(unsigned Code, unsigned BlockID, StringRef Indent,
474 ArrayRef<uint64_t> Record, StringRef Blob) {
475 if (BlockID != bitc::METADATA_BLOCK_ID)
477 if (Code != bitc::METADATA_STRINGS)
480 return decodeMetadataStringsBlob(Indent, Record, Blob);
483 /// ParseBlock - Read a block, updating statistics, etc.
484 static bool ParseBlock(BitstreamCursor &Stream, BitstreamBlockInfo &BlockInfo,
485 unsigned BlockID, unsigned IndentLevel,
486 CurStreamTypeType CurStreamType) {
487 std::string Indent(IndentLevel*2, ' ');
488 uint64_t BlockBitStart = Stream.GetCurrentBitNo();
490 // Get the statistics for this BlockID.
491 PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
493 BlockStats.NumInstances++;
495 // BLOCKINFO is a special part of the stream.
496 bool DumpRecords = Dump;
497 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
498 if (Dump) outs() << Indent << "<BLOCKINFO_BLOCK/>\n";
499 Optional<BitstreamBlockInfo> NewBlockInfo =
500 Stream.ReadBlockInfoBlock(/*ReadBlockInfoNames=*/true);
502 return ReportError("Malformed BlockInfoBlock");
503 BlockInfo = std::move(*NewBlockInfo);
504 Stream.JumpToBit(BlockBitStart);
505 // It's not really interesting to dump the contents of the blockinfo block.
509 unsigned NumWords = 0;
510 if (Stream.EnterSubBlock(BlockID, &NumWords))
511 return ReportError("Malformed block record");
513 // Keep it for later, when we see a MODULE_HASH record
514 uint64_t BlockEntryPos = Stream.getCurrentByteNo();
516 const char *BlockName = nullptr;
518 outs() << Indent << "<";
519 if ((BlockName = GetBlockName(BlockID, BlockInfo, CurStreamType)))
522 outs() << "UnknownBlock" << BlockID;
524 if (NonSymbolic && BlockName)
525 outs() << " BlockID=" << BlockID;
527 outs() << " NumWords=" << NumWords
528 << " BlockCodeSize=" << Stream.getAbbrevIDWidth() << ">\n";
531 SmallVector<uint64_t, 64> Record;
533 // Keep the offset to the metadata index if seen.
534 uint64_t MetadataIndexOffset = 0;
536 // Read all the records for this block.
538 if (Stream.AtEndOfStream())
539 return ReportError("Premature end of bitstream");
541 uint64_t RecordStartBit = Stream.GetCurrentBitNo();
543 BitstreamEntry Entry =
544 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
546 switch (Entry.Kind) {
547 case BitstreamEntry::Error:
548 return ReportError("malformed bitcode file");
549 case BitstreamEntry::EndBlock: {
550 uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
551 BlockStats.NumBits += BlockBitEnd-BlockBitStart;
553 outs() << Indent << "</";
555 outs() << BlockName << ">\n";
557 outs() << "UnknownBlock" << BlockID << ">\n";
562 case BitstreamEntry::SubBlock: {
563 uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
564 if (ParseBlock(Stream, BlockInfo, Entry.ID, IndentLevel + 1,
567 ++BlockStats.NumSubBlocks;
568 uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
570 // Don't include subblock sizes in the size of this block.
571 BlockBitStart += SubBlockBitEnd-SubBlockBitStart;
574 case BitstreamEntry::Record:
575 // The interesting case.
579 if (Entry.ID == bitc::DEFINE_ABBREV) {
580 Stream.ReadAbbrevRecord();
581 ++BlockStats.NumAbbrevs;
587 ++BlockStats.NumRecords;
590 unsigned CurrentRecordPos = Stream.GetCurrentBitNo();
591 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
593 // Increment the # occurrences of this code.
594 if (BlockStats.CodeFreq.size() <= Code)
595 BlockStats.CodeFreq.resize(Code+1);
596 BlockStats.CodeFreq[Code].NumInstances++;
597 BlockStats.CodeFreq[Code].TotalBits +=
598 Stream.GetCurrentBitNo()-RecordStartBit;
599 if (Entry.ID != bitc::UNABBREV_RECORD) {
600 BlockStats.CodeFreq[Code].NumAbbrev++;
601 ++BlockStats.NumAbbreviatedRecords;
605 outs() << Indent << " <";
606 if (const char *CodeName =
607 GetCodeName(Code, BlockID, BlockInfo, CurStreamType))
610 outs() << "UnknownCode" << Code;
611 if (NonSymbolic && GetCodeName(Code, BlockID, BlockInfo, CurStreamType))
612 outs() << " codeid=" << Code;
613 const BitCodeAbbrev *Abbv = nullptr;
614 if (Entry.ID != bitc::UNABBREV_RECORD) {
615 Abbv = Stream.getAbbrev(Entry.ID);
616 outs() << " abbrevid=" << Entry.ID;
619 for (unsigned i = 0, e = Record.size(); i != e; ++i)
620 outs() << " op" << i << "=" << (int64_t)Record[i];
622 // If we found a metadata index, let's verify that we had an offset before
623 // and validate its forward reference offset was correct!
624 if (BlockID == bitc::METADATA_BLOCK_ID) {
625 if (Code == bitc::METADATA_INDEX_OFFSET) {
626 if (Record.size() != 2)
627 outs() << "(Invalid record)";
629 auto Offset = Record[0] + (Record[1] << 32);
630 MetadataIndexOffset = Stream.GetCurrentBitNo() + Offset;
633 if (Code == bitc::METADATA_INDEX) {
634 outs() << " (offset ";
635 if (MetadataIndexOffset == RecordStartBit)
638 outs() << "mismatch: " << MetadataIndexOffset << " vs "
639 << RecordStartBit << ")";
643 // If we found a module hash, let's verify that it matches!
644 if (BlockID == bitc::MODULE_BLOCK_ID && Code == bitc::MODULE_CODE_HASH) {
645 if (Record.size() != 5)
646 outs() << " (invalid)";
648 // Recompute the hash and compare it to the one in the bitcode
652 int BlockSize = (CurrentRecordPos / 8) - BlockEntryPos;
653 auto Ptr = Stream.getPointerToByte(BlockEntryPos, BlockSize);
654 Hasher.update(ArrayRef<uint8_t>(Ptr, BlockSize));
655 Hash = Hasher.result();
657 SmallString<20> RecordedHash;
658 RecordedHash.resize(20);
660 for (auto &Val : Record) {
661 assert(!(Val >> 32) && "Unexpected high bits set");
662 RecordedHash[Pos++] = (Val >> 24) & 0xFF;
663 RecordedHash[Pos++] = (Val >> 16) & 0xFF;
664 RecordedHash[Pos++] = (Val >> 8) & 0xFF;
665 RecordedHash[Pos++] = (Val >> 0) & 0xFF;
667 if (Hash == RecordedHash)
668 outs() << " (match)";
670 outs() << " (!mismatch!)";
677 for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i != e; ++i) {
678 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
679 if (!Op.isEncoding() || Op.getEncoding() != BitCodeAbbrevOp::Array)
681 assert(i + 2 == e && "Array op not second to last");
683 bool ArrayIsPrintable = true;
684 for (unsigned j = i - 1, je = Record.size(); j != je; ++j) {
685 if (!isprint(static_cast<unsigned char>(Record[j]))) {
686 ArrayIsPrintable = false;
689 Str += (char)Record[j];
691 if (ArrayIsPrintable)
692 outs() << " record string = '" << Str << "'";
697 if (Blob.data() && decodeBlob(Code, BlockID, Indent, Record, Blob)) {
698 outs() << " blob data = ";
699 if (ShowBinaryBlobs) {
701 outs().write_escaped(Blob, /*hex=*/true) << "'";
703 bool BlobIsPrintable = true;
704 for (unsigned i = 0, e = Blob.size(); i != e; ++i)
705 if (!isprint(static_cast<unsigned char>(Blob[i]))) {
706 BlobIsPrintable = false;
711 outs() << "'" << Blob << "'";
713 outs() << "unprintable, " << Blob.size() << " bytes.";
720 // Make sure that we can skip the current record.
721 Stream.JumpToBit(CurrentRecordPos);
722 Stream.skipRecord(Entry.ID);
726 static void PrintSize(double Bits) {
727 outs() << format("%.2f/%.2fB/%luW", Bits, Bits/8,(unsigned long)(Bits/32));
729 static void PrintSize(uint64_t Bits) {
730 outs() << format("%lub/%.2fB/%luW", (unsigned long)Bits,
731 (double)Bits/8, (unsigned long)(Bits/32));
734 static bool openBitcodeFile(StringRef Path,
735 std::unique_ptr<MemoryBuffer> &MemBuf,
736 BitstreamCursor &Stream,
737 CurStreamTypeType &CurStreamType) {
738 // Read the input file.
739 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
740 MemoryBuffer::getFileOrSTDIN(Path);
741 if (std::error_code EC = MemBufOrErr.getError())
742 return ReportError(Twine("ReportError reading '") + Path + "': " + EC.message());
743 MemBuf = std::move(MemBufOrErr.get());
745 if (MemBuf->getBufferSize() & 3)
746 return ReportError("Bitcode stream should be a multiple of 4 bytes in length");
748 const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
749 const unsigned char *EndBufPtr = BufPtr + MemBuf->getBufferSize();
751 // If we have a wrapper header, parse it and ignore the non-bc file contents.
752 // The magic number is 0x0B17C0DE stored in little endian.
753 if (isBitcodeWrapper(BufPtr, EndBufPtr)) {
754 if (MemBuf->getBufferSize() < BWH_HeaderSize)
755 return ReportError("Invalid bitcode wrapper header");
758 unsigned Magic = support::endian::read32le(&BufPtr[BWH_MagicField]);
759 unsigned Version = support::endian::read32le(&BufPtr[BWH_VersionField]);
760 unsigned Offset = support::endian::read32le(&BufPtr[BWH_OffsetField]);
761 unsigned Size = support::endian::read32le(&BufPtr[BWH_SizeField]);
762 unsigned CPUType = support::endian::read32le(&BufPtr[BWH_CPUTypeField]);
764 outs() << "<BITCODE_WRAPPER_HEADER"
765 << " Magic=" << format_hex(Magic, 10)
766 << " Version=" << format_hex(Version, 10)
767 << " Offset=" << format_hex(Offset, 10)
768 << " Size=" << format_hex(Size, 10)
769 << " CPUType=" << format_hex(CPUType, 10) << "/>\n";
772 if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr, true))
773 return ReportError("Invalid bitcode wrapper header");
776 Stream = BitstreamCursor(ArrayRef<uint8_t>(BufPtr, EndBufPtr));
778 // Read the stream signature.
780 Signature[0] = Stream.Read(8);
781 Signature[1] = Stream.Read(8);
782 Signature[2] = Stream.Read(4);
783 Signature[3] = Stream.Read(4);
784 Signature[4] = Stream.Read(4);
785 Signature[5] = Stream.Read(4);
787 // Autodetect the file contents, if it is one we know.
788 CurStreamType = UnknownBitstream;
789 if (Signature[0] == 'B' && Signature[1] == 'C' &&
790 Signature[2] == 0x0 && Signature[3] == 0xC &&
791 Signature[4] == 0xE && Signature[5] == 0xD)
792 CurStreamType = LLVMIRBitstream;
797 /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
798 static int AnalyzeBitcode() {
799 std::unique_ptr<MemoryBuffer> StreamBuffer;
800 BitstreamCursor Stream;
801 BitstreamBlockInfo BlockInfo;
802 CurStreamTypeType CurStreamType;
803 if (openBitcodeFile(InputFilename, StreamBuffer, Stream, CurStreamType))
805 Stream.setBlockInfo(&BlockInfo);
807 // Read block info from BlockInfoFilename, if specified.
808 // The block info must be a top-level block.
809 if (!BlockInfoFilename.empty()) {
810 std::unique_ptr<MemoryBuffer> BlockInfoBuffer;
811 BitstreamCursor BlockInfoCursor;
812 CurStreamTypeType BlockInfoStreamType;
813 if (openBitcodeFile(BlockInfoFilename, BlockInfoBuffer, BlockInfoCursor,
814 BlockInfoStreamType))
817 while (!BlockInfoCursor.AtEndOfStream()) {
818 unsigned Code = BlockInfoCursor.ReadCode();
819 if (Code != bitc::ENTER_SUBBLOCK)
820 return ReportError("Invalid record at top-level in block info file");
822 unsigned BlockID = BlockInfoCursor.ReadSubBlockID();
823 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
824 Optional<BitstreamBlockInfo> NewBlockInfo =
825 BlockInfoCursor.ReadBlockInfoBlock(/*ReadBlockInfoNames=*/true);
827 return ReportError("Malformed BlockInfoBlock in block info file");
828 BlockInfo = std::move(*NewBlockInfo);
832 BlockInfoCursor.SkipBlock();
836 unsigned NumTopBlocks = 0;
838 // Parse the top-level structure. We only allow blocks at the top-level.
839 while (!Stream.AtEndOfStream()) {
840 unsigned Code = Stream.ReadCode();
841 if (Code != bitc::ENTER_SUBBLOCK)
842 return ReportError("Invalid record at top-level");
844 unsigned BlockID = Stream.ReadSubBlockID();
846 if (ParseBlock(Stream, BlockInfo, BlockID, 0, CurStreamType))
851 if (Dump) outs() << "\n\n";
853 uint64_t BufferSizeBits = Stream.getBitcodeBytes().size() * CHAR_BIT;
854 // Print a summary of the read file.
855 outs() << "Summary of " << InputFilename << ":\n";
856 outs() << " Total size: ";
857 PrintSize(BufferSizeBits);
859 outs() << " Stream type: ";
860 switch (CurStreamType) {
861 case UnknownBitstream: outs() << "unknown\n"; break;
862 case LLVMIRBitstream: outs() << "LLVM IR\n"; break;
864 outs() << " # Toplevel Blocks: " << NumTopBlocks << "\n";
867 // Emit per-block stats.
868 outs() << "Per-block Summary:\n";
869 for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(),
870 E = BlockIDStats.end(); I != E; ++I) {
871 outs() << " Block ID #" << I->first;
872 if (const char *BlockName =
873 GetBlockName(I->first, BlockInfo, CurStreamType))
874 outs() << " (" << BlockName << ")";
877 const PerBlockIDStats &Stats = I->second;
878 outs() << " Num Instances: " << Stats.NumInstances << "\n";
879 outs() << " Total Size: ";
880 PrintSize(Stats.NumBits);
882 double pct = (Stats.NumBits * 100.0) / BufferSizeBits;
883 outs() << " Percent of file: " << format("%2.4f%%", pct) << "\n";
884 if (Stats.NumInstances > 1) {
885 outs() << " Average Size: ";
886 PrintSize(Stats.NumBits/(double)Stats.NumInstances);
888 outs() << " Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
889 << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
890 outs() << " Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
891 << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
892 outs() << " Tot/Avg Records: " << Stats.NumRecords << "/"
893 << Stats.NumRecords/(double)Stats.NumInstances << "\n";
895 outs() << " Num SubBlocks: " << Stats.NumSubBlocks << "\n";
896 outs() << " Num Abbrevs: " << Stats.NumAbbrevs << "\n";
897 outs() << " Num Records: " << Stats.NumRecords << "\n";
899 if (Stats.NumRecords) {
900 double pct = (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumRecords;
901 outs() << " Percent Abbrevs: " << format("%2.4f%%", pct) << "\n";
905 // Print a histogram of the codes we see.
906 if (!NoHistogram && !Stats.CodeFreq.empty()) {
907 std::vector<std::pair<unsigned, unsigned> > FreqPairs; // <freq,code>
908 for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
909 if (unsigned Freq = Stats.CodeFreq[i].NumInstances)
910 FreqPairs.push_back(std::make_pair(Freq, i));
911 std::stable_sort(FreqPairs.begin(), FreqPairs.end());
912 std::reverse(FreqPairs.begin(), FreqPairs.end());
914 outs() << "\tRecord Histogram:\n";
915 outs() << "\t\t Count # Bits b/Rec % Abv Record Kind\n";
916 for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
917 const PerRecordStats &RecStats = Stats.CodeFreq[FreqPairs[i].second];
919 outs() << format("\t\t%7d %9lu",
920 RecStats.NumInstances,
921 (unsigned long)RecStats.TotalBits);
923 if (RecStats.NumInstances > 1)
924 outs() << format(" %9.1f",
925 (double)RecStats.TotalBits/RecStats.NumInstances);
929 if (RecStats.NumAbbrev)
932 (double)RecStats.NumAbbrev/RecStats.NumInstances*100);
937 if (const char *CodeName = GetCodeName(FreqPairs[i].second, I->first,
938 BlockInfo, CurStreamType))
939 outs() << CodeName << "\n";
941 outs() << "UnknownCode" << FreqPairs[i].second << "\n";
951 int main(int argc, char **argv) {
952 // Print a stack trace if we signal out.
953 sys::PrintStackTraceOnErrorSignal(argv[0]);
954 PrettyStackTraceProgram X(argc, argv);
955 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
956 cl::ParseCommandLineOptions(argc, argv, "llvm-bcanalyzer file analyzer\n");
958 return AnalyzeBitcode();