9a92671b137ceb8297ee07f2525f9c55a22b5966
[oota-llvm.git] / tools / llvm-bcanalyzer / llvm-bcanalyzer.cpp
1 //===-- llvm-bcanalyzer.cpp - Bitcode Analyzer --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
13 //
14 //  Options:
15 //      --help      - Output information about command line switches
16 //      --dump      - Dump low-level bitcode structure in readable format
17 //
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).
27 //
28 //===----------------------------------------------------------------------===//
29
30 #include "llvm/ADT/OwningPtr.h"
31 #include "llvm/Analysis/Verifier.h"
32 #include "llvm/Bitcode/BitstreamReader.h"
33 #include "llvm/Bitcode/LLVMBitCodes.h"
34 #include "llvm/Bitcode/ReaderWriter.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/raw_ostream.h"
41 #include "llvm/Support/Signals.h"
42 #include "llvm/Support/system_error.h"
43 #include <cstdio>
44 #include <map>
45 #include <algorithm>
46 using namespace llvm;
47
48 static cl::opt<std::string>
49   InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
50
51 static cl::opt<bool> Dump("dump", cl::desc("Dump low level bitcode trace"));
52
53 //===----------------------------------------------------------------------===//
54 // Bitcode specific analysis.
55 //===----------------------------------------------------------------------===//
56
57 static cl::opt<bool> NoHistogram("disable-histogram",
58                                  cl::desc("Do not print per-code histogram"));
59
60 static cl::opt<bool>
61 NonSymbolic("non-symbolic",
62             cl::desc("Emit numeric info in dump even if"
63                      " symbolic info is available"));
64
65 namespace {
66
67 /// CurStreamTypeType - A type for CurStreamType
68 enum CurStreamTypeType {
69   UnknownBitstream,
70   LLVMIRBitstream
71 };
72
73 }
74
75 /// CurStreamType - If we can sniff the flavor of this stream, we can produce
76 /// better dump info.
77 static CurStreamTypeType CurStreamType;
78
79
80 /// GetBlockName - Return a symbolic block name if known, otherwise return
81 /// null.
82 static const char *GetBlockName(unsigned BlockID,
83                                 const BitstreamReader &StreamFile) {
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";
88     return 0;
89   }
90
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();
96   }
97
98
99   if (CurStreamType != LLVMIRBitstream) return 0;
100
101   switch (BlockID) {
102   default:                           return 0;
103   case bitc::MODULE_BLOCK_ID:        return "MODULE_BLOCK";
104   case bitc::PARAMATTR_BLOCK_ID:     return "PARAMATTR_BLOCK";
105   case bitc::TYPE_BLOCK_ID:          return "TYPE_BLOCK";
106   case bitc::CONSTANTS_BLOCK_ID:     return "CONSTANTS_BLOCK";
107   case bitc::FUNCTION_BLOCK_ID:      return "FUNCTION_BLOCK";
108   case bitc::TYPE_SYMTAB_BLOCK_ID:   return "TYPE_SYMTAB";
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   }
113 }
114
115 /// GetCodeName - Return a symbolic code name if known, otherwise return
116 /// null.
117 static const char *GetCodeName(unsigned CodeID, unsigned BlockID,
118                                const BitstreamReader &StreamFile) {
119   // Standard blocks for all bitcode files.
120   if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
121     if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
122       switch (CodeID) {
123       default: return 0;
124       case bitc::BLOCKINFO_CODE_SETBID:        return "SETBID";
125       case bitc::BLOCKINFO_CODE_BLOCKNAME:     return "BLOCKNAME";
126       case bitc::BLOCKINFO_CODE_SETRECORDNAME: return "SETRECORDNAME";
127       }
128     }
129     return 0;
130   }
131
132   // Check to see if we have a blockinfo record for this record, with a name.
133   if (const BitstreamReader::BlockInfo *Info =
134         StreamFile.getBlockInfo(BlockID)) {
135     for (unsigned i = 0, e = Info->RecordNames.size(); i != e; ++i)
136       if (Info->RecordNames[i].first == CodeID)
137         return Info->RecordNames[i].second.c_str();
138   }
139
140
141   if (CurStreamType != LLVMIRBitstream) return 0;
142
143   switch (BlockID) {
144   default: return 0;
145   case bitc::MODULE_BLOCK_ID:
146     switch (CodeID) {
147     default: return 0;
148     case bitc::MODULE_CODE_VERSION:     return "VERSION";
149     case bitc::MODULE_CODE_TRIPLE:      return "TRIPLE";
150     case bitc::MODULE_CODE_DATALAYOUT:  return "DATALAYOUT";
151     case bitc::MODULE_CODE_ASM:         return "ASM";
152     case bitc::MODULE_CODE_SECTIONNAME: return "SECTIONNAME";
153     case bitc::MODULE_CODE_DEPLIB:      return "DEPLIB";
154     case bitc::MODULE_CODE_GLOBALVAR:   return "GLOBALVAR";
155     case bitc::MODULE_CODE_FUNCTION:    return "FUNCTION";
156     case bitc::MODULE_CODE_ALIAS:       return "ALIAS";
157     case bitc::MODULE_CODE_PURGEVALS:   return "PURGEVALS";
158     case bitc::MODULE_CODE_GCNAME:      return "GCNAME";
159     }
160   case bitc::PARAMATTR_BLOCK_ID:
161     switch (CodeID) {
162     default: return 0;
163     case bitc::PARAMATTR_CODE_ENTRY: return "ENTRY";
164     }
165   case bitc::TYPE_BLOCK_ID:
166     switch (CodeID) {
167     default: return 0;
168     case bitc::TYPE_CODE_NUMENTRY:  return "NUMENTRY";
169     case bitc::TYPE_CODE_VOID:      return "VOID";
170     case bitc::TYPE_CODE_FLOAT:     return "FLOAT";
171     case bitc::TYPE_CODE_DOUBLE:    return "DOUBLE";
172     case bitc::TYPE_CODE_LABEL:     return "LABEL";
173     case bitc::TYPE_CODE_OPAQUE:    return "OPAQUE";
174     case bitc::TYPE_CODE_INTEGER:   return "INTEGER";
175     case bitc::TYPE_CODE_POINTER:   return "POINTER";
176     case bitc::TYPE_CODE_FUNCTION:  return "FUNCTION";
177     case bitc::TYPE_CODE_STRUCT:    return "STRUCT";
178     case bitc::TYPE_CODE_ARRAY:     return "ARRAY";
179     case bitc::TYPE_CODE_VECTOR:    return "VECTOR";
180     case bitc::TYPE_CODE_X86_FP80:  return "X86_FP80";
181     case bitc::TYPE_CODE_FP128:     return "FP128";
182     case bitc::TYPE_CODE_PPC_FP128: return "PPC_FP128";
183     case bitc::TYPE_CODE_METADATA:  return "METADATA";
184     }
185
186   case bitc::CONSTANTS_BLOCK_ID:
187     switch (CodeID) {
188     default: return 0;
189     case bitc::CST_CODE_SETTYPE:         return "SETTYPE";
190     case bitc::CST_CODE_NULL:            return "NULL";
191     case bitc::CST_CODE_UNDEF:           return "UNDEF";
192     case bitc::CST_CODE_INTEGER:         return "INTEGER";
193     case bitc::CST_CODE_WIDE_INTEGER:    return "WIDE_INTEGER";
194     case bitc::CST_CODE_FLOAT:           return "FLOAT";
195     case bitc::CST_CODE_AGGREGATE:       return "AGGREGATE";
196     case bitc::CST_CODE_STRING:          return "STRING";
197     case bitc::CST_CODE_CSTRING:         return "CSTRING";
198     case bitc::CST_CODE_CE_BINOP:        return "CE_BINOP";
199     case bitc::CST_CODE_CE_CAST:         return "CE_CAST";
200     case bitc::CST_CODE_CE_GEP:          return "CE_GEP";
201     case bitc::CST_CODE_CE_INBOUNDS_GEP: return "CE_INBOUNDS_GEP";
202     case bitc::CST_CODE_CE_SELECT:       return "CE_SELECT";
203     case bitc::CST_CODE_CE_EXTRACTELT:   return "CE_EXTRACTELT";
204     case bitc::CST_CODE_CE_INSERTELT:    return "CE_INSERTELT";
205     case bitc::CST_CODE_CE_SHUFFLEVEC:   return "CE_SHUFFLEVEC";
206     case bitc::CST_CODE_CE_CMP:          return "CE_CMP";
207     case bitc::CST_CODE_INLINEASM:       return "INLINEASM";
208     case bitc::CST_CODE_CE_SHUFVEC_EX:   return "CE_SHUFVEC_EX";
209     }
210   case bitc::FUNCTION_BLOCK_ID:
211     switch (CodeID) {
212     default: return 0;
213     case bitc::FUNC_CODE_DECLAREBLOCKS: return "DECLAREBLOCKS";
214
215     case bitc::FUNC_CODE_INST_BINOP:        return "INST_BINOP";
216     case bitc::FUNC_CODE_INST_CAST:         return "INST_CAST";
217     case bitc::FUNC_CODE_INST_GEP:          return "INST_GEP";
218     case bitc::FUNC_CODE_INST_INBOUNDS_GEP: return "INST_INBOUNDS_GEP";
219     case bitc::FUNC_CODE_INST_SELECT:       return "INST_SELECT";
220     case bitc::FUNC_CODE_INST_EXTRACTELT:   return "INST_EXTRACTELT";
221     case bitc::FUNC_CODE_INST_INSERTELT:    return "INST_INSERTELT";
222     case bitc::FUNC_CODE_INST_SHUFFLEVEC:   return "INST_SHUFFLEVEC";
223     case bitc::FUNC_CODE_INST_CMP:          return "INST_CMP";
224
225     case bitc::FUNC_CODE_INST_RET:          return "INST_RET";
226     case bitc::FUNC_CODE_INST_BR:           return "INST_BR";
227     case bitc::FUNC_CODE_INST_SWITCH:       return "INST_SWITCH";
228     case bitc::FUNC_CODE_INST_INVOKE:       return "INST_INVOKE";
229     case bitc::FUNC_CODE_INST_UNWIND:       return "INST_UNWIND";
230     case bitc::FUNC_CODE_INST_UNREACHABLE:  return "INST_UNREACHABLE";
231
232     case bitc::FUNC_CODE_INST_PHI:          return "INST_PHI";
233     case bitc::FUNC_CODE_INST_MALLOC:       return "INST_MALLOC";
234     case bitc::FUNC_CODE_INST_FREE:         return "INST_FREE";
235     case bitc::FUNC_CODE_INST_ALLOCA:       return "INST_ALLOCA";
236     case bitc::FUNC_CODE_INST_LOAD:         return "INST_LOAD";
237     case bitc::FUNC_CODE_INST_STORE:        return "INST_STORE";
238     case bitc::FUNC_CODE_INST_CALL:         return "INST_CALL";
239     case bitc::FUNC_CODE_INST_VAARG:        return "INST_VAARG";
240     case bitc::FUNC_CODE_INST_STORE2:       return "INST_STORE2";
241     case bitc::FUNC_CODE_INST_GETRESULT:    return "INST_GETRESULT";
242     case bitc::FUNC_CODE_INST_EXTRACTVAL:   return "INST_EXTRACTVAL";
243     case bitc::FUNC_CODE_INST_INSERTVAL:    return "INST_INSERTVAL";
244     case bitc::FUNC_CODE_INST_CMP2:         return "INST_CMP2";
245     case bitc::FUNC_CODE_INST_VSELECT:      return "INST_VSELECT";
246     case bitc::FUNC_CODE_DEBUG_LOC:         return "DEBUG_LOC";
247     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:   return "DEBUG_LOC_AGAIN";
248     case bitc::FUNC_CODE_INST_CALL2:        return "INST_CALL2";
249     case bitc::FUNC_CODE_DEBUG_LOC2:        return "DEBUG_LOC2";
250     }
251   case bitc::TYPE_SYMTAB_BLOCK_ID:
252     switch (CodeID) {
253     default: return 0;
254     case bitc::TST_CODE_ENTRY: return "ENTRY";
255     }
256   case bitc::VALUE_SYMTAB_BLOCK_ID:
257     switch (CodeID) {
258     default: return 0;
259     case bitc::VST_CODE_ENTRY: return "ENTRY";
260     case bitc::VST_CODE_BBENTRY: return "BBENTRY";
261     }
262   case bitc::METADATA_ATTACHMENT_ID:
263     switch(CodeID) {
264     default:return 0;
265     case bitc::METADATA_ATTACHMENT:  return "METADATA_ATTACHMENT";
266     case bitc::METADATA_ATTACHMENT2: return "METADATA_ATTACHMENT2";
267     }
268   case bitc::METADATA_BLOCK_ID:
269     switch(CodeID) {
270     default:return 0;
271     case bitc::METADATA_STRING:      return "METADATA_STRING";
272     case bitc::METADATA_NODE:        return "METADATA_NODE";
273     case bitc::METADATA_FN_NODE:     return "METADATA_FN_NODE";
274     case bitc::METADATA_NAME:        return "METADATA_NAME";
275     case bitc::METADATA_NAMED_NODE:  return "METADATA_NAMED_NODE";
276     case bitc::METADATA_KIND:        return "METADATA_KIND";
277     case bitc::METADATA_ATTACHMENT:  return "METADATA_ATTACHMENT";
278     case bitc::METADATA_NODE2:       return "METADATA_NODE2";
279     case bitc::METADATA_FN_NODE2:    return "METADATA_FN_NODE2";
280     case bitc::METADATA_NAMED_NODE2: return "METADATA_NAMED_NODE2";
281     }
282   }
283 }
284
285 struct PerRecordStats {
286   unsigned NumInstances;
287   unsigned NumAbbrev;
288   uint64_t TotalBits;
289
290   PerRecordStats() : NumInstances(0), NumAbbrev(0), TotalBits(0) {}
291 };
292
293 struct PerBlockIDStats {
294   /// NumInstances - This the number of times this block ID has been seen.
295   unsigned NumInstances;
296
297   /// NumBits - The total size in bits of all of these blocks.
298   uint64_t NumBits;
299
300   /// NumSubBlocks - The total number of blocks these blocks contain.
301   unsigned NumSubBlocks;
302
303   /// NumAbbrevs - The total number of abbreviations.
304   unsigned NumAbbrevs;
305
306   /// NumRecords - The total number of records these blocks contain, and the
307   /// number that are abbreviated.
308   unsigned NumRecords, NumAbbreviatedRecords;
309
310   /// CodeFreq - Keep track of the number of times we see each code.
311   std::vector<PerRecordStats> CodeFreq;
312
313   PerBlockIDStats()
314     : NumInstances(0), NumBits(0),
315       NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {}
316 };
317
318 static std::map<unsigned, PerBlockIDStats> BlockIDStats;
319
320
321
322 /// Error - All bitcode analysis errors go through this function, making this a
323 /// good place to breakpoint if debugging.
324 static bool Error(const std::string &Err) {
325   errs() << Err << "\n";
326   return true;
327 }
328
329 /// ParseBlock - Read a block, updating statistics, etc.
330 static bool ParseBlock(BitstreamCursor &Stream, unsigned IndentLevel) {
331   std::string Indent(IndentLevel*2, ' ');
332   uint64_t BlockBitStart = Stream.GetCurrentBitNo();
333   unsigned BlockID = Stream.ReadSubBlockID();
334
335   // Get the statistics for this BlockID.
336   PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
337
338   BlockStats.NumInstances++;
339
340   // BLOCKINFO is a special part of the stream.
341   if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
342     if (Dump) errs() << Indent << "<BLOCKINFO_BLOCK/>\n";
343     if (Stream.ReadBlockInfoBlock())
344       return Error("Malformed BlockInfoBlock");
345     uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
346     BlockStats.NumBits += BlockBitEnd-BlockBitStart;
347     return false;
348   }
349
350   unsigned NumWords = 0;
351   if (Stream.EnterSubBlock(BlockID, &NumWords))
352     return Error("Malformed block record");
353
354   const char *BlockName = 0;
355   if (Dump) {
356     errs() << Indent << "<";
357     if ((BlockName = GetBlockName(BlockID, *Stream.getBitStreamReader())))
358       errs() << BlockName;
359     else
360       errs() << "UnknownBlock" << BlockID;
361
362     if (NonSymbolic && BlockName)
363       errs() << " BlockID=" << BlockID;
364
365     errs() << " NumWords=" << NumWords
366            << " BlockCodeSize=" << Stream.GetAbbrevIDWidth() << ">\n";
367   }
368
369   SmallVector<uint64_t, 64> Record;
370
371   // Read all the records for this block.
372   while (1) {
373     if (Stream.AtEndOfStream())
374       return Error("Premature end of bitstream");
375
376     uint64_t RecordStartBit = Stream.GetCurrentBitNo();
377
378     // Read the code for this record.
379     unsigned AbbrevID = Stream.ReadCode();
380     switch (AbbrevID) {
381     case bitc::END_BLOCK: {
382       if (Stream.ReadBlockEnd())
383         return Error("Error at end of block");
384       uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
385       BlockStats.NumBits += BlockBitEnd-BlockBitStart;
386       if (Dump) {
387         errs() << Indent << "</";
388         if (BlockName)
389           errs() << BlockName << ">\n";
390         else
391           errs() << "UnknownBlock" << BlockID << ">\n";
392       }
393       return false;
394     }
395     case bitc::ENTER_SUBBLOCK: {
396       uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
397       if (ParseBlock(Stream, IndentLevel+1))
398         return true;
399       ++BlockStats.NumSubBlocks;
400       uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
401
402       // Don't include subblock sizes in the size of this block.
403       BlockBitStart += SubBlockBitEnd-SubBlockBitStart;
404       break;
405     }
406     case bitc::DEFINE_ABBREV:
407       Stream.ReadAbbrevRecord();
408       ++BlockStats.NumAbbrevs;
409       break;
410     default:
411       Record.clear();
412
413       ++BlockStats.NumRecords;
414       if (AbbrevID != bitc::UNABBREV_RECORD)
415         ++BlockStats.NumAbbreviatedRecords;
416
417       const char *BlobStart = 0;
418       unsigned BlobLen = 0;
419       unsigned Code = Stream.ReadRecord(AbbrevID, Record, BlobStart, BlobLen);
420
421
422
423       // Increment the # occurrences of this code.
424       if (BlockStats.CodeFreq.size() <= Code)
425         BlockStats.CodeFreq.resize(Code+1);
426       BlockStats.CodeFreq[Code].NumInstances++;
427       BlockStats.CodeFreq[Code].TotalBits +=
428         Stream.GetCurrentBitNo()-RecordStartBit;
429       if (AbbrevID != bitc::UNABBREV_RECORD)
430         BlockStats.CodeFreq[Code].NumAbbrev++;
431
432       if (Dump) {
433         errs() << Indent << "  <";
434         if (const char *CodeName =
435               GetCodeName(Code, BlockID, *Stream.getBitStreamReader()))
436           errs() << CodeName;
437         else
438           errs() << "UnknownCode" << Code;
439         if (NonSymbolic &&
440             GetCodeName(Code, BlockID, *Stream.getBitStreamReader()))
441           errs() << " codeid=" << Code;
442         if (AbbrevID != bitc::UNABBREV_RECORD)
443           errs() << " abbrevid=" << AbbrevID;
444
445         for (unsigned i = 0, e = Record.size(); i != e; ++i)
446           errs() << " op" << i << "=" << (int64_t)Record[i];
447
448         errs() << "/>";
449
450         if (BlobStart) {
451           errs() << " blob data = ";
452           bool BlobIsPrintable = true;
453           for (unsigned i = 0; i != BlobLen; ++i)
454             if (!isprint(BlobStart[i])) {
455               BlobIsPrintable = false;
456               break;
457             }
458
459           if (BlobIsPrintable)
460             errs() << "'" << std::string(BlobStart, BlobStart+BlobLen) <<"'";
461           else
462             errs() << "unprintable, " << BlobLen << " bytes.";
463         }
464
465         errs() << "\n";
466       }
467
468       break;
469     }
470   }
471 }
472
473 static void PrintSize(double Bits) {
474   fprintf(stderr, "%.2f/%.2fB/%luW", Bits, Bits/8,(unsigned long)(Bits/32));
475 }
476 static void PrintSize(uint64_t Bits) {
477   fprintf(stderr, "%lub/%.2fB/%luW", (unsigned long)Bits,
478           (double)Bits/8, (unsigned long)(Bits/32));
479 }
480
481
482 /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
483 static int AnalyzeBitcode() {
484   // Read the input file.
485   OwningPtr<MemoryBuffer> MemBuf;
486
487   if (error_code ec =
488         MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), MemBuf))
489     return Error("Error reading '" + InputFilename + "': " + ec.message());
490
491   if (MemBuf->getBufferSize() & 3)
492     return Error("Bitcode stream should be a multiple of 4 bytes in length");
493
494   unsigned char *BufPtr = (unsigned char *)MemBuf->getBufferStart();
495   unsigned char *EndBufPtr = BufPtr+MemBuf->getBufferSize();
496
497   // If we have a wrapper header, parse it and ignore the non-bc file contents.
498   // The magic number is 0x0B17C0DE stored in little endian.
499   if (isBitcodeWrapper(BufPtr, EndBufPtr))
500     if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr))
501       return Error("Invalid bitcode wrapper header");
502
503   BitstreamReader StreamFile(BufPtr, EndBufPtr);
504   BitstreamCursor Stream(StreamFile);
505   StreamFile.CollectBlockInfoNames();
506
507   // Read the stream signature.
508   char Signature[6];
509   Signature[0] = Stream.Read(8);
510   Signature[1] = Stream.Read(8);
511   Signature[2] = Stream.Read(4);
512   Signature[3] = Stream.Read(4);
513   Signature[4] = Stream.Read(4);
514   Signature[5] = Stream.Read(4);
515
516   // Autodetect the file contents, if it is one we know.
517   CurStreamType = UnknownBitstream;
518   if (Signature[0] == 'B' && Signature[1] == 'C' &&
519       Signature[2] == 0x0 && Signature[3] == 0xC &&
520       Signature[4] == 0xE && Signature[5] == 0xD)
521     CurStreamType = LLVMIRBitstream;
522
523   unsigned NumTopBlocks = 0;
524
525   // Parse the top-level structure.  We only allow blocks at the top-level.
526   while (!Stream.AtEndOfStream()) {
527     unsigned Code = Stream.ReadCode();
528     if (Code != bitc::ENTER_SUBBLOCK)
529       return Error("Invalid record at top-level");
530
531     if (ParseBlock(Stream, 0))
532       return true;
533     ++NumTopBlocks;
534   }
535
536   if (Dump) errs() << "\n\n";
537
538   uint64_t BufferSizeBits = (EndBufPtr-BufPtr)*CHAR_BIT;
539   // Print a summary of the read file.
540   errs() << "Summary of " << InputFilename << ":\n";
541   errs() << "         Total size: ";
542   PrintSize(BufferSizeBits);
543   errs() << "\n";
544   errs() << "        Stream type: ";
545   switch (CurStreamType) {
546   default: assert(0 && "Unknown bitstream type");
547   case UnknownBitstream: errs() << "unknown\n"; break;
548   case LLVMIRBitstream:  errs() << "LLVM IR\n"; break;
549   }
550   errs() << "  # Toplevel Blocks: " << NumTopBlocks << "\n";
551   errs() << "\n";
552
553   // Emit per-block stats.
554   errs() << "Per-block Summary:\n";
555   for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(),
556        E = BlockIDStats.end(); I != E; ++I) {
557     errs() << "  Block ID #" << I->first;
558     if (const char *BlockName = GetBlockName(I->first, StreamFile))
559       errs() << " (" << BlockName << ")";
560     errs() << ":\n";
561
562     const PerBlockIDStats &Stats = I->second;
563     errs() << "      Num Instances: " << Stats.NumInstances << "\n";
564     errs() << "         Total Size: ";
565     PrintSize(Stats.NumBits);
566     errs() << "\n";
567     double pct = (Stats.NumBits * 100.0) / BufferSizeBits;
568     errs() << "    Percent of file: " << format("%2.4f%%", pct) << "\n";
569     if (Stats.NumInstances > 1) {
570       errs() << "       Average Size: ";
571       PrintSize(Stats.NumBits/(double)Stats.NumInstances);
572       errs() << "\n";
573       errs() << "  Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
574              << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
575       errs() << "    Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
576              << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
577       errs() << "    Tot/Avg Records: " << Stats.NumRecords << "/"
578              << Stats.NumRecords/(double)Stats.NumInstances << "\n";
579     } else {
580       errs() << "      Num SubBlocks: " << Stats.NumSubBlocks << "\n";
581       errs() << "        Num Abbrevs: " << Stats.NumAbbrevs << "\n";
582       errs() << "        Num Records: " << Stats.NumRecords << "\n";
583     }
584     if (Stats.NumRecords) {
585       double pct = (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumRecords;
586       errs() << "    Percent Abbrevs: " << format("%2.4f%%", pct) << "\n";
587     }
588     errs() << "\n";
589
590     // Print a histogram of the codes we see.
591     if (!NoHistogram && !Stats.CodeFreq.empty()) {
592       std::vector<std::pair<unsigned, unsigned> > FreqPairs;  // <freq,code>
593       for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
594         if (unsigned Freq = Stats.CodeFreq[i].NumInstances)
595           FreqPairs.push_back(std::make_pair(Freq, i));
596       std::stable_sort(FreqPairs.begin(), FreqPairs.end());
597       std::reverse(FreqPairs.begin(), FreqPairs.end());
598
599       errs() << "\tRecord Histogram:\n";
600       fprintf(stderr, "\t\t  Count    # Bits   %% Abv  Record Kind\n");
601       for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
602         const PerRecordStats &RecStats = Stats.CodeFreq[FreqPairs[i].second];
603
604         fprintf(stderr, "\t\t%7d %9lu ", RecStats.NumInstances,
605                 (unsigned long)RecStats.TotalBits);
606
607         if (RecStats.NumAbbrev)
608           fprintf(stderr, "%7.2f  ",
609                   (double)RecStats.NumAbbrev/RecStats.NumInstances*100);
610         else
611           fprintf(stderr, "         ");
612
613         if (const char *CodeName =
614               GetCodeName(FreqPairs[i].second, I->first, StreamFile))
615           fprintf(stderr, "%s\n", CodeName);
616         else
617           fprintf(stderr, "UnknownCode%d\n", FreqPairs[i].second);
618       }
619       errs() << "\n";
620
621     }
622   }
623   return 0;
624 }
625
626
627 int main(int argc, char **argv) {
628   // Print a stack trace if we signal out.
629   sys::PrintStackTraceOnErrorSignal();
630   PrettyStackTraceProgram X(argc, argv);
631   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
632   cl::ParseCommandLineOptions(argc, argv, "llvm-bcanalyzer file analyzer\n");
633
634   return AnalyzeBitcode();
635 }