[llvm-objdump/MachODump] Reduce code duplication.
[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/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"
42 #include <algorithm>
43 #include <cctype>
44 #include <map>
45 #include <system_error>
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 static cl::opt<std::string>
66   BlockInfoFilename("block-info",
67                     cl::desc("Use the BLOCK_INFO from the given file"));
68
69 static cl::opt<bool>
70   ShowBinaryBlobs("show-binary-blobs",
71                   cl::desc("Print binary blobs using hex escapes"));
72
73 namespace {
74
75 /// CurStreamTypeType - A type for CurStreamType
76 enum CurStreamTypeType {
77   UnknownBitstream,
78   LLVMIRBitstream
79 };
80
81 }
82
83 /// GetBlockName - Return a symbolic block name if known, otherwise return
84 /// null.
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";
92     return nullptr;
93   }
94
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();
100   }
101
102
103   if (CurStreamType != LLVMIRBitstream) return nullptr;
104
105   switch (BlockID) {
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::IDENTIFICATION_BLOCK_ID:
114     return "IDENTIFICATION_BLOCK_ID";
115   case bitc::VALUE_SYMTAB_BLOCK_ID:    return "VALUE_SYMTAB";
116   case bitc::METADATA_BLOCK_ID:        return "METADATA_BLOCK";
117   case bitc::METADATA_KIND_BLOCK_ID:   return "METADATA_KIND_BLOCK";
118   case bitc::METADATA_ATTACHMENT_ID:   return "METADATA_ATTACHMENT_BLOCK";
119   case bitc::USELIST_BLOCK_ID:         return "USELIST_BLOCK_ID";
120   case bitc::FUNCTION_SUMMARY_BLOCK_ID:
121                                        return "FUNCTION_SUMMARY_BLOCK";
122   case bitc::MODULE_STRTAB_BLOCK_ID:   return "MODULE_STRTAB_BLOCK";
123   }
124 }
125
126 /// GetCodeName - Return a symbolic code name if known, otherwise return
127 /// null.
128 static const char *GetCodeName(unsigned CodeID, unsigned BlockID,
129                                const BitstreamReader &StreamFile,
130                                CurStreamTypeType CurStreamType) {
131   // Standard blocks for all bitcode files.
132   if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
133     if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
134       switch (CodeID) {
135       default: return nullptr;
136       case bitc::BLOCKINFO_CODE_SETBID:        return "SETBID";
137       case bitc::BLOCKINFO_CODE_BLOCKNAME:     return "BLOCKNAME";
138       case bitc::BLOCKINFO_CODE_SETRECORDNAME: return "SETRECORDNAME";
139       }
140     }
141     return nullptr;
142   }
143
144   // Check to see if we have a blockinfo record for this record, with a name.
145   if (const BitstreamReader::BlockInfo *Info =
146         StreamFile.getBlockInfo(BlockID)) {
147     for (unsigned i = 0, e = Info->RecordNames.size(); i != e; ++i)
148       if (Info->RecordNames[i].first == CodeID)
149         return Info->RecordNames[i].second.c_str();
150   }
151
152
153   if (CurStreamType != LLVMIRBitstream) return nullptr;
154
155 #define STRINGIFY_CODE(PREFIX, CODE)                                           \
156   case bitc::PREFIX##_##CODE:                                                  \
157     return #CODE;
158   switch (BlockID) {
159   default: return nullptr;
160   case bitc::MODULE_BLOCK_ID:
161     switch (CodeID) {
162     default: return nullptr;
163       STRINGIFY_CODE(MODULE_CODE, VERSION)
164       STRINGIFY_CODE(MODULE_CODE, TRIPLE)
165       STRINGIFY_CODE(MODULE_CODE, DATALAYOUT)
166       STRINGIFY_CODE(MODULE_CODE, ASM)
167       STRINGIFY_CODE(MODULE_CODE, SECTIONNAME)
168       STRINGIFY_CODE(MODULE_CODE, DEPLIB) // FIXME: Remove in 4.0
169       STRINGIFY_CODE(MODULE_CODE, GLOBALVAR)
170       STRINGIFY_CODE(MODULE_CODE, FUNCTION)
171       STRINGIFY_CODE(MODULE_CODE, ALIAS)
172       STRINGIFY_CODE(MODULE_CODE, PURGEVALS)
173       STRINGIFY_CODE(MODULE_CODE, GCNAME)
174       STRINGIFY_CODE(MODULE_CODE, VSTOFFSET)
175       STRINGIFY_CODE(MODULE_CODE, METADATA_VALUES)
176     }
177   case bitc::IDENTIFICATION_BLOCK_ID:
178     switch (CodeID) {
179     default:
180       return nullptr;
181       STRINGIFY_CODE(IDENTIFICATION_CODE, STRING)
182       STRINGIFY_CODE(IDENTIFICATION_CODE, EPOCH)
183     }
184   case bitc::PARAMATTR_BLOCK_ID:
185     switch (CodeID) {
186     default: return nullptr;
187     // FIXME: Should these be different?
188     case bitc::PARAMATTR_CODE_ENTRY_OLD: return "ENTRY";
189     case bitc::PARAMATTR_CODE_ENTRY:     return "ENTRY";
190     case bitc::PARAMATTR_GRP_CODE_ENTRY: return "ENTRY";
191     }
192   case bitc::TYPE_BLOCK_ID_NEW:
193     switch (CodeID) {
194     default: return nullptr;
195       STRINGIFY_CODE(TYPE_CODE, NUMENTRY)
196       STRINGIFY_CODE(TYPE_CODE, VOID)
197       STRINGIFY_CODE(TYPE_CODE, FLOAT)
198       STRINGIFY_CODE(TYPE_CODE, DOUBLE)
199       STRINGIFY_CODE(TYPE_CODE, LABEL)
200       STRINGIFY_CODE(TYPE_CODE, OPAQUE)
201       STRINGIFY_CODE(TYPE_CODE, INTEGER)
202       STRINGIFY_CODE(TYPE_CODE, POINTER)
203       STRINGIFY_CODE(TYPE_CODE, ARRAY)
204       STRINGIFY_CODE(TYPE_CODE, VECTOR)
205       STRINGIFY_CODE(TYPE_CODE, X86_FP80)
206       STRINGIFY_CODE(TYPE_CODE, FP128)
207       STRINGIFY_CODE(TYPE_CODE, PPC_FP128)
208       STRINGIFY_CODE(TYPE_CODE, METADATA)
209       STRINGIFY_CODE(TYPE_CODE, STRUCT_ANON)
210       STRINGIFY_CODE(TYPE_CODE, STRUCT_NAME)
211       STRINGIFY_CODE(TYPE_CODE, STRUCT_NAMED)
212       STRINGIFY_CODE(TYPE_CODE, FUNCTION)
213     }
214
215   case bitc::CONSTANTS_BLOCK_ID:
216     switch (CodeID) {
217     default: return nullptr;
218       STRINGIFY_CODE(CST_CODE, SETTYPE)
219       STRINGIFY_CODE(CST_CODE, NULL)
220       STRINGIFY_CODE(CST_CODE, UNDEF)
221       STRINGIFY_CODE(CST_CODE, INTEGER)
222       STRINGIFY_CODE(CST_CODE, WIDE_INTEGER)
223       STRINGIFY_CODE(CST_CODE, FLOAT)
224       STRINGIFY_CODE(CST_CODE, AGGREGATE)
225       STRINGIFY_CODE(CST_CODE, STRING)
226       STRINGIFY_CODE(CST_CODE, CSTRING)
227       STRINGIFY_CODE(CST_CODE, CE_BINOP)
228       STRINGIFY_CODE(CST_CODE, CE_CAST)
229       STRINGIFY_CODE(CST_CODE, CE_GEP)
230       STRINGIFY_CODE(CST_CODE, CE_INBOUNDS_GEP)
231       STRINGIFY_CODE(CST_CODE, CE_SELECT)
232       STRINGIFY_CODE(CST_CODE, CE_EXTRACTELT)
233       STRINGIFY_CODE(CST_CODE, CE_INSERTELT)
234       STRINGIFY_CODE(CST_CODE, CE_SHUFFLEVEC)
235       STRINGIFY_CODE(CST_CODE, CE_CMP)
236       STRINGIFY_CODE(CST_CODE, INLINEASM)
237       STRINGIFY_CODE(CST_CODE, CE_SHUFVEC_EX)
238     case bitc::CST_CODE_BLOCKADDRESS:    return "CST_CODE_BLOCKADDRESS";
239       STRINGIFY_CODE(CST_CODE, DATA)
240     }
241   case bitc::FUNCTION_BLOCK_ID:
242     switch (CodeID) {
243     default: return nullptr;
244       STRINGIFY_CODE(FUNC_CODE, DECLAREBLOCKS)
245       STRINGIFY_CODE(FUNC_CODE, INST_BINOP)
246       STRINGIFY_CODE(FUNC_CODE, INST_CAST)
247       STRINGIFY_CODE(FUNC_CODE, INST_GEP_OLD)
248       STRINGIFY_CODE(FUNC_CODE, INST_INBOUNDS_GEP_OLD)
249       STRINGIFY_CODE(FUNC_CODE, INST_SELECT)
250       STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTELT)
251       STRINGIFY_CODE(FUNC_CODE, INST_INSERTELT)
252       STRINGIFY_CODE(FUNC_CODE, INST_SHUFFLEVEC)
253       STRINGIFY_CODE(FUNC_CODE, INST_CMP)
254       STRINGIFY_CODE(FUNC_CODE, INST_RET)
255       STRINGIFY_CODE(FUNC_CODE, INST_BR)
256       STRINGIFY_CODE(FUNC_CODE, INST_SWITCH)
257       STRINGIFY_CODE(FUNC_CODE, INST_INVOKE)
258       STRINGIFY_CODE(FUNC_CODE, INST_UNREACHABLE)
259       STRINGIFY_CODE(FUNC_CODE, INST_CLEANUPRET)
260       STRINGIFY_CODE(FUNC_CODE, INST_CATCHRET)
261       STRINGIFY_CODE(FUNC_CODE, INST_CATCHPAD)
262       STRINGIFY_CODE(FUNC_CODE, INST_CLEANUPENDPAD)
263       STRINGIFY_CODE(FUNC_CODE, INST_CATCHENDPAD)
264       STRINGIFY_CODE(FUNC_CODE, INST_TERMINATEPAD)
265       STRINGIFY_CODE(FUNC_CODE, INST_PHI)
266       STRINGIFY_CODE(FUNC_CODE, INST_ALLOCA)
267       STRINGIFY_CODE(FUNC_CODE, INST_LOAD)
268       STRINGIFY_CODE(FUNC_CODE, INST_VAARG)
269       STRINGIFY_CODE(FUNC_CODE, INST_STORE)
270       STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTVAL)
271       STRINGIFY_CODE(FUNC_CODE, INST_INSERTVAL)
272       STRINGIFY_CODE(FUNC_CODE, INST_CMP2)
273       STRINGIFY_CODE(FUNC_CODE, INST_VSELECT)
274       STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC_AGAIN)
275       STRINGIFY_CODE(FUNC_CODE, INST_CALL)
276       STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC)
277       STRINGIFY_CODE(FUNC_CODE, INST_GEP)
278     }
279   case bitc::VALUE_SYMTAB_BLOCK_ID:
280     switch (CodeID) {
281     default: return nullptr;
282     STRINGIFY_CODE(VST_CODE, ENTRY)
283     STRINGIFY_CODE(VST_CODE, BBENTRY)
284     STRINGIFY_CODE(VST_CODE, FNENTRY)
285     STRINGIFY_CODE(VST_CODE, COMBINED_FNENTRY)
286     }
287   case bitc::MODULE_STRTAB_BLOCK_ID:
288     switch (CodeID) {
289     default:
290       return nullptr;
291       STRINGIFY_CODE(MST_CODE, ENTRY)
292     }
293   case bitc::FUNCTION_SUMMARY_BLOCK_ID:
294     switch (CodeID) {
295     default:
296       return nullptr;
297       STRINGIFY_CODE(FS_CODE, PERMODULE_ENTRY)
298       STRINGIFY_CODE(FS_CODE, COMBINED_ENTRY)
299     }
300   case bitc::METADATA_ATTACHMENT_ID:
301     switch(CodeID) {
302     default:return nullptr;
303       STRINGIFY_CODE(METADATA, ATTACHMENT)
304     }
305   case bitc::METADATA_BLOCK_ID:
306     switch(CodeID) {
307     default:return nullptr;
308       STRINGIFY_CODE(METADATA, STRING)
309       STRINGIFY_CODE(METADATA, NAME)
310       STRINGIFY_CODE(METADATA, KIND) // Older bitcode has it in a MODULE_BLOCK
311       STRINGIFY_CODE(METADATA, NODE)
312       STRINGIFY_CODE(METADATA, VALUE)
313       STRINGIFY_CODE(METADATA, OLD_NODE)
314       STRINGIFY_CODE(METADATA, OLD_FN_NODE)
315       STRINGIFY_CODE(METADATA, NAMED_NODE)
316       STRINGIFY_CODE(METADATA, DISTINCT_NODE)
317       STRINGIFY_CODE(METADATA, LOCATION)
318       STRINGIFY_CODE(METADATA, GENERIC_DEBUG)
319       STRINGIFY_CODE(METADATA, SUBRANGE)
320       STRINGIFY_CODE(METADATA, ENUMERATOR)
321       STRINGIFY_CODE(METADATA, BASIC_TYPE)
322       STRINGIFY_CODE(METADATA, FILE)
323       STRINGIFY_CODE(METADATA, DERIVED_TYPE)
324       STRINGIFY_CODE(METADATA, COMPOSITE_TYPE)
325       STRINGIFY_CODE(METADATA, SUBROUTINE_TYPE)
326       STRINGIFY_CODE(METADATA, COMPILE_UNIT)
327       STRINGIFY_CODE(METADATA, SUBPROGRAM)
328       STRINGIFY_CODE(METADATA, LEXICAL_BLOCK)
329       STRINGIFY_CODE(METADATA, LEXICAL_BLOCK_FILE)
330       STRINGIFY_CODE(METADATA, NAMESPACE)
331       STRINGIFY_CODE(METADATA, TEMPLATE_TYPE)
332       STRINGIFY_CODE(METADATA, TEMPLATE_VALUE)
333       STRINGIFY_CODE(METADATA, GLOBAL_VAR)
334       STRINGIFY_CODE(METADATA, LOCAL_VAR)
335       STRINGIFY_CODE(METADATA, EXPRESSION)
336       STRINGIFY_CODE(METADATA, OBJC_PROPERTY)
337       STRINGIFY_CODE(METADATA, IMPORTED_ENTITY)
338       STRINGIFY_CODE(METADATA, MODULE)
339     }
340   case bitc::METADATA_KIND_BLOCK_ID:
341     switch (CodeID) {
342     default:
343       return nullptr;
344       STRINGIFY_CODE(METADATA, KIND)
345     }
346   case bitc::USELIST_BLOCK_ID:
347     switch(CodeID) {
348     default:return nullptr;
349     case bitc::USELIST_CODE_DEFAULT: return "USELIST_CODE_DEFAULT";
350     case bitc::USELIST_CODE_BB:      return "USELIST_CODE_BB";
351     }
352   }
353 #undef STRINGIFY_CODE
354 }
355
356 struct PerRecordStats {
357   unsigned NumInstances;
358   unsigned NumAbbrev;
359   uint64_t TotalBits;
360
361   PerRecordStats() : NumInstances(0), NumAbbrev(0), TotalBits(0) {}
362 };
363
364 struct PerBlockIDStats {
365   /// NumInstances - This the number of times this block ID has been seen.
366   unsigned NumInstances;
367
368   /// NumBits - The total size in bits of all of these blocks.
369   uint64_t NumBits;
370
371   /// NumSubBlocks - The total number of blocks these blocks contain.
372   unsigned NumSubBlocks;
373
374   /// NumAbbrevs - The total number of abbreviations.
375   unsigned NumAbbrevs;
376
377   /// NumRecords - The total number of records these blocks contain, and the
378   /// number that are abbreviated.
379   unsigned NumRecords, NumAbbreviatedRecords;
380
381   /// CodeFreq - Keep track of the number of times we see each code.
382   std::vector<PerRecordStats> CodeFreq;
383
384   PerBlockIDStats()
385     : NumInstances(0), NumBits(0),
386       NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {}
387 };
388
389 static std::map<unsigned, PerBlockIDStats> BlockIDStats;
390
391
392
393 /// Error - All bitcode analysis errors go through this function, making this a
394 /// good place to breakpoint if debugging.
395 static bool Error(const Twine &Err) {
396   errs() << Err << "\n";
397   return true;
398 }
399
400 /// ParseBlock - Read a block, updating statistics, etc.
401 static bool ParseBlock(BitstreamCursor &Stream, unsigned BlockID,
402                        unsigned IndentLevel, CurStreamTypeType CurStreamType) {
403   std::string Indent(IndentLevel*2, ' ');
404   uint64_t BlockBitStart = Stream.GetCurrentBitNo();
405
406   // Get the statistics for this BlockID.
407   PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
408
409   BlockStats.NumInstances++;
410
411   // BLOCKINFO is a special part of the stream.
412   if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
413     if (Dump) outs() << Indent << "<BLOCKINFO_BLOCK/>\n";
414     if (Stream.ReadBlockInfoBlock())
415       return Error("Malformed BlockInfoBlock");
416     uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
417     BlockStats.NumBits += BlockBitEnd-BlockBitStart;
418     return false;
419   }
420
421   unsigned NumWords = 0;
422   if (Stream.EnterSubBlock(BlockID, &NumWords))
423     return Error("Malformed block record");
424
425   const char *BlockName = nullptr;
426   if (Dump) {
427     outs() << Indent << "<";
428     if ((BlockName = GetBlockName(BlockID, *Stream.getBitStreamReader(),
429                                   CurStreamType)))
430       outs() << BlockName;
431     else
432       outs() << "UnknownBlock" << BlockID;
433
434     if (NonSymbolic && BlockName)
435       outs() << " BlockID=" << BlockID;
436
437     outs() << " NumWords=" << NumWords
438            << " BlockCodeSize=" << Stream.getAbbrevIDWidth() << ">\n";
439   }
440
441   SmallVector<uint64_t, 64> Record;
442
443   // Read all the records for this block.
444   while (1) {
445     if (Stream.AtEndOfStream())
446       return Error("Premature end of bitstream");
447
448     uint64_t RecordStartBit = Stream.GetCurrentBitNo();
449
450     BitstreamEntry Entry =
451       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
452     
453     switch (Entry.Kind) {
454     case BitstreamEntry::Error:
455       return Error("malformed bitcode file");
456     case BitstreamEntry::EndBlock: {
457       uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
458       BlockStats.NumBits += BlockBitEnd-BlockBitStart;
459       if (Dump) {
460         outs() << Indent << "</";
461         if (BlockName)
462           outs() << BlockName << ">\n";
463         else
464           outs() << "UnknownBlock" << BlockID << ">\n";
465       }
466       return false;
467     }
468         
469     case BitstreamEntry::SubBlock: {
470       uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
471       if (ParseBlock(Stream, Entry.ID, IndentLevel+1, CurStreamType))
472         return true;
473       ++BlockStats.NumSubBlocks;
474       uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
475       
476       // Don't include subblock sizes in the size of this block.
477       BlockBitStart += SubBlockBitEnd-SubBlockBitStart;
478       continue;
479     }
480     case BitstreamEntry::Record:
481       // The interesting case.
482       break;
483     }
484
485     if (Entry.ID == bitc::DEFINE_ABBREV) {
486       Stream.ReadAbbrevRecord();
487       ++BlockStats.NumAbbrevs;
488       continue;
489     }
490     
491     Record.clear();
492
493     ++BlockStats.NumRecords;
494
495     StringRef Blob;
496     unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
497
498     // Increment the # occurrences of this code.
499     if (BlockStats.CodeFreq.size() <= Code)
500       BlockStats.CodeFreq.resize(Code+1);
501     BlockStats.CodeFreq[Code].NumInstances++;
502     BlockStats.CodeFreq[Code].TotalBits +=
503       Stream.GetCurrentBitNo()-RecordStartBit;
504     if (Entry.ID != bitc::UNABBREV_RECORD) {
505       BlockStats.CodeFreq[Code].NumAbbrev++;
506       ++BlockStats.NumAbbreviatedRecords;
507     }
508
509     if (Dump) {
510       outs() << Indent << "  <";
511       if (const char *CodeName =
512             GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
513                         CurStreamType))
514         outs() << CodeName;
515       else
516         outs() << "UnknownCode" << Code;
517       if (NonSymbolic &&
518           GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
519                       CurStreamType))
520         outs() << " codeid=" << Code;
521       const BitCodeAbbrev *Abbv = nullptr;
522       if (Entry.ID != bitc::UNABBREV_RECORD) {
523         Abbv = Stream.getAbbrev(Entry.ID);
524         outs() << " abbrevid=" << Entry.ID;
525       }
526
527       for (unsigned i = 0, e = Record.size(); i != e; ++i)
528         outs() << " op" << i << "=" << (int64_t)Record[i];
529
530       outs() << "/>";
531
532       if (Abbv) {
533         for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i != e; ++i) {
534           const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
535           if (!Op.isEncoding() || Op.getEncoding() != BitCodeAbbrevOp::Array)
536             continue;
537           assert(i + 2 == e && "Array op not second to last");
538           std::string Str;
539           bool ArrayIsPrintable = true;
540           for (unsigned j = i - 1, je = Record.size(); j != je; ++j) {
541             if (!isprint(static_cast<unsigned char>(Record[j]))) {
542               ArrayIsPrintable = false;
543               break;
544             }
545             Str += (char)Record[j];
546           }
547           if (ArrayIsPrintable)
548             outs() << " record string = '" << Str << "'";
549           break;
550         }
551       }
552
553       if (Blob.data()) {
554         outs() << " blob data = ";
555         if (ShowBinaryBlobs) {
556           outs() << "'";
557           outs().write_escaped(Blob, /*hex=*/true) << "'";
558         } else {
559           bool BlobIsPrintable = true;
560           for (unsigned i = 0, e = Blob.size(); i != e; ++i)
561             if (!isprint(static_cast<unsigned char>(Blob[i]))) {
562               BlobIsPrintable = false;
563               break;
564             }
565
566           if (BlobIsPrintable)
567             outs() << "'" << Blob << "'";
568           else
569             outs() << "unprintable, " << Blob.size() << " bytes.";          
570         }
571       }
572
573       outs() << "\n";
574     }
575   }
576 }
577
578 static void PrintSize(double Bits) {
579   outs() << format("%.2f/%.2fB/%luW", Bits, Bits/8,(unsigned long)(Bits/32));
580 }
581 static void PrintSize(uint64_t Bits) {
582   outs() << format("%lub/%.2fB/%luW", (unsigned long)Bits,
583                    (double)Bits/8, (unsigned long)(Bits/32));
584 }
585
586 static bool openBitcodeFile(StringRef Path,
587                             std::unique_ptr<MemoryBuffer> &MemBuf,
588                             BitstreamReader &StreamFile,
589                             BitstreamCursor &Stream,
590                             CurStreamTypeType &CurStreamType) {
591   // Read the input file.
592   ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
593       MemoryBuffer::getFileOrSTDIN(Path);
594   if (std::error_code EC = MemBufOrErr.getError())
595     return Error(Twine("Error reading '") + Path + "': " + EC.message());
596   MemBuf = std::move(MemBufOrErr.get());
597
598   if (MemBuf->getBufferSize() & 3)
599     return Error("Bitcode stream should be a multiple of 4 bytes in length");
600
601   const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
602   const unsigned char *EndBufPtr = BufPtr + MemBuf->getBufferSize();
603
604   // If we have a wrapper header, parse it and ignore the non-bc file contents.
605   // The magic number is 0x0B17C0DE stored in little endian.
606   if (isBitcodeWrapper(BufPtr, EndBufPtr))
607     if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr, true))
608       return Error("Invalid bitcode wrapper header");
609
610   StreamFile = BitstreamReader(BufPtr, EndBufPtr);
611   Stream = BitstreamCursor(StreamFile);
612   StreamFile.CollectBlockInfoNames();
613
614   // Read the stream signature.
615   char Signature[6];
616   Signature[0] = Stream.Read(8);
617   Signature[1] = Stream.Read(8);
618   Signature[2] = Stream.Read(4);
619   Signature[3] = Stream.Read(4);
620   Signature[4] = Stream.Read(4);
621   Signature[5] = Stream.Read(4);
622
623   // Autodetect the file contents, if it is one we know.
624   CurStreamType = UnknownBitstream;
625   if (Signature[0] == 'B' && Signature[1] == 'C' &&
626       Signature[2] == 0x0 && Signature[3] == 0xC &&
627       Signature[4] == 0xE && Signature[5] == 0xD)
628     CurStreamType = LLVMIRBitstream;
629
630   return false;
631 }
632
633 /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
634 static int AnalyzeBitcode() {
635   std::unique_ptr<MemoryBuffer> StreamBuffer;
636   BitstreamReader StreamFile;
637   BitstreamCursor Stream;
638   CurStreamTypeType CurStreamType;
639   if (openBitcodeFile(InputFilename, StreamBuffer, StreamFile, Stream,
640                       CurStreamType))
641     return true;
642
643   // Read block info from BlockInfoFilename, if specified.
644   // The block info must be a top-level block.
645   if (!BlockInfoFilename.empty()) {
646     std::unique_ptr<MemoryBuffer> BlockInfoBuffer;
647     BitstreamReader BlockInfoFile;
648     BitstreamCursor BlockInfoCursor;
649     CurStreamTypeType BlockInfoStreamType;
650     if (openBitcodeFile(BlockInfoFilename, BlockInfoBuffer, BlockInfoFile,
651                         BlockInfoCursor, BlockInfoStreamType))
652       return true;
653
654     while (!BlockInfoCursor.AtEndOfStream()) {
655       unsigned Code = BlockInfoCursor.ReadCode();
656       if (Code != bitc::ENTER_SUBBLOCK)
657         return Error("Invalid record at top-level in block info file");
658
659       unsigned BlockID = BlockInfoCursor.ReadSubBlockID();
660       if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
661         if (BlockInfoCursor.ReadBlockInfoBlock())
662           return Error("Malformed BlockInfoBlock in block info file");
663         break;
664       }
665
666       BlockInfoCursor.SkipBlock();
667     }
668
669     StreamFile.takeBlockInfo(std::move(BlockInfoFile));
670   }
671
672   unsigned NumTopBlocks = 0;
673
674   // Parse the top-level structure.  We only allow blocks at the top-level.
675   while (!Stream.AtEndOfStream()) {
676     unsigned Code = Stream.ReadCode();
677     if (Code != bitc::ENTER_SUBBLOCK)
678       return Error("Invalid record at top-level");
679
680     unsigned BlockID = Stream.ReadSubBlockID();
681
682     if (ParseBlock(Stream, BlockID, 0, CurStreamType))
683       return true;
684     ++NumTopBlocks;
685   }
686
687   if (Dump) outs() << "\n\n";
688
689   uint64_t BufferSizeBits = StreamFile.getBitcodeBytes().getExtent() * CHAR_BIT;
690   // Print a summary of the read file.
691   outs() << "Summary of " << InputFilename << ":\n";
692   outs() << "         Total size: ";
693   PrintSize(BufferSizeBits);
694   outs() << "\n";
695   outs() << "        Stream type: ";
696   switch (CurStreamType) {
697   case UnknownBitstream: outs() << "unknown\n"; break;
698   case LLVMIRBitstream:  outs() << "LLVM IR\n"; break;
699   }
700   outs() << "  # Toplevel Blocks: " << NumTopBlocks << "\n";
701   outs() << "\n";
702
703   // Emit per-block stats.
704   outs() << "Per-block Summary:\n";
705   for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(),
706        E = BlockIDStats.end(); I != E; ++I) {
707     outs() << "  Block ID #" << I->first;
708     if (const char *BlockName = GetBlockName(I->first, StreamFile,
709                                              CurStreamType))
710       outs() << " (" << BlockName << ")";
711     outs() << ":\n";
712
713     const PerBlockIDStats &Stats = I->second;
714     outs() << "      Num Instances: " << Stats.NumInstances << "\n";
715     outs() << "         Total Size: ";
716     PrintSize(Stats.NumBits);
717     outs() << "\n";
718     double pct = (Stats.NumBits * 100.0) / BufferSizeBits;
719     outs() << "    Percent of file: " << format("%2.4f%%", pct) << "\n";
720     if (Stats.NumInstances > 1) {
721       outs() << "       Average Size: ";
722       PrintSize(Stats.NumBits/(double)Stats.NumInstances);
723       outs() << "\n";
724       outs() << "  Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
725              << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
726       outs() << "    Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
727              << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
728       outs() << "    Tot/Avg Records: " << Stats.NumRecords << "/"
729              << Stats.NumRecords/(double)Stats.NumInstances << "\n";
730     } else {
731       outs() << "      Num SubBlocks: " << Stats.NumSubBlocks << "\n";
732       outs() << "        Num Abbrevs: " << Stats.NumAbbrevs << "\n";
733       outs() << "        Num Records: " << Stats.NumRecords << "\n";
734     }
735     if (Stats.NumRecords) {
736       double pct = (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumRecords;
737       outs() << "    Percent Abbrevs: " << format("%2.4f%%", pct) << "\n";
738     }
739     outs() << "\n";
740
741     // Print a histogram of the codes we see.
742     if (!NoHistogram && !Stats.CodeFreq.empty()) {
743       std::vector<std::pair<unsigned, unsigned> > FreqPairs;  // <freq,code>
744       for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
745         if (unsigned Freq = Stats.CodeFreq[i].NumInstances)
746           FreqPairs.push_back(std::make_pair(Freq, i));
747       std::stable_sort(FreqPairs.begin(), FreqPairs.end());
748       std::reverse(FreqPairs.begin(), FreqPairs.end());
749
750       outs() << "\tRecord Histogram:\n";
751       outs() << "\t\t  Count    # Bits   %% Abv  Record Kind\n";
752       for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
753         const PerRecordStats &RecStats = Stats.CodeFreq[FreqPairs[i].second];
754
755         outs() << format("\t\t%7d %9lu",
756                          RecStats.NumInstances,
757                          (unsigned long)RecStats.TotalBits);
758
759         if (RecStats.NumAbbrev)
760           outs() <<
761               format("%7.2f  ",
762                      (double)RecStats.NumAbbrev/RecStats.NumInstances*100);
763         else
764           outs() << "         ";
765
766         if (const char *CodeName =
767               GetCodeName(FreqPairs[i].second, I->first, StreamFile,
768                           CurStreamType))
769           outs() << CodeName << "\n";
770         else
771           outs() << "UnknownCode" << FreqPairs[i].second << "\n";
772       }
773       outs() << "\n";
774
775     }
776   }
777   return 0;
778 }
779
780
781 int main(int argc, char **argv) {
782   // Print a stack trace if we signal out.
783   sys::PrintStackTraceOnErrorSignal();
784   PrettyStackTraceProgram X(argc, argv);
785   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
786   cl::ParseCommandLineOptions(argc, argv, "llvm-bcanalyzer file analyzer\n");
787
788   return AnalyzeBitcode();
789 }