llvm-bcanalyzer.cpp revision cd5b7d7c9d8f6059986cc8a19b28578f8aedbad8
1//===-- llvm-bcanalyzer.cpp - Byte Code Analyzer --------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by Reid Spencer and is distributed under the
6// University of Illinois Open Source 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 bytecode from stdin
12//  llvm-bcanalyzer [options] x.bc - Read LLVM bytecode from the x.bc file
13//
14//  Options:
15//      --help      - Output information about command line switches
16//      --nodetails - Don't print out detailed informaton about individual
17//                    blocks and functions
18//      --dump      - Dump low-level bytecode structure in readable format
19//
20// This tool provides analytical information about a bytecode file. It is
21// intended as an aid to developers of bytecode reading and writing software. It
22// produces on std::out a summary of the bytecode file that shows various
23// statistics about the contents of the file. By default this information is
24// detailed and contains information about individual bytecode blocks and the
25// functions in the module. To avoid this more detailed output, use the
26// -nodetails option to limit the output to just module level information.
27// The tool is also able to print a bytecode file in a straight forward text
28// format that shows the containment and relationships of the information in
29// the bytecode file (-dump option).
30//
31//===----------------------------------------------------------------------===//
32
33#include "llvm/Analysis/Verifier.h"
34#include "llvm/Bitcode/BitstreamReader.h"
35#include "llvm/Bitcode/LLVMBitCodes.h"
36#include "llvm/Bytecode/Analyzer.h"
37#include "llvm/Support/CommandLine.h"
38#include "llvm/Support/Compressor.h"
39#include "llvm/Support/ManagedStatic.h"
40#include "llvm/Support/MemoryBuffer.h"
41#include "llvm/System/Signals.h"
42#include <fstream>
43#include <iostream>
44using namespace llvm;
45
46static cl::opt<std::string>
47  InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
48
49static cl::opt<std::string>
50  OutputFilename("-o", cl::init("-"), cl::desc("<output file>"));
51
52static cl::opt<bool> NoDetails("nodetails", cl::desc("Skip detailed output"));
53static cl::opt<bool> Dump("dump", cl::desc("Dump low level bytecode trace"));
54static cl::opt<bool> Verify("verify", cl::desc("Progressively verify module"));
55
56//===----------------------------------------------------------------------===//
57// Bitcode specific analysis.
58//===----------------------------------------------------------------------===//
59
60static cl::opt<bool> Bitcode("bitcode", cl::desc("Read a bitcode file"));
61
62static cl::opt<bool>
63NonSymbolic("non-symbolic",
64            cl::desc("Emit numberic info in dump even if"
65                     " symbolic info is available"));
66
67/// CurStreamType - If we can sniff the flavor of this stream, we can produce
68/// better dump info.
69static enum {
70  UnknownBitstream,
71  LLVMIRBitstream
72} CurStreamType;
73
74
75/// GetBlockName - Return a symbolic block name if known, otherwise return
76/// null.
77static const char *GetBlockName(unsigned BlockID) {
78  if (CurStreamType != LLVMIRBitstream) return 0;
79
80  switch (BlockID) {
81  default:                          return 0;
82  case bitc::MODULE_BLOCK_ID:       return "MODULE_BLOCK";
83  case bitc::PARAMATTR_BLOCK_ID:    return "PARAMATTR_BLOCK";
84  case bitc::TYPE_BLOCK_ID:         return "TYPE_BLOCK";
85  case bitc::CONSTANTS_BLOCK_ID:    return "CONSTANTS_BLOCK";
86  case bitc::FUNCTION_BLOCK_ID:     return "FUNCTION_BLOCK";
87  case bitc::TYPE_SYMTAB_BLOCK_ID:  return "TYPE_SYMTAB";
88  case bitc::VALUE_SYMTAB_BLOCK_ID: return "VALUE_SYMTAB";
89  }
90}
91
92/// GetCodeName - Return a symbolic code name if known, otherwise return
93/// null.
94static const char *GetCodeName(unsigned CodeID, unsigned BlockID) {
95  if (CurStreamType != LLVMIRBitstream) return 0;
96
97  switch (BlockID) {
98  default: return 0;
99  case bitc::MODULE_BLOCK_ID:
100    switch (CodeID) {
101    default: return 0;
102    case bitc::MODULE_CODE_VERSION:     return "VERSION";
103    case bitc::MODULE_CODE_TRIPLE:      return "TRIPLE";
104    case bitc::MODULE_CODE_DATALAYOUT:  return "DATALAYOUT";
105    case bitc::MODULE_CODE_ASM:         return "ASM";
106    case bitc::MODULE_CODE_SECTIONNAME: return "SECTIONNAME";
107    case bitc::MODULE_CODE_DEPLIB:      return "DEPLIB";
108    case bitc::MODULE_CODE_GLOBALVAR:   return "GLOBALVAR";
109    case bitc::MODULE_CODE_FUNCTION:    return "FUNCTION";
110    case bitc::MODULE_CODE_ALIAS:       return "ALIAS";
111    case bitc::MODULE_CODE_PURGEVALS:   return "PURGEVALS";
112    }
113  case bitc::PARAMATTR_BLOCK_ID:
114    switch (CodeID) {
115    default: return 0;
116    case bitc::PARAMATTR_CODE_ENTRY: return "ENTRY";
117    }
118  case bitc::TYPE_BLOCK_ID:
119    switch (CodeID) {
120    default: return 0;
121    case bitc::TYPE_CODE_NUMENTRY: return "NUMENTRY";
122    case bitc::TYPE_CODE_VOID:     return "VOID";
123    case bitc::TYPE_CODE_FLOAT:    return "FLOAT";
124    case bitc::TYPE_CODE_DOUBLE:   return "DOUBLE";
125    case bitc::TYPE_CODE_LABEL:    return "LABEL";
126    case bitc::TYPE_CODE_OPAQUE:   return "OPAQUE";
127    case bitc::TYPE_CODE_INTEGER:  return "INTEGER";
128    case bitc::TYPE_CODE_POINTER:  return "POINTER";
129    case bitc::TYPE_CODE_FUNCTION: return "FUNCTION";
130    case bitc::TYPE_CODE_STRUCT:   return "STRUCT";
131    case bitc::TYPE_CODE_ARRAY:    return "ARRAY";
132    case bitc::TYPE_CODE_VECTOR:   return "VECTOR";
133    }
134
135  case bitc::CONSTANTS_BLOCK_ID:
136    switch (CodeID) {
137    default: return 0;
138    case bitc::CST_CODE_SETTYPE:       return "SETTYPE";
139    case bitc::CST_CODE_NULL:          return "NULL";
140    case bitc::CST_CODE_UNDEF:         return "UNDEF";
141    case bitc::CST_CODE_INTEGER:       return "INTEGER";
142    case bitc::CST_CODE_WIDE_INTEGER:  return "WIDE_INTEGER";
143    case bitc::CST_CODE_FLOAT:         return "FLOAT";
144    case bitc::CST_CODE_AGGREGATE:     return "AGGREGATE";
145    case bitc::CST_CODE_CE_BINOP:      return "CE_BINOP";
146    case bitc::CST_CODE_CE_CAST:       return "CE_CAST";
147    case bitc::CST_CODE_CE_GEP:        return "CE_GEP";
148    case bitc::CST_CODE_CE_SELECT:     return "CE_SELECT";
149    case bitc::CST_CODE_CE_EXTRACTELT: return "CE_EXTRACTELT";
150    case bitc::CST_CODE_CE_INSERTELT:  return "CE_INSERTELT";
151    case bitc::CST_CODE_CE_SHUFFLEVEC: return "CE_SHUFFLEVEC";
152    case bitc::CST_CODE_CE_CMP:        return "CE_CMP";
153    }
154  case bitc::FUNCTION_BLOCK_ID:
155    switch (CodeID) {
156    default: return 0;
157    case bitc::FUNC_CODE_DECLAREBLOCKS: return "DECLAREBLOCKS";
158
159    case bitc::FUNC_CODE_INST_BINOP:       return "INST_BINOP";
160    case bitc::FUNC_CODE_INST_CAST:        return "INST_CAST";
161    case bitc::FUNC_CODE_INST_GEP:         return "INST_GEP";
162    case bitc::FUNC_CODE_INST_SELECT:      return "INST_SELECT";
163    case bitc::FUNC_CODE_INST_EXTRACTELT:  return "INST_EXTRACTELT";
164    case bitc::FUNC_CODE_INST_INSERTELT:   return "INST_INSERTELT";
165    case bitc::FUNC_CODE_INST_SHUFFLEVEC:  return "INST_SHUFFLEVEC";
166    case bitc::FUNC_CODE_INST_CMP:         return "INST_CMP";
167
168    case bitc::FUNC_CODE_INST_RET:         return "INST_RET";
169    case bitc::FUNC_CODE_INST_BR:          return "INST_BR";
170    case bitc::FUNC_CODE_INST_SWITCH:      return "INST_SWITCH";
171    case bitc::FUNC_CODE_INST_INVOKE:      return "INST_INVOKE";
172    case bitc::FUNC_CODE_INST_UNWIND:      return "INST_UNWIND";
173    case bitc::FUNC_CODE_INST_UNREACHABLE: return "INST_UNREACHABLE";
174
175    case bitc::FUNC_CODE_INST_PHI:         return "INST_PHI";
176    case bitc::FUNC_CODE_INST_MALLOC:      return "INST_MALLOC";
177    case bitc::FUNC_CODE_INST_FREE:        return "INST_FREE";
178    case bitc::FUNC_CODE_INST_ALLOCA:      return "INST_ALLOCA";
179    case bitc::FUNC_CODE_INST_LOAD:        return "INST_LOAD";
180    case bitc::FUNC_CODE_INST_STORE:       return "INST_STORE";
181    case bitc::FUNC_CODE_INST_CALL:        return "INST_CALL";
182    case bitc::FUNC_CODE_INST_VAARG:       return "INST_VAARG";
183    }
184  case bitc::TYPE_SYMTAB_BLOCK_ID:
185    switch (CodeID) {
186    default: return 0;
187    case bitc::TST_CODE_ENTRY: return "ENTRY";
188    }
189  case bitc::VALUE_SYMTAB_BLOCK_ID:
190    switch (CodeID) {
191    default: return 0;
192    case bitc::VST_CODE_ENTRY: return "ENTRY";
193    case bitc::VST_CODE_BBENTRY: return "BBENTRY";
194    }
195  }
196}
197
198
199struct PerBlockIDStats {
200  /// NumInstances - This the number of times this block ID has been seen.
201  unsigned NumInstances;
202
203  /// NumBits - The total size in bits of all of these blocks.
204  uint64_t NumBits;
205
206  /// NumSubBlocks - The total number of blocks these blocks contain.
207  unsigned NumSubBlocks;
208
209  /// NumAbbrevs - The total number of abbreviations.
210  unsigned NumAbbrevs;
211
212  /// NumRecords - The total number of records these blocks contain, and the
213  /// number that are abbreviated.
214  unsigned NumRecords, NumAbbreviatedRecords;
215
216  PerBlockIDStats()
217    : NumInstances(0), NumBits(0),
218      NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {}
219};
220
221static std::map<unsigned, PerBlockIDStats> BlockIDStats;
222
223
224
225/// Error - All bitcode analysis errors go through this function, making this a
226/// good place to breakpoint if debugging.
227static bool Error(const std::string &Err) {
228  std::cerr << Err << "\n";
229  return true;
230}
231
232/// ParseBlock - Read a block, updating statistics, etc.
233static bool ParseBlock(BitstreamReader &Stream, unsigned IndentLevel) {
234  uint64_t BlockBitStart = Stream.GetCurrentBitNo();
235  unsigned BlockID = Stream.ReadSubBlockID();
236
237  // Get the statistics for this BlockID.
238  PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
239
240  BlockStats.NumInstances++;
241
242  unsigned NumWords = 0;
243  if (Stream.EnterSubBlock(&NumWords))
244    return Error("Malformed block record");
245
246  std::string Indent(IndentLevel*2, ' ');
247  const char *BlockName = 0;
248  if (Dump) {
249    std::cerr << Indent << "<";
250    if ((BlockName = GetBlockName(BlockID)))
251      std::cerr << BlockName;
252    else
253      std::cerr << "UnknownBlock" << BlockID;
254
255    if (NonSymbolic && BlockName)
256      std::cerr << " BlockID=" << BlockID;
257
258    std::cerr << " NumWords=" << NumWords
259              << " BlockCodeSize=" << Stream.GetAbbrevIDWidth() << ">\n";
260  }
261
262  SmallVector<uint64_t, 64> Record;
263
264  // Read all the records for this block.
265  while (1) {
266    if (Stream.AtEndOfStream())
267      return Error("Premature end of bitstream");
268
269    // Read the code for this record.
270    unsigned AbbrevID = Stream.ReadCode();
271    switch (AbbrevID) {
272    case bitc::END_BLOCK: {
273      if (Stream.ReadBlockEnd())
274        return Error("Error at end of block");
275      uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
276      BlockStats.NumBits += BlockBitEnd-BlockBitStart;
277      if (Dump) {
278        std::cerr << Indent << "</";
279        if (BlockName)
280          std::cerr << BlockName << ">\n";
281        else
282          std::cerr << "UnknownBlock" << BlockID << ">\n";
283      }
284      return false;
285    }
286    case bitc::ENTER_SUBBLOCK:
287      if (ParseBlock(Stream, IndentLevel+1))
288        return true;
289      ++BlockStats.NumSubBlocks;
290      break;
291    case bitc::DEFINE_ABBREV:
292      Stream.ReadAbbrevRecord();
293      ++BlockStats.NumAbbrevs;
294      break;
295    default:
296      ++BlockStats.NumRecords;
297      if (AbbrevID != bitc::UNABBREV_RECORD)
298        ++BlockStats.NumAbbreviatedRecords;
299
300      Record.clear();
301      unsigned Code = Stream.ReadRecord(AbbrevID, Record);
302      // TODO: Compute per-blockid/code stats.
303
304      if (Dump) {
305        std::cerr << Indent << "  <";
306        if (const char *CodeName = GetCodeName(Code, BlockID))
307          std::cerr << CodeName;
308        else
309          std::cerr << "UnknownCode" << Code;
310        if (NonSymbolic && GetCodeName(Code, BlockID))
311          std::cerr << " codeid=" << Code;
312        if (AbbrevID != bitc::UNABBREV_RECORD)
313          std::cerr << " abbrevid=" << AbbrevID;
314
315        for (unsigned i = 0, e = Record.size(); i != e; ++i)
316          std::cerr << " op" << i << "=" << (int64_t)Record[i];
317
318        std::cerr << ">\n";
319      }
320
321      break;
322    }
323  }
324}
325
326static void PrintSize(double Bits) {
327  std::cerr << Bits << "b/" << Bits/8 << "B/" << Bits/32 << "W";
328}
329
330
331/// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
332static int AnalyzeBitcode() {
333  // Read the input file.
334  MemoryBuffer *Buffer;
335  if (InputFilename == "-")
336    Buffer = MemoryBuffer::getSTDIN();
337  else
338    Buffer = MemoryBuffer::getFile(&InputFilename[0], InputFilename.size());
339
340  if (Buffer == 0)
341    return Error("Error reading '" + InputFilename + "'.");
342
343  if (Buffer->getBufferSize() & 3)
344    return Error("Bitcode stream should be a multiple of 4 bytes in length");
345
346  unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
347  BitstreamReader Stream(BufPtr, BufPtr+Buffer->getBufferSize());
348
349
350  // Read the stream signature.
351  char Signature[6];
352  Signature[0] = Stream.Read(8);
353  Signature[1] = Stream.Read(8);
354  Signature[2] = Stream.Read(4);
355  Signature[3] = Stream.Read(4);
356  Signature[4] = Stream.Read(4);
357  Signature[5] = Stream.Read(4);
358
359  // Autodetect the file contents, if it is one we know.
360  CurStreamType = UnknownBitstream;
361  if (Signature[0] == 'B' && Signature[1] == 'C' &&
362      Signature[2] == 0x0 && Signature[3] == 0xC &&
363      Signature[4] == 0xE && Signature[5] == 0xD)
364    CurStreamType = LLVMIRBitstream;
365
366  unsigned NumTopBlocks = 0;
367
368  // Parse the top-level structure.  We only allow blocks at the top-level.
369  while (!Stream.AtEndOfStream()) {
370    unsigned Code = Stream.ReadCode();
371    if (Code != bitc::ENTER_SUBBLOCK)
372      return Error("Invalid record at top-level");
373
374    if (ParseBlock(Stream, 0))
375      return true;
376    ++NumTopBlocks;
377  }
378
379  if (Dump) std::cerr << "\n\n";
380
381  uint64_t BufferSizeBits = Buffer->getBufferSize()*8;
382  // Print a summary of the read file.
383  std::cerr << "Summary of " << InputFilename << ":\n";
384  std::cerr << "         Total size: ";
385  PrintSize(BufferSizeBits);
386  std::cerr << "\n";
387  std::cerr << "        Stream type: ";
388  switch (CurStreamType) {
389  default: assert(0 && "Unknown bitstream type");
390  case UnknownBitstream: std::cerr << "unknown\n"; break;
391  case LLVMIRBitstream:  std::cerr << "LLVM IR\n"; break;
392  }
393  std::cerr << "  # Toplevel Blocks: " << NumTopBlocks << "\n";
394  std::cerr << "\n";
395
396  // Emit per-block stats.
397  std::cerr << "Per-block Summary:\n";
398  for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(),
399       E = BlockIDStats.end(); I != E; ++I) {
400    std::cerr << "  Block ID #" << I->first;
401    if (const char *BlockName = GetBlockName(I->first))
402      std::cerr << " (" << BlockName << ")";
403    std::cerr << ":\n";
404
405    const PerBlockIDStats &Stats = I->second;
406    std::cerr << "      Num Instances: " << Stats.NumInstances << "\n";
407    std::cerr << "         Total Size: ";
408    PrintSize(Stats.NumBits);
409    std::cerr << "\n";
410    std::cerr << "       Average Size: ";
411    PrintSize(Stats.NumBits/(double)Stats.NumInstances);
412    std::cerr << "\n";
413    std::cerr << "          % of file: "
414              << Stats.NumBits/(double)BufferSizeBits*100 << "\n";
415    std::cerr << "  Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
416              << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
417    std::cerr << "    Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
418              << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
419    std::cerr << "    Tot/Avg Records: " << Stats.NumRecords << "/"
420              << Stats.NumRecords/(double)Stats.NumInstances << "\n";
421    std::cerr << "      % Abbrev Recs: " << (Stats.NumAbbreviatedRecords/
422                 (double)Stats.NumRecords)*100 << "\n";
423    std::cerr << "\n";
424  }
425  return 0;
426}
427
428
429//===----------------------------------------------------------------------===//
430// Bytecode specific analysis.
431//===----------------------------------------------------------------------===//
432
433int main(int argc, char **argv) {
434  llvm_shutdown_obj X;  // Call llvm_shutdown() on exit.
435  cl::ParseCommandLineOptions(argc, argv, " llvm-bcanalyzer file analyzer\n");
436
437  sys::PrintStackTraceOnErrorSignal();
438
439  if (Bitcode)
440    return AnalyzeBitcode();
441
442  try {
443    std::ostream *Out = &std::cout;  // Default to printing to stdout...
444    std::string ErrorMessage;
445    BytecodeAnalysis bca;
446
447    /// Determine what to generate
448    bca.detailedResults = !NoDetails;
449    bca.progressiveVerify = Verify;
450
451    /// Analyze the bytecode file
452    Module* M = AnalyzeBytecodeFile(InputFilename, bca,
453                                    Compressor::decompressToNewBuffer,
454                                    &ErrorMessage, (Dump?Out:0));
455
456    // All that bcanalyzer does is write the gathered statistics to the output
457    PrintBytecodeAnalysis(bca,*Out);
458
459    if (M && Verify) {
460      std::string verificationMsg;
461      if (verifyModule(*M, ReturnStatusAction, &verificationMsg))
462        std::cerr << "Final Verification Message: " << verificationMsg << "\n";
463    }
464
465    if (Out != &std::cout) {
466      ((std::ofstream*)Out)->close();
467      delete Out;
468    }
469    return 0;
470  } catch (const std::string& msg) {
471    std::cerr << argv[0] << ": " << msg << "\n";
472  } catch (...) {
473    std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
474  }
475  return 1;
476}
477