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