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