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/Bitcode/BitstreamReader.h"
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/Bitcode/LLVMBitCodes.h"
33 #include "llvm/Bitcode/ReaderWriter.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/Signals.h"
41 #include "llvm/Support/raw_ostream.h"
45 #include <system_error>
48 static cl::opt<std::string>
49 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
51 static cl::opt<bool> Dump("dump", cl::desc("Dump low level bitcode trace"));
53 //===----------------------------------------------------------------------===//
54 // Bitcode specific analysis.
55 //===----------------------------------------------------------------------===//
57 static cl::opt<bool> NoHistogram("disable-histogram",
58 cl::desc("Do not print per-code histogram"));
61 NonSymbolic("non-symbolic",
62 cl::desc("Emit numeric info in dump even if"
63 " symbolic info is available"));
65 static cl::opt<std::string>
66 BlockInfoFilename("block-info",
67 cl::desc("Use the BLOCK_INFO from the given file"));
70 ShowBinaryBlobs("show-binary-blobs",
71 cl::desc("Print binary blobs using hex escapes"));
75 /// CurStreamTypeType - A type for CurStreamType
76 enum CurStreamTypeType {
83 /// GetBlockName - Return a symbolic block name if known, otherwise return
85 static const char *GetBlockName(unsigned BlockID,
86 const BitstreamReader &StreamFile,
87 CurStreamTypeType CurStreamType) {
88 // Standard blocks for all bitcode files.
89 if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
90 if (BlockID == bitc::BLOCKINFO_BLOCK_ID)
91 return "BLOCKINFO_BLOCK";
95 // Check to see if we have a blockinfo record for this block, with a name.
96 if (const BitstreamReader::BlockInfo *Info =
97 StreamFile.getBlockInfo(BlockID)) {
98 if (!Info->Name.empty())
99 return Info->Name.c_str();
103 if (CurStreamType != LLVMIRBitstream) return nullptr;
106 default: return nullptr;
107 case bitc::MODULE_BLOCK_ID: return "MODULE_BLOCK";
108 case bitc::PARAMATTR_BLOCK_ID: return "PARAMATTR_BLOCK";
109 case bitc::PARAMATTR_GROUP_BLOCK_ID: return "PARAMATTR_GROUP_BLOCK_ID";
110 case bitc::TYPE_BLOCK_ID_NEW: return "TYPE_BLOCK_ID";
111 case bitc::CONSTANTS_BLOCK_ID: return "CONSTANTS_BLOCK";
112 case bitc::FUNCTION_BLOCK_ID: return "FUNCTION_BLOCK";
113 case bitc::VALUE_SYMTAB_BLOCK_ID: return "VALUE_SYMTAB";
114 case bitc::METADATA_BLOCK_ID: return "METADATA_BLOCK";
115 case bitc::METADATA_ATTACHMENT_ID: return "METADATA_ATTACHMENT_BLOCK";
116 case bitc::USELIST_BLOCK_ID: return "USELIST_BLOCK_ID";
120 /// GetCodeName - Return a symbolic code name if known, otherwise return
122 static const char *GetCodeName(unsigned CodeID, unsigned BlockID,
123 const BitstreamReader &StreamFile,
124 CurStreamTypeType CurStreamType) {
125 // Standard blocks for all bitcode files.
126 if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
127 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
129 default: return nullptr;
130 case bitc::BLOCKINFO_CODE_SETBID: return "SETBID";
131 case bitc::BLOCKINFO_CODE_BLOCKNAME: return "BLOCKNAME";
132 case bitc::BLOCKINFO_CODE_SETRECORDNAME: return "SETRECORDNAME";
138 // Check to see if we have a blockinfo record for this record, with a name.
139 if (const BitstreamReader::BlockInfo *Info =
140 StreamFile.getBlockInfo(BlockID)) {
141 for (unsigned i = 0, e = Info->RecordNames.size(); i != e; ++i)
142 if (Info->RecordNames[i].first == CodeID)
143 return Info->RecordNames[i].second.c_str();
147 if (CurStreamType != LLVMIRBitstream) return nullptr;
150 default: return nullptr;
151 case bitc::MODULE_BLOCK_ID:
153 default: return nullptr;
154 case bitc::MODULE_CODE_VERSION: return "VERSION";
155 case bitc::MODULE_CODE_TRIPLE: return "TRIPLE";
156 case bitc::MODULE_CODE_DATALAYOUT: return "DATALAYOUT";
157 case bitc::MODULE_CODE_ASM: return "ASM";
158 case bitc::MODULE_CODE_SECTIONNAME: return "SECTIONNAME";
159 case bitc::MODULE_CODE_DEPLIB: return "DEPLIB"; // FIXME: Remove in 4.0
160 case bitc::MODULE_CODE_GLOBALVAR: return "GLOBALVAR";
161 case bitc::MODULE_CODE_FUNCTION: return "FUNCTION";
162 case bitc::MODULE_CODE_ALIAS: return "ALIAS";
163 case bitc::MODULE_CODE_PURGEVALS: return "PURGEVALS";
164 case bitc::MODULE_CODE_GCNAME: return "GCNAME";
166 case bitc::PARAMATTR_BLOCK_ID:
168 default: return nullptr;
169 case bitc::PARAMATTR_CODE_ENTRY_OLD: return "ENTRY";
170 case bitc::PARAMATTR_CODE_ENTRY: return "ENTRY";
171 case bitc::PARAMATTR_GRP_CODE_ENTRY: return "ENTRY";
173 case bitc::TYPE_BLOCK_ID_NEW:
175 default: return nullptr;
176 case bitc::TYPE_CODE_NUMENTRY: return "NUMENTRY";
177 case bitc::TYPE_CODE_VOID: return "VOID";
178 case bitc::TYPE_CODE_FLOAT: return "FLOAT";
179 case bitc::TYPE_CODE_DOUBLE: return "DOUBLE";
180 case bitc::TYPE_CODE_LABEL: return "LABEL";
181 case bitc::TYPE_CODE_OPAQUE: return "OPAQUE";
182 case bitc::TYPE_CODE_INTEGER: return "INTEGER";
183 case bitc::TYPE_CODE_POINTER: return "POINTER";
184 case bitc::TYPE_CODE_ARRAY: return "ARRAY";
185 case bitc::TYPE_CODE_VECTOR: return "VECTOR";
186 case bitc::TYPE_CODE_X86_FP80: return "X86_FP80";
187 case bitc::TYPE_CODE_FP128: return "FP128";
188 case bitc::TYPE_CODE_PPC_FP128: return "PPC_FP128";
189 case bitc::TYPE_CODE_METADATA: return "METADATA";
190 case bitc::TYPE_CODE_STRUCT_ANON: return "STRUCT_ANON";
191 case bitc::TYPE_CODE_STRUCT_NAME: return "STRUCT_NAME";
192 case bitc::TYPE_CODE_STRUCT_NAMED: return "STRUCT_NAMED";
193 case bitc::TYPE_CODE_FUNCTION: return "FUNCTION";
196 case bitc::CONSTANTS_BLOCK_ID:
198 default: return nullptr;
199 case bitc::CST_CODE_SETTYPE: return "SETTYPE";
200 case bitc::CST_CODE_NULL: return "NULL";
201 case bitc::CST_CODE_UNDEF: return "UNDEF";
202 case bitc::CST_CODE_INTEGER: return "INTEGER";
203 case bitc::CST_CODE_WIDE_INTEGER: return "WIDE_INTEGER";
204 case bitc::CST_CODE_FLOAT: return "FLOAT";
205 case bitc::CST_CODE_AGGREGATE: return "AGGREGATE";
206 case bitc::CST_CODE_STRING: return "STRING";
207 case bitc::CST_CODE_CSTRING: return "CSTRING";
208 case bitc::CST_CODE_CE_BINOP: return "CE_BINOP";
209 case bitc::CST_CODE_CE_CAST: return "CE_CAST";
210 case bitc::CST_CODE_CE_GEP: return "CE_GEP";
211 case bitc::CST_CODE_CE_INBOUNDS_GEP: return "CE_INBOUNDS_GEP";
212 case bitc::CST_CODE_CE_SELECT: return "CE_SELECT";
213 case bitc::CST_CODE_CE_EXTRACTELT: return "CE_EXTRACTELT";
214 case bitc::CST_CODE_CE_INSERTELT: return "CE_INSERTELT";
215 case bitc::CST_CODE_CE_SHUFFLEVEC: return "CE_SHUFFLEVEC";
216 case bitc::CST_CODE_CE_CMP: return "CE_CMP";
217 case bitc::CST_CODE_INLINEASM: return "INLINEASM";
218 case bitc::CST_CODE_CE_SHUFVEC_EX: return "CE_SHUFVEC_EX";
219 case bitc::CST_CODE_BLOCKADDRESS: return "CST_CODE_BLOCKADDRESS";
220 case bitc::CST_CODE_DATA: return "DATA";
222 case bitc::FUNCTION_BLOCK_ID:
224 default: return nullptr;
225 case bitc::FUNC_CODE_DECLAREBLOCKS: return "DECLAREBLOCKS";
227 case bitc::FUNC_CODE_INST_BINOP: return "INST_BINOP";
228 case bitc::FUNC_CODE_INST_CAST: return "INST_CAST";
229 case bitc::FUNC_CODE_INST_GEP_OLD:
230 return "INST_GEP_OLD";
231 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
232 return "INST_INBOUNDS_GEP_OLD";
233 case bitc::FUNC_CODE_INST_SELECT: return "INST_SELECT";
234 case bitc::FUNC_CODE_INST_EXTRACTELT: return "INST_EXTRACTELT";
235 case bitc::FUNC_CODE_INST_INSERTELT: return "INST_INSERTELT";
236 case bitc::FUNC_CODE_INST_SHUFFLEVEC: return "INST_SHUFFLEVEC";
237 case bitc::FUNC_CODE_INST_CMP: return "INST_CMP";
239 case bitc::FUNC_CODE_INST_RET: return "INST_RET";
240 case bitc::FUNC_CODE_INST_BR: return "INST_BR";
241 case bitc::FUNC_CODE_INST_SWITCH: return "INST_SWITCH";
242 case bitc::FUNC_CODE_INST_INVOKE: return "INST_INVOKE";
243 case bitc::FUNC_CODE_INST_UNREACHABLE: return "INST_UNREACHABLE";
245 case bitc::FUNC_CODE_INST_PHI: return "INST_PHI";
246 case bitc::FUNC_CODE_INST_ALLOCA: return "INST_ALLOCA";
247 case bitc::FUNC_CODE_INST_LOAD: return "INST_LOAD";
248 case bitc::FUNC_CODE_INST_VAARG: return "INST_VAARG";
249 case bitc::FUNC_CODE_INST_STORE: return "INST_STORE";
250 case bitc::FUNC_CODE_INST_EXTRACTVAL: return "INST_EXTRACTVAL";
251 case bitc::FUNC_CODE_INST_INSERTVAL: return "INST_INSERTVAL";
252 case bitc::FUNC_CODE_INST_CMP2: return "INST_CMP2";
253 case bitc::FUNC_CODE_INST_VSELECT: return "INST_VSELECT";
254 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: return "DEBUG_LOC_AGAIN";
255 case bitc::FUNC_CODE_INST_CALL: return "INST_CALL";
256 case bitc::FUNC_CODE_DEBUG_LOC: return "DEBUG_LOC";
257 case bitc::FUNC_CODE_INST_GEP:
260 case bitc::VALUE_SYMTAB_BLOCK_ID:
262 default: return nullptr;
263 case bitc::VST_CODE_ENTRY: return "ENTRY";
264 case bitc::VST_CODE_BBENTRY: return "BBENTRY";
266 case bitc::METADATA_ATTACHMENT_ID:
268 default:return nullptr;
269 case bitc::METADATA_ATTACHMENT: return "METADATA_ATTACHMENT";
271 case bitc::METADATA_BLOCK_ID:
273 default:return nullptr;
274 case bitc::METADATA_STRING: return "METADATA_STRING";
275 case bitc::METADATA_NAME: return "METADATA_NAME";
276 case bitc::METADATA_KIND: return "METADATA_KIND";
277 case bitc::METADATA_NODE: return "METADATA_NODE";
278 case bitc::METADATA_VALUE: return "METADATA_VALUE";
279 case bitc::METADATA_OLD_NODE: return "METADATA_OLD_NODE";
280 case bitc::METADATA_OLD_FN_NODE: return "METADATA_OLD_FN_NODE";
281 case bitc::METADATA_NAMED_NODE: return "METADATA_NAMED_NODE";
283 case bitc::USELIST_BLOCK_ID:
285 default:return nullptr;
286 case bitc::USELIST_CODE_DEFAULT: return "USELIST_CODE_DEFAULT";
287 case bitc::USELIST_CODE_BB: return "USELIST_CODE_BB";
292 struct PerRecordStats {
293 unsigned NumInstances;
297 PerRecordStats() : NumInstances(0), NumAbbrev(0), TotalBits(0) {}
300 struct PerBlockIDStats {
301 /// NumInstances - This the number of times this block ID has been seen.
302 unsigned NumInstances;
304 /// NumBits - The total size in bits of all of these blocks.
307 /// NumSubBlocks - The total number of blocks these blocks contain.
308 unsigned NumSubBlocks;
310 /// NumAbbrevs - The total number of abbreviations.
313 /// NumRecords - The total number of records these blocks contain, and the
314 /// number that are abbreviated.
315 unsigned NumRecords, NumAbbreviatedRecords;
317 /// CodeFreq - Keep track of the number of times we see each code.
318 std::vector<PerRecordStats> CodeFreq;
321 : NumInstances(0), NumBits(0),
322 NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {}
325 static std::map<unsigned, PerBlockIDStats> BlockIDStats;
329 /// Error - All bitcode analysis errors go through this function, making this a
330 /// good place to breakpoint if debugging.
331 static bool Error(const Twine &Err) {
332 errs() << Err << "\n";
336 /// ParseBlock - Read a block, updating statistics, etc.
337 static bool ParseBlock(BitstreamCursor &Stream, unsigned BlockID,
338 unsigned IndentLevel, CurStreamTypeType CurStreamType) {
339 std::string Indent(IndentLevel*2, ' ');
340 uint64_t BlockBitStart = Stream.GetCurrentBitNo();
342 // Get the statistics for this BlockID.
343 PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
345 BlockStats.NumInstances++;
347 // BLOCKINFO is a special part of the stream.
348 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
349 if (Dump) outs() << Indent << "<BLOCKINFO_BLOCK/>\n";
350 if (Stream.ReadBlockInfoBlock())
351 return Error("Malformed BlockInfoBlock");
352 uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
353 BlockStats.NumBits += BlockBitEnd-BlockBitStart;
357 unsigned NumWords = 0;
358 if (Stream.EnterSubBlock(BlockID, &NumWords))
359 return Error("Malformed block record");
361 const char *BlockName = nullptr;
363 outs() << Indent << "<";
364 if ((BlockName = GetBlockName(BlockID, *Stream.getBitStreamReader(),
368 outs() << "UnknownBlock" << BlockID;
370 if (NonSymbolic && BlockName)
371 outs() << " BlockID=" << BlockID;
373 outs() << " NumWords=" << NumWords
374 << " BlockCodeSize=" << Stream.getAbbrevIDWidth() << ">\n";
377 SmallVector<uint64_t, 64> Record;
379 // Read all the records for this block.
381 if (Stream.AtEndOfStream())
382 return Error("Premature end of bitstream");
384 uint64_t RecordStartBit = Stream.GetCurrentBitNo();
386 BitstreamEntry Entry =
387 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
389 switch (Entry.Kind) {
390 case BitstreamEntry::Error:
391 return Error("malformed bitcode file");
392 case BitstreamEntry::EndBlock: {
393 uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
394 BlockStats.NumBits += BlockBitEnd-BlockBitStart;
396 outs() << Indent << "</";
398 outs() << BlockName << ">\n";
400 outs() << "UnknownBlock" << BlockID << ">\n";
405 case BitstreamEntry::SubBlock: {
406 uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
407 if (ParseBlock(Stream, Entry.ID, IndentLevel+1, CurStreamType))
409 ++BlockStats.NumSubBlocks;
410 uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
412 // Don't include subblock sizes in the size of this block.
413 BlockBitStart += SubBlockBitEnd-SubBlockBitStart;
416 case BitstreamEntry::Record:
417 // The interesting case.
421 if (Entry.ID == bitc::DEFINE_ABBREV) {
422 Stream.ReadAbbrevRecord();
423 ++BlockStats.NumAbbrevs;
429 ++BlockStats.NumRecords;
432 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
434 // Increment the # occurrences of this code.
435 if (BlockStats.CodeFreq.size() <= Code)
436 BlockStats.CodeFreq.resize(Code+1);
437 BlockStats.CodeFreq[Code].NumInstances++;
438 BlockStats.CodeFreq[Code].TotalBits +=
439 Stream.GetCurrentBitNo()-RecordStartBit;
440 if (Entry.ID != bitc::UNABBREV_RECORD) {
441 BlockStats.CodeFreq[Code].NumAbbrev++;
442 ++BlockStats.NumAbbreviatedRecords;
446 outs() << Indent << " <";
447 if (const char *CodeName =
448 GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
452 outs() << "UnknownCode" << Code;
454 GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
456 outs() << " codeid=" << Code;
457 if (Entry.ID != bitc::UNABBREV_RECORD)
458 outs() << " abbrevid=" << Entry.ID;
460 for (unsigned i = 0, e = Record.size(); i != e; ++i)
461 outs() << " op" << i << "=" << (int64_t)Record[i];
466 outs() << " blob data = ";
467 if (ShowBinaryBlobs) {
469 outs().write_escaped(Blob, /*hex=*/true) << "'";
471 bool BlobIsPrintable = true;
472 for (unsigned i = 0, e = Blob.size(); i != e; ++i)
473 if (!isprint(static_cast<unsigned char>(Blob[i]))) {
474 BlobIsPrintable = false;
479 outs() << "'" << Blob << "'";
481 outs() << "unprintable, " << Blob.size() << " bytes.";
490 static void PrintSize(double Bits) {
491 outs() << format("%.2f/%.2fB/%luW", Bits, Bits/8,(unsigned long)(Bits/32));
493 static void PrintSize(uint64_t Bits) {
494 outs() << format("%lub/%.2fB/%luW", (unsigned long)Bits,
495 (double)Bits/8, (unsigned long)(Bits/32));
498 static bool openBitcodeFile(StringRef Path,
499 std::unique_ptr<MemoryBuffer> &MemBuf,
500 BitstreamReader &StreamFile,
501 BitstreamCursor &Stream,
502 CurStreamTypeType &CurStreamType) {
503 // Read the input file.
504 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
505 MemoryBuffer::getFileOrSTDIN(Path);
506 if (std::error_code EC = MemBufOrErr.getError())
507 return Error(Twine("Error reading '") + Path + "': " + EC.message());
508 MemBuf = std::move(MemBufOrErr.get());
510 if (MemBuf->getBufferSize() & 3)
511 return Error("Bitcode stream should be a multiple of 4 bytes in length");
513 const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
514 const unsigned char *EndBufPtr = BufPtr + MemBuf->getBufferSize();
516 // If we have a wrapper header, parse it and ignore the non-bc file contents.
517 // The magic number is 0x0B17C0DE stored in little endian.
518 if (isBitcodeWrapper(BufPtr, EndBufPtr))
519 if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr, true))
520 return Error("Invalid bitcode wrapper header");
522 StreamFile = BitstreamReader(BufPtr, EndBufPtr);
523 Stream = BitstreamCursor(StreamFile);
524 StreamFile.CollectBlockInfoNames();
526 // Read the stream signature.
528 Signature[0] = Stream.Read(8);
529 Signature[1] = Stream.Read(8);
530 Signature[2] = Stream.Read(4);
531 Signature[3] = Stream.Read(4);
532 Signature[4] = Stream.Read(4);
533 Signature[5] = Stream.Read(4);
535 // Autodetect the file contents, if it is one we know.
536 CurStreamType = UnknownBitstream;
537 if (Signature[0] == 'B' && Signature[1] == 'C' &&
538 Signature[2] == 0x0 && Signature[3] == 0xC &&
539 Signature[4] == 0xE && Signature[5] == 0xD)
540 CurStreamType = LLVMIRBitstream;
545 /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
546 static int AnalyzeBitcode() {
547 std::unique_ptr<MemoryBuffer> StreamBuffer;
548 BitstreamReader StreamFile;
549 BitstreamCursor Stream;
550 CurStreamTypeType CurStreamType;
551 if (openBitcodeFile(InputFilename, StreamBuffer, StreamFile, Stream,
555 // Read block info from BlockInfoFilename, if specified.
556 // The block info must be a top-level block.
557 if (!BlockInfoFilename.empty()) {
558 std::unique_ptr<MemoryBuffer> BlockInfoBuffer;
559 BitstreamReader BlockInfoFile;
560 BitstreamCursor BlockInfoCursor;
561 CurStreamTypeType BlockInfoStreamType;
562 if (openBitcodeFile(BlockInfoFilename, BlockInfoBuffer, BlockInfoFile,
563 BlockInfoCursor, BlockInfoStreamType))
566 while (!BlockInfoCursor.AtEndOfStream()) {
567 unsigned Code = BlockInfoCursor.ReadCode();
568 if (Code != bitc::ENTER_SUBBLOCK)
569 return Error("Invalid record at top-level in block info file");
571 unsigned BlockID = BlockInfoCursor.ReadSubBlockID();
572 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
573 if (BlockInfoCursor.ReadBlockInfoBlock())
574 return Error("Malformed BlockInfoBlock in block info file");
578 BlockInfoCursor.SkipBlock();
581 StreamFile.takeBlockInfo(std::move(BlockInfoFile));
584 unsigned NumTopBlocks = 0;
586 // Parse the top-level structure. We only allow blocks at the top-level.
587 while (!Stream.AtEndOfStream()) {
588 unsigned Code = Stream.ReadCode();
589 if (Code != bitc::ENTER_SUBBLOCK)
590 return Error("Invalid record at top-level");
592 unsigned BlockID = Stream.ReadSubBlockID();
594 if (ParseBlock(Stream, BlockID, 0, CurStreamType))
599 if (Dump) outs() << "\n\n";
601 uint64_t BufferSizeBits = StreamFile.getBitcodeBytes().getExtent() * CHAR_BIT;
602 // Print a summary of the read file.
603 outs() << "Summary of " << InputFilename << ":\n";
604 outs() << " Total size: ";
605 PrintSize(BufferSizeBits);
607 outs() << " Stream type: ";
608 switch (CurStreamType) {
609 case UnknownBitstream: outs() << "unknown\n"; break;
610 case LLVMIRBitstream: outs() << "LLVM IR\n"; break;
612 outs() << " # Toplevel Blocks: " << NumTopBlocks << "\n";
615 // Emit per-block stats.
616 outs() << "Per-block Summary:\n";
617 for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(),
618 E = BlockIDStats.end(); I != E; ++I) {
619 outs() << " Block ID #" << I->first;
620 if (const char *BlockName = GetBlockName(I->first, StreamFile,
622 outs() << " (" << BlockName << ")";
625 const PerBlockIDStats &Stats = I->second;
626 outs() << " Num Instances: " << Stats.NumInstances << "\n";
627 outs() << " Total Size: ";
628 PrintSize(Stats.NumBits);
630 double pct = (Stats.NumBits * 100.0) / BufferSizeBits;
631 outs() << " Percent of file: " << format("%2.4f%%", pct) << "\n";
632 if (Stats.NumInstances > 1) {
633 outs() << " Average Size: ";
634 PrintSize(Stats.NumBits/(double)Stats.NumInstances);
636 outs() << " Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
637 << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
638 outs() << " Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
639 << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
640 outs() << " Tot/Avg Records: " << Stats.NumRecords << "/"
641 << Stats.NumRecords/(double)Stats.NumInstances << "\n";
643 outs() << " Num SubBlocks: " << Stats.NumSubBlocks << "\n";
644 outs() << " Num Abbrevs: " << Stats.NumAbbrevs << "\n";
645 outs() << " Num Records: " << Stats.NumRecords << "\n";
647 if (Stats.NumRecords) {
648 double pct = (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumRecords;
649 outs() << " Percent Abbrevs: " << format("%2.4f%%", pct) << "\n";
653 // Print a histogram of the codes we see.
654 if (!NoHistogram && !Stats.CodeFreq.empty()) {
655 std::vector<std::pair<unsigned, unsigned> > FreqPairs; // <freq,code>
656 for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
657 if (unsigned Freq = Stats.CodeFreq[i].NumInstances)
658 FreqPairs.push_back(std::make_pair(Freq, i));
659 std::stable_sort(FreqPairs.begin(), FreqPairs.end());
660 std::reverse(FreqPairs.begin(), FreqPairs.end());
662 outs() << "\tRecord Histogram:\n";
663 outs() << "\t\t Count # Bits %% Abv Record Kind\n";
664 for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
665 const PerRecordStats &RecStats = Stats.CodeFreq[FreqPairs[i].second];
667 outs() << format("\t\t%7d %9lu",
668 RecStats.NumInstances,
669 (unsigned long)RecStats.TotalBits);
671 if (RecStats.NumAbbrev)
674 (double)RecStats.NumAbbrev/RecStats.NumInstances*100);
678 if (const char *CodeName =
679 GetCodeName(FreqPairs[i].second, I->first, StreamFile,
681 outs() << CodeName << "\n";
683 outs() << "UnknownCode" << FreqPairs[i].second << "\n";
693 int main(int argc, char **argv) {
694 // Print a stack trace if we signal out.
695 sys::PrintStackTraceOnErrorSignal();
696 PrettyStackTraceProgram X(argc, argv);
697 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
698 cl::ParseCommandLineOptions(argc, argv, "llvm-bcanalyzer file analyzer\n");
700 return AnalyzeBitcode();