Update to add newer bitcodes.
[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/Analysis/Verifier.h"
31 #include "llvm/Bitcode/BitstreamReader.h"
32 #include "llvm/Bitcode/LLVMBitCodes.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/System/Signals.h"
37 #include <map>
38 #include <fstream>
39 #include <iostream>
40 #include <algorithm>
41 using namespace llvm;
42
43 static cl::opt<std::string>
44   InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
45
46 static cl::opt<std::string>
47   OutputFilename("-o", cl::init("-"), cl::desc("<output file>"));
48
49 static cl::opt<bool> Dump("dump", cl::desc("Dump low level bitcode trace"));
50
51 //===----------------------------------------------------------------------===//
52 // Bitcode specific analysis.
53 //===----------------------------------------------------------------------===//
54
55 static cl::opt<bool> NoHistogram("disable-histogram",
56                                  cl::desc("Do not print per-code histogram"));
57
58 static cl::opt<bool>
59 NonSymbolic("non-symbolic",
60             cl::desc("Emit numberic info in dump even if"
61                      " symbolic info is available"));
62
63 /// CurStreamType - If we can sniff the flavor of this stream, we can produce 
64 /// better dump info.
65 static enum {
66   UnknownBitstream,
67   LLVMIRBitstream
68 } CurStreamType;
69
70
71 /// GetBlockName - Return a symbolic block name if known, otherwise return
72 /// null.
73 static const char *GetBlockName(unsigned BlockID) {
74   // Standard blocks for all bitcode files.
75   if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
76     if (BlockID == bitc::BLOCKINFO_BLOCK_ID)
77       return "BLOCKINFO_BLOCK";
78     return 0;
79   }
80   
81   if (CurStreamType != LLVMIRBitstream) return 0;
82   
83   switch (BlockID) {
84   default:                          return 0;
85   case bitc::MODULE_BLOCK_ID:       return "MODULE_BLOCK";
86   case bitc::PARAMATTR_BLOCK_ID:    return "PARAMATTR_BLOCK";
87   case bitc::TYPE_BLOCK_ID:         return "TYPE_BLOCK";
88   case bitc::CONSTANTS_BLOCK_ID:    return "CONSTANTS_BLOCK";
89   case bitc::FUNCTION_BLOCK_ID:     return "FUNCTION_BLOCK";
90   case bitc::TYPE_SYMTAB_BLOCK_ID:  return "TYPE_SYMTAB";
91   case bitc::VALUE_SYMTAB_BLOCK_ID: return "VALUE_SYMTAB";
92   }
93 }
94
95 /// GetCodeName - Return a symbolic code name if known, otherwise return
96 /// null.
97 static const char *GetCodeName(unsigned CodeID, unsigned BlockID) {
98   // Standard blocks for all bitcode files.
99   if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
100     if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
101       switch (CodeID) {
102       default: return 0;
103       case bitc::MODULE_CODE_VERSION:     return "VERSION";
104       }
105     }
106     return 0;
107   }
108   
109   if (CurStreamType != LLVMIRBitstream) return 0;
110   
111   switch (BlockID) {
112   default: return 0;
113   case bitc::MODULE_BLOCK_ID:
114     switch (CodeID) {
115     default: return 0;
116     case bitc::MODULE_CODE_VERSION:     return "VERSION";
117     case bitc::MODULE_CODE_TRIPLE:      return "TRIPLE";
118     case bitc::MODULE_CODE_DATALAYOUT:  return "DATALAYOUT";
119     case bitc::MODULE_CODE_ASM:         return "ASM";
120     case bitc::MODULE_CODE_SECTIONNAME: return "SECTIONNAME";
121     case bitc::MODULE_CODE_DEPLIB:      return "DEPLIB";
122     case bitc::MODULE_CODE_GLOBALVAR:   return "GLOBALVAR";
123     case bitc::MODULE_CODE_FUNCTION:    return "FUNCTION";
124     case bitc::MODULE_CODE_ALIAS:       return "ALIAS";
125     case bitc::MODULE_CODE_PURGEVALS:   return "PURGEVALS";
126     case bitc::MODULE_CODE_GCNAME:      return "GCNAME";
127     }
128   case bitc::PARAMATTR_BLOCK_ID:
129     switch (CodeID) {
130     default: return 0;
131     case bitc::PARAMATTR_CODE_ENTRY: return "ENTRY";
132     }
133   case bitc::TYPE_BLOCK_ID:
134     switch (CodeID) {
135     default: return 0;
136     case bitc::TYPE_CODE_NUMENTRY:  return "NUMENTRY";
137     case bitc::TYPE_CODE_VOID:      return "VOID";
138     case bitc::TYPE_CODE_FLOAT:     return "FLOAT";
139     case bitc::TYPE_CODE_DOUBLE:    return "DOUBLE";
140     case bitc::TYPE_CODE_LABEL:     return "LABEL";
141     case bitc::TYPE_CODE_OPAQUE:    return "OPAQUE";
142     case bitc::TYPE_CODE_INTEGER:   return "INTEGER";
143     case bitc::TYPE_CODE_POINTER:   return "POINTER";
144     case bitc::TYPE_CODE_FUNCTION:  return "FUNCTION";
145     case bitc::TYPE_CODE_STRUCT:    return "STRUCT";
146     case bitc::TYPE_CODE_ARRAY:     return "ARRAY";
147     case bitc::TYPE_CODE_VECTOR:    return "VECTOR";
148     case bitc::TYPE_CODE_X86_FP80:  return "X86_FP80";
149     case bitc::TYPE_CODE_FP128:     return "FP128";
150     case bitc::TYPE_CODE_PPC_FP128: return "PPC_FP128";
151     }
152     
153   case bitc::CONSTANTS_BLOCK_ID:
154     switch (CodeID) {
155     default: return 0;
156     case bitc::CST_CODE_SETTYPE:       return "SETTYPE";
157     case bitc::CST_CODE_NULL:          return "NULL";
158     case bitc::CST_CODE_UNDEF:         return "UNDEF";
159     case bitc::CST_CODE_INTEGER:       return "INTEGER";
160     case bitc::CST_CODE_WIDE_INTEGER:  return "WIDE_INTEGER";
161     case bitc::CST_CODE_FLOAT:         return "FLOAT";
162     case bitc::CST_CODE_AGGREGATE:     return "AGGREGATE";
163     case bitc::CST_CODE_STRING:        return "STRING";
164     case bitc::CST_CODE_CSTRING:       return "CSTRING";
165     case bitc::CST_CODE_CE_BINOP:      return "CE_BINOP";
166     case bitc::CST_CODE_CE_CAST:       return "CE_CAST";
167     case bitc::CST_CODE_CE_GEP:        return "CE_GEP";
168     case bitc::CST_CODE_CE_SELECT:     return "CE_SELECT";
169     case bitc::CST_CODE_CE_EXTRACTELT: return "CE_EXTRACTELT";
170     case bitc::CST_CODE_CE_INSERTELT:  return "CE_INSERTELT";
171     case bitc::CST_CODE_CE_SHUFFLEVEC: return "CE_SHUFFLEVEC";
172     case bitc::CST_CODE_CE_CMP:        return "CE_CMP";
173     case bitc::CST_CODE_INLINEASM:     return "INLINEASM";
174     }        
175   case bitc::FUNCTION_BLOCK_ID:
176     switch (CodeID) {
177     default: return 0;
178     case bitc::FUNC_CODE_DECLAREBLOCKS: return "DECLAREBLOCKS";
179     
180     case bitc::FUNC_CODE_INST_BINOP:       return "INST_BINOP";
181     case bitc::FUNC_CODE_INST_CAST:        return "INST_CAST";
182     case bitc::FUNC_CODE_INST_GEP:         return "INST_GEP";
183     case bitc::FUNC_CODE_INST_SELECT:      return "INST_SELECT";
184     case bitc::FUNC_CODE_INST_EXTRACTELT:  return "INST_EXTRACTELT";
185     case bitc::FUNC_CODE_INST_INSERTELT:   return "INST_INSERTELT";
186     case bitc::FUNC_CODE_INST_SHUFFLEVEC:  return "INST_SHUFFLEVEC";
187     case bitc::FUNC_CODE_INST_CMP:         return "INST_CMP";
188     
189     case bitc::FUNC_CODE_INST_RET:         return "INST_RET";
190     case bitc::FUNC_CODE_INST_BR:          return "INST_BR";
191     case bitc::FUNC_CODE_INST_SWITCH:      return "INST_SWITCH";
192     case bitc::FUNC_CODE_INST_INVOKE:      return "INST_INVOKE";
193     case bitc::FUNC_CODE_INST_UNWIND:      return "INST_UNWIND";
194     case bitc::FUNC_CODE_INST_UNREACHABLE: return "INST_UNREACHABLE";
195     
196     case bitc::FUNC_CODE_INST_PHI:         return "INST_PHI";
197     case bitc::FUNC_CODE_INST_MALLOC:      return "INST_MALLOC";
198     case bitc::FUNC_CODE_INST_FREE:        return "INST_FREE";
199     case bitc::FUNC_CODE_INST_ALLOCA:      return "INST_ALLOCA";
200     case bitc::FUNC_CODE_INST_LOAD:        return "INST_LOAD";
201     case bitc::FUNC_CODE_INST_STORE:       return "INST_STORE";
202     case bitc::FUNC_CODE_INST_CALL:        return "INST_CALL";
203     case bitc::FUNC_CODE_INST_VAARG:       return "INST_VAARG";
204     case bitc::FUNC_CODE_INST_STORE2:      return "INST_STORE2";
205     case bitc::FUNC_CODE_INST_GETRESULT:   return "INST_GETRESULT";
206     case bitc::FUNC_CODE_INST_EXTRACTVAL:  return "INST_EXTRACTVAL";
207     case bitc::FUNC_CODE_INST_INSERTVAL:   return "INST_INSERTVAL";
208     case bitc::FUNC_CODE_INST_CMP2:        return "INST_CMP2";
209     case bitc::FUNC_CODE_INST_VSELECT:     return "INST_VSELECT";
210     }
211   case bitc::TYPE_SYMTAB_BLOCK_ID:
212     switch (CodeID) {
213     default: return 0;
214     case bitc::TST_CODE_ENTRY: return "ENTRY";
215     }
216   case bitc::VALUE_SYMTAB_BLOCK_ID:
217     switch (CodeID) {
218     default: return 0;
219     case bitc::VST_CODE_ENTRY: return "ENTRY";
220     case bitc::VST_CODE_BBENTRY: return "BBENTRY";
221     }
222   }
223 }
224
225
226 struct PerBlockIDStats {
227   /// NumInstances - This the number of times this block ID has been seen.
228   unsigned NumInstances;
229   
230   /// NumBits - The total size in bits of all of these blocks.
231   uint64_t NumBits;
232   
233   /// NumSubBlocks - The total number of blocks these blocks contain.
234   unsigned NumSubBlocks;
235   
236   /// NumAbbrevs - The total number of abbreviations.
237   unsigned NumAbbrevs;
238   
239   /// NumRecords - The total number of records these blocks contain, and the 
240   /// number that are abbreviated.
241   unsigned NumRecords, NumAbbreviatedRecords;
242   
243   /// CodeFreq - Keep track of the number of times we see each code.
244   std::vector<unsigned> CodeFreq;
245   
246   PerBlockIDStats()
247     : NumInstances(0), NumBits(0),
248       NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {}
249 };
250
251 static std::map<unsigned, PerBlockIDStats> BlockIDStats;
252
253
254
255 /// Error - All bitcode analysis errors go through this function, making this a
256 /// good place to breakpoint if debugging.
257 static bool Error(const std::string &Err) {
258   std::cerr << Err << "\n";
259   return true;
260 }
261
262 /// ParseBlock - Read a block, updating statistics, etc.
263 static bool ParseBlock(BitstreamReader &Stream, unsigned IndentLevel) {
264   std::string Indent(IndentLevel*2, ' ');
265   uint64_t BlockBitStart = Stream.GetCurrentBitNo();
266   unsigned BlockID = Stream.ReadSubBlockID();
267
268   // Get the statistics for this BlockID.
269   PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
270   
271   BlockStats.NumInstances++;
272   
273   // BLOCKINFO is a special part of the stream.
274   if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
275     if (Dump) std::cerr << Indent << "<BLOCKINFO_BLOCK/>\n";
276     if (Stream.ReadBlockInfoBlock())
277       return Error("Malformed BlockInfoBlock");
278     uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
279     BlockStats.NumBits += BlockBitEnd-BlockBitStart;
280     return false;
281   }
282   
283   unsigned NumWords = 0;
284   if (Stream.EnterSubBlock(BlockID, &NumWords))
285     return Error("Malformed block record");
286
287   const char *BlockName = 0;
288   if (Dump) {
289     std::cerr << Indent << "<";
290     if ((BlockName = GetBlockName(BlockID)))
291       std::cerr << BlockName;
292     else
293       std::cerr << "UnknownBlock" << BlockID;
294     
295     if (NonSymbolic && BlockName)
296       std::cerr << " BlockID=" << BlockID;
297     
298     std::cerr << " NumWords=" << NumWords
299               << " BlockCodeSize=" << Stream.GetAbbrevIDWidth() << ">\n";
300   }
301   
302   SmallVector<uint64_t, 64> Record;
303
304   // Read all the records for this block.
305   while (1) {
306     if (Stream.AtEndOfStream())
307       return Error("Premature end of bitstream");
308
309     // Read the code for this record.
310     unsigned AbbrevID = Stream.ReadCode();
311     switch (AbbrevID) {
312     case bitc::END_BLOCK: {
313       if (Stream.ReadBlockEnd())
314         return Error("Error at end of block");
315       uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
316       BlockStats.NumBits += BlockBitEnd-BlockBitStart;
317       if (Dump) {
318         std::cerr << Indent << "</";
319         if (BlockName)
320           std::cerr << BlockName << ">\n";
321         else
322           std::cerr << "UnknownBlock" << BlockID << ">\n";
323       }
324       return false;
325     } 
326     case bitc::ENTER_SUBBLOCK: {
327       uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
328       if (ParseBlock(Stream, IndentLevel+1))
329         return true;
330       ++BlockStats.NumSubBlocks;
331       uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
332       
333       // Don't include subblock sizes in the size of this block.
334       BlockBitStart += SubBlockBitEnd-SubBlockBitStart;
335       break;
336     }
337     case bitc::DEFINE_ABBREV:
338       Stream.ReadAbbrevRecord();
339       ++BlockStats.NumAbbrevs;
340       break;
341     default:
342       ++BlockStats.NumRecords;
343       if (AbbrevID != bitc::UNABBREV_RECORD)
344         ++BlockStats.NumAbbreviatedRecords;
345       
346       Record.clear();
347       unsigned Code = Stream.ReadRecord(AbbrevID, Record);
348
349       // Increment the # occurrences of this code.
350       if (BlockStats.CodeFreq.size() <= Code)
351         BlockStats.CodeFreq.resize(Code+1);
352       BlockStats.CodeFreq[Code]++;
353       
354       if (Dump) {
355         std::cerr << Indent << "  <";
356         if (const char *CodeName = GetCodeName(Code, BlockID))
357           std::cerr << CodeName;
358         else
359           std::cerr << "UnknownCode" << Code;
360         if (NonSymbolic && GetCodeName(Code, BlockID))
361           std::cerr << " codeid=" << Code;
362         if (AbbrevID != bitc::UNABBREV_RECORD)
363           std::cerr << " abbrevid=" << AbbrevID;
364
365         for (unsigned i = 0, e = Record.size(); i != e; ++i)
366           std::cerr << " op" << i << "=" << (int64_t)Record[i];
367         
368         std::cerr << "/>\n";
369       }
370       
371       break;
372     }
373   }
374 }
375
376 static void PrintSize(double Bits) {
377   std::cerr << Bits << "b/" << Bits/8 << "B/" << Bits/32 << "W";
378 }
379
380
381 /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
382 static int AnalyzeBitcode() {
383   // Read the input file.
384   MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename.c_str());
385
386   if (Buffer == 0)
387     return Error("Error reading '" + InputFilename + "'.");
388   
389   if (Buffer->getBufferSize() & 3)
390     return Error("Bitcode stream should be a multiple of 4 bytes in length");
391   
392   unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
393   BitstreamReader Stream(BufPtr, BufPtr+Buffer->getBufferSize());
394
395   
396   // Read the stream signature.
397   char Signature[6];
398   Signature[0] = Stream.Read(8);
399   Signature[1] = Stream.Read(8);
400   Signature[2] = Stream.Read(4);
401   Signature[3] = Stream.Read(4);
402   Signature[4] = Stream.Read(4);
403   Signature[5] = Stream.Read(4);
404   
405   // Autodetect the file contents, if it is one we know.
406   CurStreamType = UnknownBitstream;
407   if (Signature[0] == 'B' && Signature[1] == 'C' &&
408       Signature[2] == 0x0 && Signature[3] == 0xC &&
409       Signature[4] == 0xE && Signature[5] == 0xD)
410     CurStreamType = LLVMIRBitstream;
411
412   unsigned NumTopBlocks = 0;
413   
414   // Parse the top-level structure.  We only allow blocks at the top-level.
415   while (!Stream.AtEndOfStream()) {
416     unsigned Code = Stream.ReadCode();
417     if (Code != bitc::ENTER_SUBBLOCK)
418       return Error("Invalid record at top-level");
419     
420     if (ParseBlock(Stream, 0))
421       return true;
422     ++NumTopBlocks;
423   }
424   
425   if (Dump) std::cerr << "\n\n";
426   
427   uint64_t BufferSizeBits = Buffer->getBufferSize()*8;
428   // Print a summary of the read file.
429   std::cerr << "Summary of " << InputFilename << ":\n";
430   std::cerr << "         Total size: ";
431   PrintSize(BufferSizeBits);
432   std::cerr << "\n";
433   std::cerr << "        Stream type: ";
434   switch (CurStreamType) {
435   default: assert(0 && "Unknown bitstream type");
436   case UnknownBitstream: std::cerr << "unknown\n"; break;
437   case LLVMIRBitstream:  std::cerr << "LLVM IR\n"; break;
438   }
439   std::cerr << "  # Toplevel Blocks: " << NumTopBlocks << "\n";
440   std::cerr << "\n";
441
442   // Emit per-block stats.
443   std::cerr << "Per-block Summary:\n";
444   for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(),
445        E = BlockIDStats.end(); I != E; ++I) {
446     std::cerr << "  Block ID #" << I->first;
447     if (const char *BlockName = GetBlockName(I->first))
448       std::cerr << " (" << BlockName << ")";
449     std::cerr << ":\n";
450     
451     const PerBlockIDStats &Stats = I->second;
452     std::cerr << "      Num Instances: " << Stats.NumInstances << "\n";
453     std::cerr << "         Total Size: ";
454     PrintSize(Stats.NumBits);
455     std::cerr << "\n";
456     std::cerr << "          % of file: "
457               << Stats.NumBits/(double)BufferSizeBits*100 << "\n";
458     if (Stats.NumInstances > 1) {
459       std::cerr << "       Average Size: ";
460       PrintSize(Stats.NumBits/(double)Stats.NumInstances);
461       std::cerr << "\n";
462       std::cerr << "  Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
463                 << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
464       std::cerr << "    Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
465                 << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
466       std::cerr << "    Tot/Avg Records: " << Stats.NumRecords << "/"
467                 << Stats.NumRecords/(double)Stats.NumInstances << "\n";
468     } else {
469       std::cerr << "      Num SubBlocks: " << Stats.NumSubBlocks << "\n";
470       std::cerr << "        Num Abbrevs: " << Stats.NumAbbrevs << "\n";
471       std::cerr << "        Num Records: " << Stats.NumRecords << "\n";
472     }
473     if (Stats.NumRecords)
474       std::cerr << "      % Abbrev Recs: " << (Stats.NumAbbreviatedRecords/
475                    (double)Stats.NumRecords)*100 << "\n";
476     std::cerr << "\n";
477     
478     // Print a histogram of the codes we see.
479     if (!NoHistogram && !Stats.CodeFreq.empty()) {
480       std::vector<std::pair<unsigned, unsigned> > FreqPairs;  // <freq,code>
481       for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
482         if (unsigned Freq = Stats.CodeFreq[i])
483           FreqPairs.push_back(std::make_pair(Freq, i));
484       std::stable_sort(FreqPairs.begin(), FreqPairs.end());
485       std::reverse(FreqPairs.begin(), FreqPairs.end());
486       
487       std::cerr << "\tCode Histogram:\n";
488       for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
489         std::cerr << "\t\t" << FreqPairs[i].first << "\t";
490         if (const char *CodeName = GetCodeName(FreqPairs[i].second, I->first))
491           std::cerr << CodeName << "\n";
492         else
493           std::cerr << "UnknownCode" << FreqPairs[i].second << "\n";
494       }
495       std::cerr << "\n";
496       
497     }
498   }
499   return 0;
500 }
501
502
503 int main(int argc, char **argv) {
504   llvm_shutdown_obj X;  // Call llvm_shutdown() on exit.
505   cl::ParseCommandLineOptions(argc, argv, "llvm-bcanalyzer file analyzer\n");
506   
507   sys::PrintStackTraceOnErrorSignal();
508   
509   return AnalyzeBitcode();
510 }