Bitcode: Move the DEBUG_LOC record to DEBUG_LOC_OLD
[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_OLD:     return "DEBUG_LOC_OLD";
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_NODE:        return "METADATA_NODE";
270     case bitc::METADATA_VALUE:       return "METADATA_VALUE";
271     case bitc::METADATA_OLD_NODE:    return "METADATA_OLD_NODE";
272     case bitc::METADATA_OLD_FN_NODE: return "METADATA_OLD_FN_NODE";
273     case bitc::METADATA_NAMED_NODE:  return "METADATA_NAMED_NODE";
274     }
275   case bitc::USELIST_BLOCK_ID:
276     switch(CodeID) {
277     default:return nullptr;
278     case bitc::USELIST_CODE_DEFAULT: return "USELIST_CODE_DEFAULT";
279     case bitc::USELIST_CODE_BB:      return "USELIST_CODE_BB";
280     }
281   }
282 }
283
284 struct PerRecordStats {
285   unsigned NumInstances;
286   unsigned NumAbbrev;
287   uint64_t TotalBits;
288
289   PerRecordStats() : NumInstances(0), NumAbbrev(0), TotalBits(0) {}
290 };
291
292 struct PerBlockIDStats {
293   /// NumInstances - This the number of times this block ID has been seen.
294   unsigned NumInstances;
295
296   /// NumBits - The total size in bits of all of these blocks.
297   uint64_t NumBits;
298
299   /// NumSubBlocks - The total number of blocks these blocks contain.
300   unsigned NumSubBlocks;
301
302   /// NumAbbrevs - The total number of abbreviations.
303   unsigned NumAbbrevs;
304
305   /// NumRecords - The total number of records these blocks contain, and the
306   /// number that are abbreviated.
307   unsigned NumRecords, NumAbbreviatedRecords;
308
309   /// CodeFreq - Keep track of the number of times we see each code.
310   std::vector<PerRecordStats> CodeFreq;
311
312   PerBlockIDStats()
313     : NumInstances(0), NumBits(0),
314       NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {}
315 };
316
317 static std::map<unsigned, PerBlockIDStats> BlockIDStats;
318
319
320
321 /// Error - All bitcode analysis errors go through this function, making this a
322 /// good place to breakpoint if debugging.
323 static bool Error(const Twine &Err) {
324   errs() << Err << "\n";
325   return true;
326 }
327
328 /// ParseBlock - Read a block, updating statistics, etc.
329 static bool ParseBlock(BitstreamCursor &Stream, unsigned BlockID,
330                        unsigned IndentLevel, CurStreamTypeType CurStreamType) {
331   std::string Indent(IndentLevel*2, ' ');
332   uint64_t BlockBitStart = Stream.GetCurrentBitNo();
333
334   // Get the statistics for this BlockID.
335   PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
336
337   BlockStats.NumInstances++;
338
339   // BLOCKINFO is a special part of the stream.
340   if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
341     if (Dump) outs() << Indent << "<BLOCKINFO_BLOCK/>\n";
342     if (Stream.ReadBlockInfoBlock())
343       return Error("Malformed BlockInfoBlock");
344     uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
345     BlockStats.NumBits += BlockBitEnd-BlockBitStart;
346     return false;
347   }
348
349   unsigned NumWords = 0;
350   if (Stream.EnterSubBlock(BlockID, &NumWords))
351     return Error("Malformed block record");
352
353   const char *BlockName = nullptr;
354   if (Dump) {
355     outs() << Indent << "<";
356     if ((BlockName = GetBlockName(BlockID, *Stream.getBitStreamReader(),
357                                   CurStreamType)))
358       outs() << BlockName;
359     else
360       outs() << "UnknownBlock" << BlockID;
361
362     if (NonSymbolic && BlockName)
363       outs() << " BlockID=" << BlockID;
364
365     outs() << " NumWords=" << NumWords
366            << " BlockCodeSize=" << Stream.getAbbrevIDWidth() << ">\n";
367   }
368
369   SmallVector<uint64_t, 64> Record;
370
371   // Read all the records for this block.
372   while (1) {
373     if (Stream.AtEndOfStream())
374       return Error("Premature end of bitstream");
375
376     uint64_t RecordStartBit = Stream.GetCurrentBitNo();
377
378     BitstreamEntry Entry =
379       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
380     
381     switch (Entry.Kind) {
382     case BitstreamEntry::Error:
383       return Error("malformed bitcode file");
384     case BitstreamEntry::EndBlock: {
385       uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
386       BlockStats.NumBits += BlockBitEnd-BlockBitStart;
387       if (Dump) {
388         outs() << Indent << "</";
389         if (BlockName)
390           outs() << BlockName << ">\n";
391         else
392           outs() << "UnknownBlock" << BlockID << ">\n";
393       }
394       return false;
395     }
396         
397     case BitstreamEntry::SubBlock: {
398       uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
399       if (ParseBlock(Stream, Entry.ID, IndentLevel+1, CurStreamType))
400         return true;
401       ++BlockStats.NumSubBlocks;
402       uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
403       
404       // Don't include subblock sizes in the size of this block.
405       BlockBitStart += SubBlockBitEnd-SubBlockBitStart;
406       continue;
407     }
408     case BitstreamEntry::Record:
409       // The interesting case.
410       break;
411     }
412
413     if (Entry.ID == bitc::DEFINE_ABBREV) {
414       Stream.ReadAbbrevRecord();
415       ++BlockStats.NumAbbrevs;
416       continue;
417     }
418     
419     Record.clear();
420
421     ++BlockStats.NumRecords;
422
423     StringRef Blob;
424     unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
425
426     // Increment the # occurrences of this code.
427     if (BlockStats.CodeFreq.size() <= Code)
428       BlockStats.CodeFreq.resize(Code+1);
429     BlockStats.CodeFreq[Code].NumInstances++;
430     BlockStats.CodeFreq[Code].TotalBits +=
431       Stream.GetCurrentBitNo()-RecordStartBit;
432     if (Entry.ID != bitc::UNABBREV_RECORD) {
433       BlockStats.CodeFreq[Code].NumAbbrev++;
434       ++BlockStats.NumAbbreviatedRecords;
435     }
436
437     if (Dump) {
438       outs() << Indent << "  <";
439       if (const char *CodeName =
440             GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
441                         CurStreamType))
442         outs() << CodeName;
443       else
444         outs() << "UnknownCode" << Code;
445       if (NonSymbolic &&
446           GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
447                       CurStreamType))
448         outs() << " codeid=" << Code;
449       if (Entry.ID != bitc::UNABBREV_RECORD)
450         outs() << " abbrevid=" << Entry.ID;
451
452       for (unsigned i = 0, e = Record.size(); i != e; ++i)
453         outs() << " op" << i << "=" << (int64_t)Record[i];
454
455       outs() << "/>";
456
457       if (Blob.data()) {
458         outs() << " blob data = ";
459         bool BlobIsPrintable = true;
460         for (unsigned i = 0, e = Blob.size(); i != e; ++i)
461           if (!isprint(static_cast<unsigned char>(Blob[i]))) {
462             BlobIsPrintable = false;
463             break;
464           }
465
466         if (BlobIsPrintable)
467           outs() << "'" << Blob << "'";
468         else
469           outs() << "unprintable, " << Blob.size() << " bytes.";
470       }
471
472       outs() << "\n";
473     }
474   }
475 }
476
477 static void PrintSize(double Bits) {
478   outs() << format("%.2f/%.2fB/%luW", Bits, Bits/8,(unsigned long)(Bits/32));
479 }
480 static void PrintSize(uint64_t Bits) {
481   outs() << format("%lub/%.2fB/%luW", (unsigned long)Bits,
482                    (double)Bits/8, (unsigned long)(Bits/32));
483 }
484
485 static bool openBitcodeFile(StringRef Path,
486                             std::unique_ptr<MemoryBuffer> &MemBuf,
487                             BitstreamReader &StreamFile,
488                             BitstreamCursor &Stream,
489                             CurStreamTypeType &CurStreamType) {
490   // Read the input file.
491   ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
492       MemoryBuffer::getFileOrSTDIN(Path);
493   if (std::error_code EC = MemBufOrErr.getError())
494     return Error(Twine("Error reading '") + Path + "': " + EC.message());
495   MemBuf = std::move(MemBufOrErr.get());
496
497   if (MemBuf->getBufferSize() & 3)
498     return Error("Bitcode stream should be a multiple of 4 bytes in length");
499
500   const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
501   const unsigned char *EndBufPtr = BufPtr + MemBuf->getBufferSize();
502
503   // If we have a wrapper header, parse it and ignore the non-bc file contents.
504   // The magic number is 0x0B17C0DE stored in little endian.
505   if (isBitcodeWrapper(BufPtr, EndBufPtr))
506     if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr, true))
507       return Error("Invalid bitcode wrapper header");
508
509   StreamFile = BitstreamReader(BufPtr, EndBufPtr);
510   Stream = BitstreamCursor(StreamFile);
511   StreamFile.CollectBlockInfoNames();
512
513   // Read the stream signature.
514   char Signature[6];
515   Signature[0] = Stream.Read(8);
516   Signature[1] = Stream.Read(8);
517   Signature[2] = Stream.Read(4);
518   Signature[3] = Stream.Read(4);
519   Signature[4] = Stream.Read(4);
520   Signature[5] = Stream.Read(4);
521
522   // Autodetect the file contents, if it is one we know.
523   CurStreamType = UnknownBitstream;
524   if (Signature[0] == 'B' && Signature[1] == 'C' &&
525       Signature[2] == 0x0 && Signature[3] == 0xC &&
526       Signature[4] == 0xE && Signature[5] == 0xD)
527     CurStreamType = LLVMIRBitstream;
528
529   return false;
530 }
531
532 /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
533 static int AnalyzeBitcode() {
534   std::unique_ptr<MemoryBuffer> StreamBuffer;
535   BitstreamReader StreamFile;
536   BitstreamCursor Stream;
537   CurStreamTypeType CurStreamType;
538   if (openBitcodeFile(InputFilename, StreamBuffer, StreamFile, Stream,
539                       CurStreamType))
540     return true;
541
542   // Read block info from BlockInfoFilename, if specified.
543   // The block info must be a top-level block.
544   if (!BlockInfoFilename.empty()) {
545     std::unique_ptr<MemoryBuffer> BlockInfoBuffer;
546     BitstreamReader BlockInfoFile;
547     BitstreamCursor BlockInfoCursor;
548     CurStreamTypeType BlockInfoStreamType;
549     if (openBitcodeFile(BlockInfoFilename, BlockInfoBuffer, BlockInfoFile,
550                         BlockInfoCursor, BlockInfoStreamType))
551       return true;
552
553     while (!BlockInfoCursor.AtEndOfStream()) {
554       unsigned Code = BlockInfoCursor.ReadCode();
555       if (Code != bitc::ENTER_SUBBLOCK)
556         return Error("Invalid record at top-level in block info file");
557
558       unsigned BlockID = BlockInfoCursor.ReadSubBlockID();
559       if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
560         if (BlockInfoCursor.ReadBlockInfoBlock())
561           return Error("Malformed BlockInfoBlock in block info file");
562         break;
563       }
564
565       BlockInfoCursor.SkipBlock();
566     }
567
568     StreamFile.takeBlockInfo(std::move(BlockInfoFile));
569   }
570
571   unsigned NumTopBlocks = 0;
572
573   // Parse the top-level structure.  We only allow blocks at the top-level.
574   while (!Stream.AtEndOfStream()) {
575     unsigned Code = Stream.ReadCode();
576     if (Code != bitc::ENTER_SUBBLOCK)
577       return Error("Invalid record at top-level");
578
579     unsigned BlockID = Stream.ReadSubBlockID();
580
581     if (ParseBlock(Stream, BlockID, 0, CurStreamType))
582       return true;
583     ++NumTopBlocks;
584   }
585
586   if (Dump) outs() << "\n\n";
587
588   uint64_t BufferSizeBits = StreamFile.getBitcodeBytes().getExtent() * CHAR_BIT;
589   // Print a summary of the read file.
590   outs() << "Summary of " << InputFilename << ":\n";
591   outs() << "         Total size: ";
592   PrintSize(BufferSizeBits);
593   outs() << "\n";
594   outs() << "        Stream type: ";
595   switch (CurStreamType) {
596   case UnknownBitstream: outs() << "unknown\n"; break;
597   case LLVMIRBitstream:  outs() << "LLVM IR\n"; break;
598   }
599   outs() << "  # Toplevel Blocks: " << NumTopBlocks << "\n";
600   outs() << "\n";
601
602   // Emit per-block stats.
603   outs() << "Per-block Summary:\n";
604   for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(),
605        E = BlockIDStats.end(); I != E; ++I) {
606     outs() << "  Block ID #" << I->first;
607     if (const char *BlockName = GetBlockName(I->first, StreamFile,
608                                              CurStreamType))
609       outs() << " (" << BlockName << ")";
610     outs() << ":\n";
611
612     const PerBlockIDStats &Stats = I->second;
613     outs() << "      Num Instances: " << Stats.NumInstances << "\n";
614     outs() << "         Total Size: ";
615     PrintSize(Stats.NumBits);
616     outs() << "\n";
617     double pct = (Stats.NumBits * 100.0) / BufferSizeBits;
618     outs() << "    Percent of file: " << format("%2.4f%%", pct) << "\n";
619     if (Stats.NumInstances > 1) {
620       outs() << "       Average Size: ";
621       PrintSize(Stats.NumBits/(double)Stats.NumInstances);
622       outs() << "\n";
623       outs() << "  Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
624              << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
625       outs() << "    Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
626              << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
627       outs() << "    Tot/Avg Records: " << Stats.NumRecords << "/"
628              << Stats.NumRecords/(double)Stats.NumInstances << "\n";
629     } else {
630       outs() << "      Num SubBlocks: " << Stats.NumSubBlocks << "\n";
631       outs() << "        Num Abbrevs: " << Stats.NumAbbrevs << "\n";
632       outs() << "        Num Records: " << Stats.NumRecords << "\n";
633     }
634     if (Stats.NumRecords) {
635       double pct = (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumRecords;
636       outs() << "    Percent Abbrevs: " << format("%2.4f%%", pct) << "\n";
637     }
638     outs() << "\n";
639
640     // Print a histogram of the codes we see.
641     if (!NoHistogram && !Stats.CodeFreq.empty()) {
642       std::vector<std::pair<unsigned, unsigned> > FreqPairs;  // <freq,code>
643       for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
644         if (unsigned Freq = Stats.CodeFreq[i].NumInstances)
645           FreqPairs.push_back(std::make_pair(Freq, i));
646       std::stable_sort(FreqPairs.begin(), FreqPairs.end());
647       std::reverse(FreqPairs.begin(), FreqPairs.end());
648
649       outs() << "\tRecord Histogram:\n";
650       outs() << "\t\t  Count    # Bits   %% Abv  Record Kind\n";
651       for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
652         const PerRecordStats &RecStats = Stats.CodeFreq[FreqPairs[i].second];
653
654         outs() << format("\t\t%7d %9lu",
655                          RecStats.NumInstances,
656                          (unsigned long)RecStats.TotalBits);
657
658         if (RecStats.NumAbbrev)
659           outs() <<
660               format("%7.2f  ",
661                      (double)RecStats.NumAbbrev/RecStats.NumInstances*100);
662         else
663           outs() << "         ";
664
665         if (const char *CodeName =
666               GetCodeName(FreqPairs[i].second, I->first, StreamFile,
667                           CurStreamType))
668           outs() << CodeName << "\n";
669         else
670           outs() << "UnknownCode" << FreqPairs[i].second << "\n";
671       }
672       outs() << "\n";
673
674     }
675   }
676   return 0;
677 }
678
679
680 int main(int argc, char **argv) {
681   // Print a stack trace if we signal out.
682   sys::PrintStackTraceOnErrorSignal();
683   PrettyStackTraceProgram X(argc, argv);
684   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
685   cl::ParseCommandLineOptions(argc, argv, "llvm-bcanalyzer file analyzer\n");
686
687   return AnalyzeBitcode();
688 }