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/Bitcode/LLVMBitCodes.h"
32 #include "llvm/Bitcode/ReaderWriter.h"
33 #include "llvm/IR/Verifier.h"
34 #include "llvm/ADT/Optional.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"));
71 /// CurStreamTypeType - A type for CurStreamType
72 enum CurStreamTypeType {
79 /// GetBlockName - Return a symbolic block name if known, otherwise return
81 static const char *GetBlockName(unsigned BlockID,
82 const BitstreamReader &StreamFile,
83 CurStreamTypeType CurStreamType) {
84 // Standard blocks for all bitcode files.
85 if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
86 if (BlockID == bitc::BLOCKINFO_BLOCK_ID)
87 return "BLOCKINFO_BLOCK";
91 // Check to see if we have a blockinfo record for this block, with a name.
92 if (const BitstreamReader::BlockInfo *Info =
93 StreamFile.getBlockInfo(BlockID)) {
94 if (!Info->Name.empty())
95 return Info->Name.c_str();
99 if (CurStreamType != LLVMIRBitstream) return nullptr;
102 default: return nullptr;
103 case bitc::MODULE_BLOCK_ID: return "MODULE_BLOCK";
104 case bitc::PARAMATTR_BLOCK_ID: return "PARAMATTR_BLOCK";
105 case bitc::PARAMATTR_GROUP_BLOCK_ID: return "PARAMATTR_GROUP_BLOCK_ID";
106 case bitc::TYPE_BLOCK_ID_NEW: return "TYPE_BLOCK_ID";
107 case bitc::CONSTANTS_BLOCK_ID: return "CONSTANTS_BLOCK";
108 case bitc::FUNCTION_BLOCK_ID: return "FUNCTION_BLOCK";
109 case bitc::VALUE_SYMTAB_BLOCK_ID: return "VALUE_SYMTAB";
110 case bitc::METADATA_BLOCK_ID: return "METADATA_BLOCK";
111 case bitc::METADATA_ATTACHMENT_ID: return "METADATA_ATTACHMENT_BLOCK";
112 case bitc::USELIST_BLOCK_ID: return "USELIST_BLOCK_ID";
116 /// GetCodeName - Return a symbolic code name if known, otherwise return
118 static const char *GetCodeName(unsigned CodeID, unsigned BlockID,
119 const BitstreamReader &StreamFile,
120 CurStreamTypeType CurStreamType) {
121 // Standard blocks for all bitcode files.
122 if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
123 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
125 default: return nullptr;
126 case bitc::BLOCKINFO_CODE_SETBID: return "SETBID";
127 case bitc::BLOCKINFO_CODE_BLOCKNAME: return "BLOCKNAME";
128 case bitc::BLOCKINFO_CODE_SETRECORDNAME: return "SETRECORDNAME";
134 // Check to see if we have a blockinfo record for this record, with a name.
135 if (const BitstreamReader::BlockInfo *Info =
136 StreamFile.getBlockInfo(BlockID)) {
137 for (unsigned i = 0, e = Info->RecordNames.size(); i != e; ++i)
138 if (Info->RecordNames[i].first == CodeID)
139 return Info->RecordNames[i].second.c_str();
143 if (CurStreamType != LLVMIRBitstream) return nullptr;
146 default: return nullptr;
147 case bitc::MODULE_BLOCK_ID:
149 default: return nullptr;
150 case bitc::MODULE_CODE_VERSION: return "VERSION";
151 case bitc::MODULE_CODE_TRIPLE: return "TRIPLE";
152 case bitc::MODULE_CODE_DATALAYOUT: return "DATALAYOUT";
153 case bitc::MODULE_CODE_ASM: return "ASM";
154 case bitc::MODULE_CODE_SECTIONNAME: return "SECTIONNAME";
155 case bitc::MODULE_CODE_DEPLIB: return "DEPLIB"; // FIXME: Remove in 4.0
156 case bitc::MODULE_CODE_GLOBALVAR: return "GLOBALVAR";
157 case bitc::MODULE_CODE_FUNCTION: return "FUNCTION";
158 case bitc::MODULE_CODE_ALIAS: return "ALIAS";
159 case bitc::MODULE_CODE_PURGEVALS: return "PURGEVALS";
160 case bitc::MODULE_CODE_GCNAME: return "GCNAME";
162 case bitc::PARAMATTR_BLOCK_ID:
164 default: return nullptr;
165 case bitc::PARAMATTR_CODE_ENTRY_OLD: return "ENTRY";
166 case bitc::PARAMATTR_CODE_ENTRY: return "ENTRY";
167 case bitc::PARAMATTR_GRP_CODE_ENTRY: return "ENTRY";
169 case bitc::TYPE_BLOCK_ID_NEW:
171 default: return nullptr;
172 case bitc::TYPE_CODE_NUMENTRY: return "NUMENTRY";
173 case bitc::TYPE_CODE_VOID: return "VOID";
174 case bitc::TYPE_CODE_FLOAT: return "FLOAT";
175 case bitc::TYPE_CODE_DOUBLE: return "DOUBLE";
176 case bitc::TYPE_CODE_LABEL: return "LABEL";
177 case bitc::TYPE_CODE_OPAQUE: return "OPAQUE";
178 case bitc::TYPE_CODE_INTEGER: return "INTEGER";
179 case bitc::TYPE_CODE_POINTER: return "POINTER";
180 case bitc::TYPE_CODE_ARRAY: return "ARRAY";
181 case bitc::TYPE_CODE_VECTOR: return "VECTOR";
182 case bitc::TYPE_CODE_X86_FP80: return "X86_FP80";
183 case bitc::TYPE_CODE_FP128: return "FP128";
184 case bitc::TYPE_CODE_PPC_FP128: return "PPC_FP128";
185 case bitc::TYPE_CODE_METADATA: return "METADATA";
186 case bitc::TYPE_CODE_STRUCT_ANON: return "STRUCT_ANON";
187 case bitc::TYPE_CODE_STRUCT_NAME: return "STRUCT_NAME";
188 case bitc::TYPE_CODE_STRUCT_NAMED: return "STRUCT_NAMED";
189 case bitc::TYPE_CODE_FUNCTION: return "FUNCTION";
192 case bitc::CONSTANTS_BLOCK_ID:
194 default: return nullptr;
195 case bitc::CST_CODE_SETTYPE: return "SETTYPE";
196 case bitc::CST_CODE_NULL: return "NULL";
197 case bitc::CST_CODE_UNDEF: return "UNDEF";
198 case bitc::CST_CODE_INTEGER: return "INTEGER";
199 case bitc::CST_CODE_WIDE_INTEGER: return "WIDE_INTEGER";
200 case bitc::CST_CODE_FLOAT: return "FLOAT";
201 case bitc::CST_CODE_AGGREGATE: return "AGGREGATE";
202 case bitc::CST_CODE_STRING: return "STRING";
203 case bitc::CST_CODE_CSTRING: return "CSTRING";
204 case bitc::CST_CODE_CE_BINOP: return "CE_BINOP";
205 case bitc::CST_CODE_CE_CAST: return "CE_CAST";
206 case bitc::CST_CODE_CE_GEP: return "CE_GEP";
207 case bitc::CST_CODE_CE_INBOUNDS_GEP: return "CE_INBOUNDS_GEP";
208 case bitc::CST_CODE_CE_SELECT: return "CE_SELECT";
209 case bitc::CST_CODE_CE_EXTRACTELT: return "CE_EXTRACTELT";
210 case bitc::CST_CODE_CE_INSERTELT: return "CE_INSERTELT";
211 case bitc::CST_CODE_CE_SHUFFLEVEC: return "CE_SHUFFLEVEC";
212 case bitc::CST_CODE_CE_CMP: return "CE_CMP";
213 case bitc::CST_CODE_INLINEASM: return "INLINEASM";
214 case bitc::CST_CODE_CE_SHUFVEC_EX: return "CE_SHUFVEC_EX";
215 case bitc::CST_CODE_BLOCKADDRESS: return "CST_CODE_BLOCKADDRESS";
216 case bitc::CST_CODE_DATA: return "DATA";
218 case bitc::FUNCTION_BLOCK_ID:
220 default: return nullptr;
221 case bitc::FUNC_CODE_DECLAREBLOCKS: return "DECLAREBLOCKS";
223 case bitc::FUNC_CODE_INST_BINOP: return "INST_BINOP";
224 case bitc::FUNC_CODE_INST_CAST: return "INST_CAST";
225 case bitc::FUNC_CODE_INST_GEP: return "INST_GEP";
226 case bitc::FUNC_CODE_INST_INBOUNDS_GEP: return "INST_INBOUNDS_GEP";
227 case bitc::FUNC_CODE_INST_SELECT: return "INST_SELECT";
228 case bitc::FUNC_CODE_INST_EXTRACTELT: return "INST_EXTRACTELT";
229 case bitc::FUNC_CODE_INST_INSERTELT: return "INST_INSERTELT";
230 case bitc::FUNC_CODE_INST_SHUFFLEVEC: return "INST_SHUFFLEVEC";
231 case bitc::FUNC_CODE_INST_CMP: return "INST_CMP";
233 case bitc::FUNC_CODE_INST_RET: return "INST_RET";
234 case bitc::FUNC_CODE_INST_BR: return "INST_BR";
235 case bitc::FUNC_CODE_INST_SWITCH: return "INST_SWITCH";
236 case bitc::FUNC_CODE_INST_INVOKE: return "INST_INVOKE";
237 case bitc::FUNC_CODE_INST_UNREACHABLE: return "INST_UNREACHABLE";
239 case bitc::FUNC_CODE_INST_PHI: return "INST_PHI";
240 case bitc::FUNC_CODE_INST_ALLOCA: return "INST_ALLOCA";
241 case bitc::FUNC_CODE_INST_LOAD: return "INST_LOAD";
242 case bitc::FUNC_CODE_INST_VAARG: return "INST_VAARG";
243 case bitc::FUNC_CODE_INST_STORE: return "INST_STORE";
244 case bitc::FUNC_CODE_INST_EXTRACTVAL: return "INST_EXTRACTVAL";
245 case bitc::FUNC_CODE_INST_INSERTVAL: return "INST_INSERTVAL";
246 case bitc::FUNC_CODE_INST_CMP2: return "INST_CMP2";
247 case bitc::FUNC_CODE_INST_VSELECT: return "INST_VSELECT";
248 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: return "DEBUG_LOC_AGAIN";
249 case bitc::FUNC_CODE_INST_CALL: return "INST_CALL";
250 case bitc::FUNC_CODE_DEBUG_LOC: return "DEBUG_LOC";
252 case bitc::VALUE_SYMTAB_BLOCK_ID:
254 default: return nullptr;
255 case bitc::VST_CODE_ENTRY: return "ENTRY";
256 case bitc::VST_CODE_BBENTRY: return "BBENTRY";
258 case bitc::METADATA_ATTACHMENT_ID:
260 default:return nullptr;
261 case bitc::METADATA_ATTACHMENT: return "METADATA_ATTACHMENT";
263 case bitc::METADATA_BLOCK_ID:
265 default:return nullptr;
266 case bitc::METADATA_STRING: return "METADATA_STRING";
267 case bitc::METADATA_NAME: return "METADATA_NAME";
268 case bitc::METADATA_KIND: return "METADATA_KIND";
269 case bitc::METADATA_NODE: return "METADATA_NODE";
270 case bitc::METADATA_FN_NODE: return "METADATA_FN_NODE";
271 case bitc::METADATA_NAMED_NODE: return "METADATA_NAMED_NODE";
273 case bitc::USELIST_BLOCK_ID:
275 default:return nullptr;
276 case bitc::USELIST_CODE_DEFAULT: return "USELIST_CODE_DEFAULT";
277 case bitc::USELIST_CODE_BB: return "USELIST_CODE_BB";
282 struct PerRecordStats {
283 unsigned NumInstances;
287 PerRecordStats() : NumInstances(0), NumAbbrev(0), TotalBits(0) {}
290 struct PerBlockIDStats {
291 /// NumInstances - This the number of times this block ID has been seen.
292 unsigned NumInstances;
294 /// NumBits - The total size in bits of all of these blocks.
297 /// NumSubBlocks - The total number of blocks these blocks contain.
298 unsigned NumSubBlocks;
300 /// NumAbbrevs - The total number of abbreviations.
303 /// NumRecords - The total number of records these blocks contain, and the
304 /// number that are abbreviated.
305 unsigned NumRecords, NumAbbreviatedRecords;
307 /// CodeFreq - Keep track of the number of times we see each code.
308 std::vector<PerRecordStats> CodeFreq;
311 : NumInstances(0), NumBits(0),
312 NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {}
315 static std::map<unsigned, PerBlockIDStats> BlockIDStats;
319 /// Error - All bitcode analysis errors go through this function, making this a
320 /// good place to breakpoint if debugging.
321 static bool Error(const Twine &Err) {
322 errs() << Err << "\n";
326 /// ParseBlock - Read a block, updating statistics, etc.
327 static bool ParseBlock(BitstreamCursor &Stream, unsigned BlockID,
328 unsigned IndentLevel, CurStreamTypeType CurStreamType) {
329 std::string Indent(IndentLevel*2, ' ');
330 uint64_t BlockBitStart = Stream.GetCurrentBitNo();
332 // Get the statistics for this BlockID.
333 PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
335 BlockStats.NumInstances++;
337 // BLOCKINFO is a special part of the stream.
338 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
339 if (Dump) outs() << Indent << "<BLOCKINFO_BLOCK/>\n";
340 if (Stream.ReadBlockInfoBlock())
341 return Error("Malformed BlockInfoBlock");
342 uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
343 BlockStats.NumBits += BlockBitEnd-BlockBitStart;
347 unsigned NumWords = 0;
348 if (Stream.EnterSubBlock(BlockID, &NumWords))
349 return Error("Malformed block record");
351 const char *BlockName = nullptr;
353 outs() << Indent << "<";
354 if ((BlockName = GetBlockName(BlockID, *Stream.getBitStreamReader(),
358 outs() << "UnknownBlock" << BlockID;
360 if (NonSymbolic && BlockName)
361 outs() << " BlockID=" << BlockID;
363 outs() << " NumWords=" << NumWords
364 << " BlockCodeSize=" << Stream.getAbbrevIDWidth() << ">\n";
367 SmallVector<uint64_t, 64> Record;
369 // Read all the records for this block.
371 if (Stream.AtEndOfStream())
372 return Error("Premature end of bitstream");
374 uint64_t RecordStartBit = Stream.GetCurrentBitNo();
376 BitstreamEntry Entry =
377 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
379 switch (Entry.Kind) {
380 case BitstreamEntry::Error:
381 return Error("malformed bitcode file");
382 case BitstreamEntry::EndBlock: {
383 uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
384 BlockStats.NumBits += BlockBitEnd-BlockBitStart;
386 outs() << Indent << "</";
388 outs() << BlockName << ">\n";
390 outs() << "UnknownBlock" << BlockID << ">\n";
395 case BitstreamEntry::SubBlock: {
396 uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
397 if (ParseBlock(Stream, Entry.ID, IndentLevel+1, CurStreamType))
399 ++BlockStats.NumSubBlocks;
400 uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
402 // Don't include subblock sizes in the size of this block.
403 BlockBitStart += SubBlockBitEnd-SubBlockBitStart;
406 case BitstreamEntry::Record:
407 // The interesting case.
411 if (Entry.ID == bitc::DEFINE_ABBREV) {
412 Stream.ReadAbbrevRecord();
413 ++BlockStats.NumAbbrevs;
419 ++BlockStats.NumRecords;
422 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
424 // Increment the # occurrences of this code.
425 if (BlockStats.CodeFreq.size() <= Code)
426 BlockStats.CodeFreq.resize(Code+1);
427 BlockStats.CodeFreq[Code].NumInstances++;
428 BlockStats.CodeFreq[Code].TotalBits +=
429 Stream.GetCurrentBitNo()-RecordStartBit;
430 if (Entry.ID != bitc::UNABBREV_RECORD) {
431 BlockStats.CodeFreq[Code].NumAbbrev++;
432 ++BlockStats.NumAbbreviatedRecords;
436 outs() << Indent << " <";
437 if (const char *CodeName =
438 GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
442 outs() << "UnknownCode" << Code;
444 GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
446 outs() << " codeid=" << Code;
447 if (Entry.ID != bitc::UNABBREV_RECORD)
448 outs() << " abbrevid=" << Entry.ID;
450 for (unsigned i = 0, e = Record.size(); i != e; ++i)
451 outs() << " op" << i << "=" << (int64_t)Record[i];
456 outs() << " blob data = ";
457 bool BlobIsPrintable = true;
458 for (unsigned i = 0, e = Blob.size(); i != e; ++i)
459 if (!isprint(static_cast<unsigned char>(Blob[i]))) {
460 BlobIsPrintable = false;
465 outs() << "'" << Blob << "'";
467 outs() << "unprintable, " << Blob.size() << " bytes.";
475 static void PrintSize(double Bits) {
476 outs() << format("%.2f/%.2fB/%luW", Bits, Bits/8,(unsigned long)(Bits/32));
478 static void PrintSize(uint64_t Bits) {
479 outs() << format("%lub/%.2fB/%luW", (unsigned long)Bits,
480 (double)Bits/8, (unsigned long)(Bits/32));
483 static bool openBitcodeFile(StringRef Path,
484 std::unique_ptr<MemoryBuffer> &MemBuf,
485 BitstreamReader &StreamFile,
486 BitstreamCursor &Stream,
487 CurStreamTypeType &CurStreamType) {
488 // Read the input file.
489 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
490 MemoryBuffer::getFileOrSTDIN(Path);
491 if (std::error_code EC = MemBufOrErr.getError())
492 return Error(Twine("Error reading '") + Path + "': " + EC.message());
493 MemBuf = std::move(MemBufOrErr.get());
495 if (MemBuf->getBufferSize() & 3)
496 return Error("Bitcode stream should be a multiple of 4 bytes in length");
498 const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
499 const unsigned char *EndBufPtr = BufPtr + MemBuf->getBufferSize();
501 // If we have a wrapper header, parse it and ignore the non-bc file contents.
502 // The magic number is 0x0B17C0DE stored in little endian.
503 if (isBitcodeWrapper(BufPtr, EndBufPtr))
504 if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr, true))
505 return Error("Invalid bitcode wrapper header");
507 StreamFile = BitstreamReader(BufPtr, EndBufPtr);
508 Stream = BitstreamCursor(StreamFile);
509 StreamFile.CollectBlockInfoNames();
511 // Read the stream signature.
513 Signature[0] = Stream.Read(8);
514 Signature[1] = Stream.Read(8);
515 Signature[2] = Stream.Read(4);
516 Signature[3] = Stream.Read(4);
517 Signature[4] = Stream.Read(4);
518 Signature[5] = Stream.Read(4);
520 // Autodetect the file contents, if it is one we know.
521 CurStreamType = UnknownBitstream;
522 if (Signature[0] == 'B' && Signature[1] == 'C' &&
523 Signature[2] == 0x0 && Signature[3] == 0xC &&
524 Signature[4] == 0xE && Signature[5] == 0xD)
525 CurStreamType = LLVMIRBitstream;
530 /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
531 static int AnalyzeBitcode() {
532 std::unique_ptr<MemoryBuffer> StreamBuffer;
533 BitstreamReader StreamFile;
534 BitstreamCursor Stream;
535 CurStreamTypeType CurStreamType;
536 if (openBitcodeFile(InputFilename, StreamBuffer, StreamFile, Stream,
540 // Read block info from BlockInfoFilename, if specified.
541 // The block info must be a top-level block.
542 if (!BlockInfoFilename.empty()) {
543 std::unique_ptr<MemoryBuffer> BlockInfoBuffer;
544 BitstreamReader BlockInfoFile;
545 BitstreamCursor BlockInfoCursor;
546 CurStreamTypeType BlockInfoStreamType;
547 if (openBitcodeFile(BlockInfoFilename, BlockInfoBuffer, BlockInfoFile,
548 BlockInfoCursor, BlockInfoStreamType))
551 while (!BlockInfoCursor.AtEndOfStream()) {
552 unsigned Code = BlockInfoCursor.ReadCode();
553 if (Code != bitc::ENTER_SUBBLOCK)
554 return Error("Invalid record at top-level in block info file");
556 unsigned BlockID = BlockInfoCursor.ReadSubBlockID();
557 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
558 if (BlockInfoCursor.ReadBlockInfoBlock())
559 return Error("Malformed BlockInfoBlock in block info file");
563 BlockInfoCursor.SkipBlock();
566 StreamFile.takeBlockInfo(std::move(BlockInfoFile));
569 unsigned NumTopBlocks = 0;
571 // Parse the top-level structure. We only allow blocks at the top-level.
572 while (!Stream.AtEndOfStream()) {
573 unsigned Code = Stream.ReadCode();
574 if (Code != bitc::ENTER_SUBBLOCK)
575 return Error("Invalid record at top-level");
577 unsigned BlockID = Stream.ReadSubBlockID();
579 if (ParseBlock(Stream, BlockID, 0, CurStreamType))
584 if (Dump) outs() << "\n\n";
586 uint64_t BufferSizeBits = StreamFile.getBitcodeBytes().getExtent() * CHAR_BIT;
587 // Print a summary of the read file.
588 outs() << "Summary of " << InputFilename << ":\n";
589 outs() << " Total size: ";
590 PrintSize(BufferSizeBits);
592 outs() << " Stream type: ";
593 switch (CurStreamType) {
594 case UnknownBitstream: outs() << "unknown\n"; break;
595 case LLVMIRBitstream: outs() << "LLVM IR\n"; break;
597 outs() << " # Toplevel Blocks: " << NumTopBlocks << "\n";
600 // Emit per-block stats.
601 outs() << "Per-block Summary:\n";
602 for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(),
603 E = BlockIDStats.end(); I != E; ++I) {
604 outs() << " Block ID #" << I->first;
605 if (const char *BlockName = GetBlockName(I->first, StreamFile,
607 outs() << " (" << BlockName << ")";
610 const PerBlockIDStats &Stats = I->second;
611 outs() << " Num Instances: " << Stats.NumInstances << "\n";
612 outs() << " Total Size: ";
613 PrintSize(Stats.NumBits);
615 double pct = (Stats.NumBits * 100.0) / BufferSizeBits;
616 outs() << " Percent of file: " << format("%2.4f%%", pct) << "\n";
617 if (Stats.NumInstances > 1) {
618 outs() << " Average Size: ";
619 PrintSize(Stats.NumBits/(double)Stats.NumInstances);
621 outs() << " Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
622 << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
623 outs() << " Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
624 << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
625 outs() << " Tot/Avg Records: " << Stats.NumRecords << "/"
626 << Stats.NumRecords/(double)Stats.NumInstances << "\n";
628 outs() << " Num SubBlocks: " << Stats.NumSubBlocks << "\n";
629 outs() << " Num Abbrevs: " << Stats.NumAbbrevs << "\n";
630 outs() << " Num Records: " << Stats.NumRecords << "\n";
632 if (Stats.NumRecords) {
633 double pct = (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumRecords;
634 outs() << " Percent Abbrevs: " << format("%2.4f%%", pct) << "\n";
638 // Print a histogram of the codes we see.
639 if (!NoHistogram && !Stats.CodeFreq.empty()) {
640 std::vector<std::pair<unsigned, unsigned> > FreqPairs; // <freq,code>
641 for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
642 if (unsigned Freq = Stats.CodeFreq[i].NumInstances)
643 FreqPairs.push_back(std::make_pair(Freq, i));
644 std::stable_sort(FreqPairs.begin(), FreqPairs.end());
645 std::reverse(FreqPairs.begin(), FreqPairs.end());
647 outs() << "\tRecord Histogram:\n";
648 outs() << "\t\t Count # Bits %% Abv Record Kind\n";
649 for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
650 const PerRecordStats &RecStats = Stats.CodeFreq[FreqPairs[i].second];
652 outs() << format("\t\t%7d %9lu",
653 RecStats.NumInstances,
654 (unsigned long)RecStats.TotalBits);
656 if (RecStats.NumAbbrev)
659 (double)RecStats.NumAbbrev/RecStats.NumInstances*100);
663 if (const char *CodeName =
664 GetCodeName(FreqPairs[i].second, I->first, StreamFile,
666 outs() << CodeName << "\n";
668 outs() << "UnknownCode" << FreqPairs[i].second << "\n";
678 int main(int argc, char **argv) {
679 // Print a stack trace if we signal out.
680 sys::PrintStackTraceOnErrorSignal();
681 PrettyStackTraceProgram X(argc, argv);
682 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
683 cl::ParseCommandLineOptions(argc, argv, "llvm-bcanalyzer file analyzer\n");
685 return AnalyzeBitcode();