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