Bitcode: Add `OLD_` prefix to metadata node records
[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/Bitcode/LLVMBitCodes.h"
32 #include "llvm/Bitcode/ReaderWriter.h"
33 #include "llvm/IR/Verifier.h"
34 #include "llvm/ADT/Optional.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/ManagedStatic.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/PrettyStackTrace.h"
40 #include "llvm/Support/Signals.h"
41 #include "llvm/Support/raw_ostream.h"
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 namespace {
70
71 /// CurStreamTypeType - A type for CurStreamType
72 enum CurStreamTypeType {
73   UnknownBitstream,
74   LLVMIRBitstream
75 };
76
77 }
78
79 /// GetBlockName - Return a symbolic block name if known, otherwise return
80 /// null.
81 static const char *GetBlockName(unsigned BlockID,
82                                 const BitstreamReader &StreamFile,
83                                 CurStreamTypeType CurStreamType) {
84   // Standard blocks for all bitcode files.
85   if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
86     if (BlockID == bitc::BLOCKINFO_BLOCK_ID)
87       return "BLOCKINFO_BLOCK";
88     return nullptr;
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 nullptr;
100
101   switch (BlockID) {
102   default:                             return nullptr;
103   case bitc::MODULE_BLOCK_ID:          return "MODULE_BLOCK";
104   case bitc::PARAMATTR_BLOCK_ID:       return "PARAMATTR_BLOCK";
105   case bitc::PARAMATTR_GROUP_BLOCK_ID: return "PARAMATTR_GROUP_BLOCK_ID";
106   case bitc::TYPE_BLOCK_ID_NEW:        return "TYPE_BLOCK_ID";
107   case bitc::CONSTANTS_BLOCK_ID:       return "CONSTANTS_BLOCK";
108   case bitc::FUNCTION_BLOCK_ID:        return "FUNCTION_BLOCK";
109   case bitc::VALUE_SYMTAB_BLOCK_ID:    return "VALUE_SYMTAB";
110   case bitc::METADATA_BLOCK_ID:        return "METADATA_BLOCK";
111   case bitc::METADATA_ATTACHMENT_ID:   return "METADATA_ATTACHMENT_BLOCK";
112   case bitc::USELIST_BLOCK_ID:         return "USELIST_BLOCK_ID";
113   }
114 }
115
116 /// GetCodeName - Return a symbolic code name if known, otherwise return
117 /// null.
118 static const char *GetCodeName(unsigned CodeID, unsigned BlockID,
119                                const BitstreamReader &StreamFile,
120                                CurStreamTypeType CurStreamType) {
121   // Standard blocks for all bitcode files.
122   if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
123     if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
124       switch (CodeID) {
125       default: return nullptr;
126       case bitc::BLOCKINFO_CODE_SETBID:        return "SETBID";
127       case bitc::BLOCKINFO_CODE_BLOCKNAME:     return "BLOCKNAME";
128       case bitc::BLOCKINFO_CODE_SETRECORDNAME: return "SETRECORDNAME";
129       }
130     }
131     return nullptr;
132   }
133
134   // Check to see if we have a blockinfo record for this record, with a name.
135   if (const BitstreamReader::BlockInfo *Info =
136         StreamFile.getBlockInfo(BlockID)) {
137     for (unsigned i = 0, e = Info->RecordNames.size(); i != e; ++i)
138       if (Info->RecordNames[i].first == CodeID)
139         return Info->RecordNames[i].second.c_str();
140   }
141
142
143   if (CurStreamType != LLVMIRBitstream) return nullptr;
144
145   switch (BlockID) {
146   default: return nullptr;
147   case bitc::MODULE_BLOCK_ID:
148     switch (CodeID) {
149     default: return nullptr;
150     case bitc::MODULE_CODE_VERSION:     return "VERSION";
151     case bitc::MODULE_CODE_TRIPLE:      return "TRIPLE";
152     case bitc::MODULE_CODE_DATALAYOUT:  return "DATALAYOUT";
153     case bitc::MODULE_CODE_ASM:         return "ASM";
154     case bitc::MODULE_CODE_SECTIONNAME: return "SECTIONNAME";
155     case bitc::MODULE_CODE_DEPLIB:      return "DEPLIB"; // FIXME: Remove in 4.0
156     case bitc::MODULE_CODE_GLOBALVAR:   return "GLOBALVAR";
157     case bitc::MODULE_CODE_FUNCTION:    return "FUNCTION";
158     case bitc::MODULE_CODE_ALIAS:       return "ALIAS";
159     case bitc::MODULE_CODE_PURGEVALS:   return "PURGEVALS";
160     case bitc::MODULE_CODE_GCNAME:      return "GCNAME";
161     }
162   case bitc::PARAMATTR_BLOCK_ID:
163     switch (CodeID) {
164     default: return nullptr;
165     case bitc::PARAMATTR_CODE_ENTRY_OLD: return "ENTRY";
166     case bitc::PARAMATTR_CODE_ENTRY:     return "ENTRY";
167     case bitc::PARAMATTR_GRP_CODE_ENTRY: return "ENTRY";
168     }
169   case bitc::TYPE_BLOCK_ID_NEW:
170     switch (CodeID) {
171     default: return nullptr;
172     case bitc::TYPE_CODE_NUMENTRY:     return "NUMENTRY";
173     case bitc::TYPE_CODE_VOID:         return "VOID";
174     case bitc::TYPE_CODE_FLOAT:        return "FLOAT";
175     case bitc::TYPE_CODE_DOUBLE:       return "DOUBLE";
176     case bitc::TYPE_CODE_LABEL:        return "LABEL";
177     case bitc::TYPE_CODE_OPAQUE:       return "OPAQUE";
178     case bitc::TYPE_CODE_INTEGER:      return "INTEGER";
179     case bitc::TYPE_CODE_POINTER:      return "POINTER";
180     case bitc::TYPE_CODE_ARRAY:        return "ARRAY";
181     case bitc::TYPE_CODE_VECTOR:       return "VECTOR";
182     case bitc::TYPE_CODE_X86_FP80:     return "X86_FP80";
183     case bitc::TYPE_CODE_FP128:        return "FP128";
184     case bitc::TYPE_CODE_PPC_FP128:    return "PPC_FP128";
185     case bitc::TYPE_CODE_METADATA:     return "METADATA";
186     case bitc::TYPE_CODE_STRUCT_ANON:  return "STRUCT_ANON";
187     case bitc::TYPE_CODE_STRUCT_NAME:  return "STRUCT_NAME";
188     case bitc::TYPE_CODE_STRUCT_NAMED: return "STRUCT_NAMED";
189     case bitc::TYPE_CODE_FUNCTION:     return "FUNCTION";
190     }
191
192   case bitc::CONSTANTS_BLOCK_ID:
193     switch (CodeID) {
194     default: return nullptr;
195     case bitc::CST_CODE_SETTYPE:         return "SETTYPE";
196     case bitc::CST_CODE_NULL:            return "NULL";
197     case bitc::CST_CODE_UNDEF:           return "UNDEF";
198     case bitc::CST_CODE_INTEGER:         return "INTEGER";
199     case bitc::CST_CODE_WIDE_INTEGER:    return "WIDE_INTEGER";
200     case bitc::CST_CODE_FLOAT:           return "FLOAT";
201     case bitc::CST_CODE_AGGREGATE:       return "AGGREGATE";
202     case bitc::CST_CODE_STRING:          return "STRING";
203     case bitc::CST_CODE_CSTRING:         return "CSTRING";
204     case bitc::CST_CODE_CE_BINOP:        return "CE_BINOP";
205     case bitc::CST_CODE_CE_CAST:         return "CE_CAST";
206     case bitc::CST_CODE_CE_GEP:          return "CE_GEP";
207     case bitc::CST_CODE_CE_INBOUNDS_GEP: return "CE_INBOUNDS_GEP";
208     case bitc::CST_CODE_CE_SELECT:       return "CE_SELECT";
209     case bitc::CST_CODE_CE_EXTRACTELT:   return "CE_EXTRACTELT";
210     case bitc::CST_CODE_CE_INSERTELT:    return "CE_INSERTELT";
211     case bitc::CST_CODE_CE_SHUFFLEVEC:   return "CE_SHUFFLEVEC";
212     case bitc::CST_CODE_CE_CMP:          return "CE_CMP";
213     case bitc::CST_CODE_INLINEASM:       return "INLINEASM";
214     case bitc::CST_CODE_CE_SHUFVEC_EX:   return "CE_SHUFVEC_EX";
215     case bitc::CST_CODE_BLOCKADDRESS:    return "CST_CODE_BLOCKADDRESS";
216     case bitc::CST_CODE_DATA:            return "DATA";
217     }
218   case bitc::FUNCTION_BLOCK_ID:
219     switch (CodeID) {
220     default: return nullptr;
221     case bitc::FUNC_CODE_DECLAREBLOCKS: return "DECLAREBLOCKS";
222
223     case bitc::FUNC_CODE_INST_BINOP:        return "INST_BINOP";
224     case bitc::FUNC_CODE_INST_CAST:         return "INST_CAST";
225     case bitc::FUNC_CODE_INST_GEP:          return "INST_GEP";
226     case bitc::FUNC_CODE_INST_INBOUNDS_GEP: return "INST_INBOUNDS_GEP";
227     case bitc::FUNC_CODE_INST_SELECT:       return "INST_SELECT";
228     case bitc::FUNC_CODE_INST_EXTRACTELT:   return "INST_EXTRACTELT";
229     case bitc::FUNC_CODE_INST_INSERTELT:    return "INST_INSERTELT";
230     case bitc::FUNC_CODE_INST_SHUFFLEVEC:   return "INST_SHUFFLEVEC";
231     case bitc::FUNC_CODE_INST_CMP:          return "INST_CMP";
232
233     case bitc::FUNC_CODE_INST_RET:          return "INST_RET";
234     case bitc::FUNC_CODE_INST_BR:           return "INST_BR";
235     case bitc::FUNC_CODE_INST_SWITCH:       return "INST_SWITCH";
236     case bitc::FUNC_CODE_INST_INVOKE:       return "INST_INVOKE";
237     case bitc::FUNC_CODE_INST_UNREACHABLE:  return "INST_UNREACHABLE";
238
239     case bitc::FUNC_CODE_INST_PHI:          return "INST_PHI";
240     case bitc::FUNC_CODE_INST_ALLOCA:       return "INST_ALLOCA";
241     case bitc::FUNC_CODE_INST_LOAD:         return "INST_LOAD";
242     case bitc::FUNC_CODE_INST_VAARG:        return "INST_VAARG";
243     case bitc::FUNC_CODE_INST_STORE:        return "INST_STORE";
244     case bitc::FUNC_CODE_INST_EXTRACTVAL:   return "INST_EXTRACTVAL";
245     case bitc::FUNC_CODE_INST_INSERTVAL:    return "INST_INSERTVAL";
246     case bitc::FUNC_CODE_INST_CMP2:         return "INST_CMP2";
247     case bitc::FUNC_CODE_INST_VSELECT:      return "INST_VSELECT";
248     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:   return "DEBUG_LOC_AGAIN";
249     case bitc::FUNC_CODE_INST_CALL:         return "INST_CALL";
250     case bitc::FUNC_CODE_DEBUG_LOC:         return "DEBUG_LOC";
251     }
252   case bitc::VALUE_SYMTAB_BLOCK_ID:
253     switch (CodeID) {
254     default: return nullptr;
255     case bitc::VST_CODE_ENTRY: return "ENTRY";
256     case bitc::VST_CODE_BBENTRY: return "BBENTRY";
257     }
258   case bitc::METADATA_ATTACHMENT_ID:
259     switch(CodeID) {
260     default:return nullptr;
261     case bitc::METADATA_ATTACHMENT: return "METADATA_ATTACHMENT";
262     }
263   case bitc::METADATA_BLOCK_ID:
264     switch(CodeID) {
265     default:return nullptr;
266     case bitc::METADATA_STRING:      return "METADATA_STRING";
267     case bitc::METADATA_NAME:        return "METADATA_NAME";
268     case bitc::METADATA_KIND:        return "METADATA_KIND";
269     case bitc::METADATA_OLD_NODE:    return "METADATA_OLD_NODE";
270     case bitc::METADATA_OLD_FN_NODE: return "METADATA_OLD_FN_NODE";
271     case bitc::METADATA_NAMED_NODE:  return "METADATA_NAMED_NODE";
272     }
273   case bitc::USELIST_BLOCK_ID:
274     switch(CodeID) {
275     default:return nullptr;
276     case bitc::USELIST_CODE_DEFAULT: return "USELIST_CODE_DEFAULT";
277     case bitc::USELIST_CODE_BB:      return "USELIST_CODE_BB";
278     }
279   }
280 }
281
282 struct PerRecordStats {
283   unsigned NumInstances;
284   unsigned NumAbbrev;
285   uint64_t TotalBits;
286
287   PerRecordStats() : NumInstances(0), NumAbbrev(0), TotalBits(0) {}
288 };
289
290 struct PerBlockIDStats {
291   /// NumInstances - This the number of times this block ID has been seen.
292   unsigned NumInstances;
293
294   /// NumBits - The total size in bits of all of these blocks.
295   uint64_t NumBits;
296
297   /// NumSubBlocks - The total number of blocks these blocks contain.
298   unsigned NumSubBlocks;
299
300   /// NumAbbrevs - The total number of abbreviations.
301   unsigned NumAbbrevs;
302
303   /// NumRecords - The total number of records these blocks contain, and the
304   /// number that are abbreviated.
305   unsigned NumRecords, NumAbbreviatedRecords;
306
307   /// CodeFreq - Keep track of the number of times we see each code.
308   std::vector<PerRecordStats> CodeFreq;
309
310   PerBlockIDStats()
311     : NumInstances(0), NumBits(0),
312       NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {}
313 };
314
315 static std::map<unsigned, PerBlockIDStats> BlockIDStats;
316
317
318
319 /// Error - All bitcode analysis errors go through this function, making this a
320 /// good place to breakpoint if debugging.
321 static bool Error(const Twine &Err) {
322   errs() << Err << "\n";
323   return true;
324 }
325
326 /// ParseBlock - Read a block, updating statistics, etc.
327 static bool ParseBlock(BitstreamCursor &Stream, unsigned BlockID,
328                        unsigned IndentLevel, CurStreamTypeType CurStreamType) {
329   std::string Indent(IndentLevel*2, ' ');
330   uint64_t BlockBitStart = Stream.GetCurrentBitNo();
331
332   // Get the statistics for this BlockID.
333   PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
334
335   BlockStats.NumInstances++;
336
337   // BLOCKINFO is a special part of the stream.
338   if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
339     if (Dump) outs() << Indent << "<BLOCKINFO_BLOCK/>\n";
340     if (Stream.ReadBlockInfoBlock())
341       return Error("Malformed BlockInfoBlock");
342     uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
343     BlockStats.NumBits += BlockBitEnd-BlockBitStart;
344     return false;
345   }
346
347   unsigned NumWords = 0;
348   if (Stream.EnterSubBlock(BlockID, &NumWords))
349     return Error("Malformed block record");
350
351   const char *BlockName = nullptr;
352   if (Dump) {
353     outs() << Indent << "<";
354     if ((BlockName = GetBlockName(BlockID, *Stream.getBitStreamReader(),
355                                   CurStreamType)))
356       outs() << BlockName;
357     else
358       outs() << "UnknownBlock" << BlockID;
359
360     if (NonSymbolic && BlockName)
361       outs() << " BlockID=" << BlockID;
362
363     outs() << " NumWords=" << NumWords
364            << " BlockCodeSize=" << Stream.getAbbrevIDWidth() << ">\n";
365   }
366
367   SmallVector<uint64_t, 64> Record;
368
369   // Read all the records for this block.
370   while (1) {
371     if (Stream.AtEndOfStream())
372       return Error("Premature end of bitstream");
373
374     uint64_t RecordStartBit = Stream.GetCurrentBitNo();
375
376     BitstreamEntry Entry =
377       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
378     
379     switch (Entry.Kind) {
380     case BitstreamEntry::Error:
381       return Error("malformed bitcode file");
382     case BitstreamEntry::EndBlock: {
383       uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
384       BlockStats.NumBits += BlockBitEnd-BlockBitStart;
385       if (Dump) {
386         outs() << Indent << "</";
387         if (BlockName)
388           outs() << BlockName << ">\n";
389         else
390           outs() << "UnknownBlock" << BlockID << ">\n";
391       }
392       return false;
393     }
394         
395     case BitstreamEntry::SubBlock: {
396       uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
397       if (ParseBlock(Stream, Entry.ID, IndentLevel+1, CurStreamType))
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       continue;
405     }
406     case BitstreamEntry::Record:
407       // The interesting case.
408       break;
409     }
410
411     if (Entry.ID == bitc::DEFINE_ABBREV) {
412       Stream.ReadAbbrevRecord();
413       ++BlockStats.NumAbbrevs;
414       continue;
415     }
416     
417     Record.clear();
418
419     ++BlockStats.NumRecords;
420
421     StringRef Blob;
422     unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
423
424     // Increment the # occurrences of this code.
425     if (BlockStats.CodeFreq.size() <= Code)
426       BlockStats.CodeFreq.resize(Code+1);
427     BlockStats.CodeFreq[Code].NumInstances++;
428     BlockStats.CodeFreq[Code].TotalBits +=
429       Stream.GetCurrentBitNo()-RecordStartBit;
430     if (Entry.ID != bitc::UNABBREV_RECORD) {
431       BlockStats.CodeFreq[Code].NumAbbrev++;
432       ++BlockStats.NumAbbreviatedRecords;
433     }
434
435     if (Dump) {
436       outs() << Indent << "  <";
437       if (const char *CodeName =
438             GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
439                         CurStreamType))
440         outs() << CodeName;
441       else
442         outs() << "UnknownCode" << Code;
443       if (NonSymbolic &&
444           GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
445                       CurStreamType))
446         outs() << " codeid=" << Code;
447       if (Entry.ID != bitc::UNABBREV_RECORD)
448         outs() << " abbrevid=" << Entry.ID;
449
450       for (unsigned i = 0, e = Record.size(); i != e; ++i)
451         outs() << " op" << i << "=" << (int64_t)Record[i];
452
453       outs() << "/>";
454
455       if (Blob.data()) {
456         outs() << " blob data = ";
457         bool BlobIsPrintable = true;
458         for (unsigned i = 0, e = Blob.size(); i != e; ++i)
459           if (!isprint(static_cast<unsigned char>(Blob[i]))) {
460             BlobIsPrintable = false;
461             break;
462           }
463
464         if (BlobIsPrintable)
465           outs() << "'" << Blob << "'";
466         else
467           outs() << "unprintable, " << Blob.size() << " bytes.";
468       }
469
470       outs() << "\n";
471     }
472   }
473 }
474
475 static void PrintSize(double Bits) {
476   outs() << format("%.2f/%.2fB/%luW", Bits, Bits/8,(unsigned long)(Bits/32));
477 }
478 static void PrintSize(uint64_t Bits) {
479   outs() << format("%lub/%.2fB/%luW", (unsigned long)Bits,
480                    (double)Bits/8, (unsigned long)(Bits/32));
481 }
482
483 static bool openBitcodeFile(StringRef Path,
484                             std::unique_ptr<MemoryBuffer> &MemBuf,
485                             BitstreamReader &StreamFile,
486                             BitstreamCursor &Stream,
487                             CurStreamTypeType &CurStreamType) {
488   // Read the input file.
489   ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
490       MemoryBuffer::getFileOrSTDIN(Path);
491   if (std::error_code EC = MemBufOrErr.getError())
492     return Error(Twine("Error reading '") + Path + "': " + EC.message());
493   MemBuf = std::move(MemBufOrErr.get());
494
495   if (MemBuf->getBufferSize() & 3)
496     return Error("Bitcode stream should be a multiple of 4 bytes in length");
497
498   const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
499   const unsigned char *EndBufPtr = BufPtr + MemBuf->getBufferSize();
500
501   // If we have a wrapper header, parse it and ignore the non-bc file contents.
502   // The magic number is 0x0B17C0DE stored in little endian.
503   if (isBitcodeWrapper(BufPtr, EndBufPtr))
504     if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr, true))
505       return Error("Invalid bitcode wrapper header");
506
507   StreamFile = BitstreamReader(BufPtr, EndBufPtr);
508   Stream = BitstreamCursor(StreamFile);
509   StreamFile.CollectBlockInfoNames();
510
511   // Read the stream signature.
512   char Signature[6];
513   Signature[0] = Stream.Read(8);
514   Signature[1] = Stream.Read(8);
515   Signature[2] = Stream.Read(4);
516   Signature[3] = Stream.Read(4);
517   Signature[4] = Stream.Read(4);
518   Signature[5] = Stream.Read(4);
519
520   // Autodetect the file contents, if it is one we know.
521   CurStreamType = UnknownBitstream;
522   if (Signature[0] == 'B' && Signature[1] == 'C' &&
523       Signature[2] == 0x0 && Signature[3] == 0xC &&
524       Signature[4] == 0xE && Signature[5] == 0xD)
525     CurStreamType = LLVMIRBitstream;
526
527   return false;
528 }
529
530 /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
531 static int AnalyzeBitcode() {
532   std::unique_ptr<MemoryBuffer> StreamBuffer;
533   BitstreamReader StreamFile;
534   BitstreamCursor Stream;
535   CurStreamTypeType CurStreamType;
536   if (openBitcodeFile(InputFilename, StreamBuffer, StreamFile, Stream,
537                       CurStreamType))
538     return true;
539
540   // Read block info from BlockInfoFilename, if specified.
541   // The block info must be a top-level block.
542   if (!BlockInfoFilename.empty()) {
543     std::unique_ptr<MemoryBuffer> BlockInfoBuffer;
544     BitstreamReader BlockInfoFile;
545     BitstreamCursor BlockInfoCursor;
546     CurStreamTypeType BlockInfoStreamType;
547     if (openBitcodeFile(BlockInfoFilename, BlockInfoBuffer, BlockInfoFile,
548                         BlockInfoCursor, BlockInfoStreamType))
549       return true;
550
551     while (!BlockInfoCursor.AtEndOfStream()) {
552       unsigned Code = BlockInfoCursor.ReadCode();
553       if (Code != bitc::ENTER_SUBBLOCK)
554         return Error("Invalid record at top-level in block info file");
555
556       unsigned BlockID = BlockInfoCursor.ReadSubBlockID();
557       if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
558         if (BlockInfoCursor.ReadBlockInfoBlock())
559           return Error("Malformed BlockInfoBlock in block info file");
560         break;
561       }
562
563       BlockInfoCursor.SkipBlock();
564     }
565
566     StreamFile.takeBlockInfo(std::move(BlockInfoFile));
567   }
568
569   unsigned NumTopBlocks = 0;
570
571   // Parse the top-level structure.  We only allow blocks at the top-level.
572   while (!Stream.AtEndOfStream()) {
573     unsigned Code = Stream.ReadCode();
574     if (Code != bitc::ENTER_SUBBLOCK)
575       return Error("Invalid record at top-level");
576
577     unsigned BlockID = Stream.ReadSubBlockID();
578
579     if (ParseBlock(Stream, BlockID, 0, CurStreamType))
580       return true;
581     ++NumTopBlocks;
582   }
583
584   if (Dump) outs() << "\n\n";
585
586   uint64_t BufferSizeBits = StreamFile.getBitcodeBytes().getExtent() * CHAR_BIT;
587   // Print a summary of the read file.
588   outs() << "Summary of " << InputFilename << ":\n";
589   outs() << "         Total size: ";
590   PrintSize(BufferSizeBits);
591   outs() << "\n";
592   outs() << "        Stream type: ";
593   switch (CurStreamType) {
594   case UnknownBitstream: outs() << "unknown\n"; break;
595   case LLVMIRBitstream:  outs() << "LLVM IR\n"; break;
596   }
597   outs() << "  # Toplevel Blocks: " << NumTopBlocks << "\n";
598   outs() << "\n";
599
600   // Emit per-block stats.
601   outs() << "Per-block Summary:\n";
602   for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(),
603        E = BlockIDStats.end(); I != E; ++I) {
604     outs() << "  Block ID #" << I->first;
605     if (const char *BlockName = GetBlockName(I->first, StreamFile,
606                                              CurStreamType))
607       outs() << " (" << BlockName << ")";
608     outs() << ":\n";
609
610     const PerBlockIDStats &Stats = I->second;
611     outs() << "      Num Instances: " << Stats.NumInstances << "\n";
612     outs() << "         Total Size: ";
613     PrintSize(Stats.NumBits);
614     outs() << "\n";
615     double pct = (Stats.NumBits * 100.0) / BufferSizeBits;
616     outs() << "    Percent of file: " << format("%2.4f%%", pct) << "\n";
617     if (Stats.NumInstances > 1) {
618       outs() << "       Average Size: ";
619       PrintSize(Stats.NumBits/(double)Stats.NumInstances);
620       outs() << "\n";
621       outs() << "  Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
622              << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
623       outs() << "    Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
624              << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
625       outs() << "    Tot/Avg Records: " << Stats.NumRecords << "/"
626              << Stats.NumRecords/(double)Stats.NumInstances << "\n";
627     } else {
628       outs() << "      Num SubBlocks: " << Stats.NumSubBlocks << "\n";
629       outs() << "        Num Abbrevs: " << Stats.NumAbbrevs << "\n";
630       outs() << "        Num Records: " << Stats.NumRecords << "\n";
631     }
632     if (Stats.NumRecords) {
633       double pct = (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumRecords;
634       outs() << "    Percent Abbrevs: " << format("%2.4f%%", pct) << "\n";
635     }
636     outs() << "\n";
637
638     // Print a histogram of the codes we see.
639     if (!NoHistogram && !Stats.CodeFreq.empty()) {
640       std::vector<std::pair<unsigned, unsigned> > FreqPairs;  // <freq,code>
641       for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
642         if (unsigned Freq = Stats.CodeFreq[i].NumInstances)
643           FreqPairs.push_back(std::make_pair(Freq, i));
644       std::stable_sort(FreqPairs.begin(), FreqPairs.end());
645       std::reverse(FreqPairs.begin(), FreqPairs.end());
646
647       outs() << "\tRecord Histogram:\n";
648       outs() << "\t\t  Count    # Bits   %% Abv  Record Kind\n";
649       for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
650         const PerRecordStats &RecStats = Stats.CodeFreq[FreqPairs[i].second];
651
652         outs() << format("\t\t%7d %9lu",
653                          RecStats.NumInstances,
654                          (unsigned long)RecStats.TotalBits);
655
656         if (RecStats.NumAbbrev)
657           outs() <<
658               format("%7.2f  ",
659                      (double)RecStats.NumAbbrev/RecStats.NumInstances*100);
660         else
661           outs() << "         ";
662
663         if (const char *CodeName =
664               GetCodeName(FreqPairs[i].second, I->first, StreamFile,
665                           CurStreamType))
666           outs() << CodeName << "\n";
667         else
668           outs() << "UnknownCode" << FreqPairs[i].second << "\n";
669       }
670       outs() << "\n";
671
672     }
673   }
674   return 0;
675 }
676
677
678 int main(int argc, char **argv) {
679   // Print a stack trace if we signal out.
680   sys::PrintStackTraceOnErrorSignal();
681   PrettyStackTraceProgram X(argc, argv);
682   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
683   cl::ParseCommandLineOptions(argc, argv, "llvm-bcanalyzer file analyzer\n");
684
685   return AnalyzeBitcode();
686 }