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