[Orc] Add support for emitting indirect stubs directly into the JIT target's
[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/MathExtras.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/PrettyStackTrace.h"
41 #include "llvm/Support/Signals.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include <algorithm>
44 #include <cctype>
45 #include <map>
46 #include <system_error>
47 using namespace llvm;
48
49 static cl::opt<std::string>
50   InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
51
52 static cl::opt<bool> Dump("dump", cl::desc("Dump low level bitcode trace"));
53
54 //===----------------------------------------------------------------------===//
55 // Bitcode specific analysis.
56 //===----------------------------------------------------------------------===//
57
58 static cl::opt<bool> NoHistogram("disable-histogram",
59                                  cl::desc("Do not print per-code histogram"));
60
61 static cl::opt<bool>
62 NonSymbolic("non-symbolic",
63             cl::desc("Emit numeric info in dump even if"
64                      " symbolic info is available"));
65
66 static cl::opt<std::string>
67   BlockInfoFilename("block-info",
68                     cl::desc("Use the BLOCK_INFO from the given file"));
69
70 static cl::opt<bool>
71   ShowBinaryBlobs("show-binary-blobs",
72                   cl::desc("Print binary blobs using hex escapes"));
73
74 namespace {
75
76 /// CurStreamTypeType - A type for CurStreamType
77 enum CurStreamTypeType {
78   UnknownBitstream,
79   LLVMIRBitstream
80 };
81
82 }
83
84 /// GetBlockName - Return a symbolic block name if known, otherwise return
85 /// null.
86 static const char *GetBlockName(unsigned BlockID,
87                                 const BitstreamReader &StreamFile,
88                                 CurStreamTypeType CurStreamType) {
89   // Standard blocks for all bitcode files.
90   if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
91     if (BlockID == bitc::BLOCKINFO_BLOCK_ID)
92       return "BLOCKINFO_BLOCK";
93     return nullptr;
94   }
95
96   // Check to see if we have a blockinfo record for this block, with a name.
97   if (const BitstreamReader::BlockInfo *Info =
98         StreamFile.getBlockInfo(BlockID)) {
99     if (!Info->Name.empty())
100       return Info->Name.c_str();
101   }
102
103
104   if (CurStreamType != LLVMIRBitstream) return nullptr;
105
106   switch (BlockID) {
107   default:                             return nullptr;
108   case bitc::MODULE_BLOCK_ID:          return "MODULE_BLOCK";
109   case bitc::PARAMATTR_BLOCK_ID:       return "PARAMATTR_BLOCK";
110   case bitc::PARAMATTR_GROUP_BLOCK_ID: return "PARAMATTR_GROUP_BLOCK_ID";
111   case bitc::TYPE_BLOCK_ID_NEW:        return "TYPE_BLOCK_ID";
112   case bitc::CONSTANTS_BLOCK_ID:       return "CONSTANTS_BLOCK";
113   case bitc::FUNCTION_BLOCK_ID:        return "FUNCTION_BLOCK";
114   case bitc::VALUE_SYMTAB_BLOCK_ID:    return "VALUE_SYMTAB";
115   case bitc::METADATA_BLOCK_ID:        return "METADATA_BLOCK";
116   case bitc::METADATA_ATTACHMENT_ID:   return "METADATA_ATTACHMENT_BLOCK";
117   case bitc::USELIST_BLOCK_ID:         return "USELIST_BLOCK_ID";
118   case bitc::FUNCTION_SUMMARY_BLOCK_ID:
119                                        return "FUNCTION_SUMMARY_BLOCK";
120   case bitc::MODULE_STRTAB_BLOCK_ID:   return "MODULE_STRTAB_BLOCK";
121   }
122 }
123
124 /// GetCodeName - Return a symbolic code name if known, otherwise return
125 /// null.
126 static const char *GetCodeName(unsigned CodeID, unsigned BlockID,
127                                const BitstreamReader &StreamFile,
128                                CurStreamTypeType CurStreamType) {
129   // Standard blocks for all bitcode files.
130   if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
131     if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
132       switch (CodeID) {
133       default: return nullptr;
134       case bitc::BLOCKINFO_CODE_SETBID:        return "SETBID";
135       case bitc::BLOCKINFO_CODE_BLOCKNAME:     return "BLOCKNAME";
136       case bitc::BLOCKINFO_CODE_SETRECORDNAME: return "SETRECORDNAME";
137       }
138     }
139     return nullptr;
140   }
141
142   // Check to see if we have a blockinfo record for this record, with a name.
143   if (const BitstreamReader::BlockInfo *Info =
144         StreamFile.getBlockInfo(BlockID)) {
145     for (unsigned i = 0, e = Info->RecordNames.size(); i != e; ++i)
146       if (Info->RecordNames[i].first == CodeID)
147         return Info->RecordNames[i].second.c_str();
148   }
149
150
151   if (CurStreamType != LLVMIRBitstream) return nullptr;
152
153 #define STRINGIFY_CODE(PREFIX, CODE)                                           \
154   case bitc::PREFIX##_##CODE:                                                  \
155     return #CODE;
156   switch (BlockID) {
157   default: return nullptr;
158   case bitc::MODULE_BLOCK_ID:
159     switch (CodeID) {
160     default: return nullptr;
161       STRINGIFY_CODE(MODULE_CODE, VERSION)
162       STRINGIFY_CODE(MODULE_CODE, TRIPLE)
163       STRINGIFY_CODE(MODULE_CODE, DATALAYOUT)
164       STRINGIFY_CODE(MODULE_CODE, ASM)
165       STRINGIFY_CODE(MODULE_CODE, SECTIONNAME)
166       STRINGIFY_CODE(MODULE_CODE, DEPLIB) // FIXME: Remove in 4.0
167       STRINGIFY_CODE(MODULE_CODE, GLOBALVAR)
168       STRINGIFY_CODE(MODULE_CODE, FUNCTION)
169       STRINGIFY_CODE(MODULE_CODE, ALIAS)
170       STRINGIFY_CODE(MODULE_CODE, PURGEVALS)
171       STRINGIFY_CODE(MODULE_CODE, GCNAME)
172       STRINGIFY_CODE(MODULE_CODE, VSTOFFSET)
173     }
174   case bitc::PARAMATTR_BLOCK_ID:
175     switch (CodeID) {
176     default: return nullptr;
177     // FIXME: Should these be different?
178     case bitc::PARAMATTR_CODE_ENTRY_OLD: return "ENTRY";
179     case bitc::PARAMATTR_CODE_ENTRY:     return "ENTRY";
180     case bitc::PARAMATTR_GRP_CODE_ENTRY: return "ENTRY";
181     }
182   case bitc::TYPE_BLOCK_ID_NEW:
183     switch (CodeID) {
184     default: return nullptr;
185       STRINGIFY_CODE(TYPE_CODE, NUMENTRY)
186       STRINGIFY_CODE(TYPE_CODE, VOID)
187       STRINGIFY_CODE(TYPE_CODE, FLOAT)
188       STRINGIFY_CODE(TYPE_CODE, DOUBLE)
189       STRINGIFY_CODE(TYPE_CODE, LABEL)
190       STRINGIFY_CODE(TYPE_CODE, OPAQUE)
191       STRINGIFY_CODE(TYPE_CODE, INTEGER)
192       STRINGIFY_CODE(TYPE_CODE, POINTER)
193       STRINGIFY_CODE(TYPE_CODE, ARRAY)
194       STRINGIFY_CODE(TYPE_CODE, VECTOR)
195       STRINGIFY_CODE(TYPE_CODE, X86_FP80)
196       STRINGIFY_CODE(TYPE_CODE, FP128)
197       STRINGIFY_CODE(TYPE_CODE, PPC_FP128)
198       STRINGIFY_CODE(TYPE_CODE, METADATA)
199       STRINGIFY_CODE(TYPE_CODE, STRUCT_ANON)
200       STRINGIFY_CODE(TYPE_CODE, STRUCT_NAME)
201       STRINGIFY_CODE(TYPE_CODE, STRUCT_NAMED)
202       STRINGIFY_CODE(TYPE_CODE, FUNCTION)
203     }
204
205   case bitc::CONSTANTS_BLOCK_ID:
206     switch (CodeID) {
207     default: return nullptr;
208       STRINGIFY_CODE(CST_CODE, SETTYPE)
209       STRINGIFY_CODE(CST_CODE, NULL)
210       STRINGIFY_CODE(CST_CODE, UNDEF)
211       STRINGIFY_CODE(CST_CODE, INTEGER)
212       STRINGIFY_CODE(CST_CODE, WIDE_INTEGER)
213       STRINGIFY_CODE(CST_CODE, FLOAT)
214       STRINGIFY_CODE(CST_CODE, AGGREGATE)
215       STRINGIFY_CODE(CST_CODE, STRING)
216       STRINGIFY_CODE(CST_CODE, CSTRING)
217       STRINGIFY_CODE(CST_CODE, CE_BINOP)
218       STRINGIFY_CODE(CST_CODE, CE_CAST)
219       STRINGIFY_CODE(CST_CODE, CE_GEP)
220       STRINGIFY_CODE(CST_CODE, CE_INBOUNDS_GEP)
221       STRINGIFY_CODE(CST_CODE, CE_SELECT)
222       STRINGIFY_CODE(CST_CODE, CE_EXTRACTELT)
223       STRINGIFY_CODE(CST_CODE, CE_INSERTELT)
224       STRINGIFY_CODE(CST_CODE, CE_SHUFFLEVEC)
225       STRINGIFY_CODE(CST_CODE, CE_CMP)
226       STRINGIFY_CODE(CST_CODE, INLINEASM)
227       STRINGIFY_CODE(CST_CODE, CE_SHUFVEC_EX)
228     case bitc::CST_CODE_BLOCKADDRESS:    return "CST_CODE_BLOCKADDRESS";
229       STRINGIFY_CODE(CST_CODE, DATA)
230     }
231   case bitc::FUNCTION_BLOCK_ID:
232     switch (CodeID) {
233     default: return nullptr;
234       STRINGIFY_CODE(FUNC_CODE, DECLAREBLOCKS)
235       STRINGIFY_CODE(FUNC_CODE, INST_BINOP)
236       STRINGIFY_CODE(FUNC_CODE, INST_CAST)
237       STRINGIFY_CODE(FUNC_CODE, INST_GEP_OLD)
238       STRINGIFY_CODE(FUNC_CODE, INST_INBOUNDS_GEP_OLD)
239       STRINGIFY_CODE(FUNC_CODE, INST_SELECT)
240       STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTELT)
241       STRINGIFY_CODE(FUNC_CODE, INST_INSERTELT)
242       STRINGIFY_CODE(FUNC_CODE, INST_SHUFFLEVEC)
243       STRINGIFY_CODE(FUNC_CODE, INST_CMP)
244       STRINGIFY_CODE(FUNC_CODE, INST_RET)
245       STRINGIFY_CODE(FUNC_CODE, INST_BR)
246       STRINGIFY_CODE(FUNC_CODE, INST_SWITCH)
247       STRINGIFY_CODE(FUNC_CODE, INST_INVOKE)
248       STRINGIFY_CODE(FUNC_CODE, INST_UNREACHABLE)
249       STRINGIFY_CODE(FUNC_CODE, INST_CLEANUPRET)
250       STRINGIFY_CODE(FUNC_CODE, INST_CATCHRET)
251       STRINGIFY_CODE(FUNC_CODE, INST_CATCHPAD)
252       STRINGIFY_CODE(FUNC_CODE, INST_CLEANUPENDPAD)
253       STRINGIFY_CODE(FUNC_CODE, INST_CATCHENDPAD)
254       STRINGIFY_CODE(FUNC_CODE, INST_TERMINATEPAD)
255       STRINGIFY_CODE(FUNC_CODE, INST_PHI)
256       STRINGIFY_CODE(FUNC_CODE, INST_ALLOCA)
257       STRINGIFY_CODE(FUNC_CODE, INST_LOAD)
258       STRINGIFY_CODE(FUNC_CODE, INST_VAARG)
259       STRINGIFY_CODE(FUNC_CODE, INST_STORE)
260       STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTVAL)
261       STRINGIFY_CODE(FUNC_CODE, INST_INSERTVAL)
262       STRINGIFY_CODE(FUNC_CODE, INST_CMP2)
263       STRINGIFY_CODE(FUNC_CODE, INST_VSELECT)
264       STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC_AGAIN)
265       STRINGIFY_CODE(FUNC_CODE, INST_CALL)
266       STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC)
267       STRINGIFY_CODE(FUNC_CODE, INST_GEP)
268     }
269   case bitc::VALUE_SYMTAB_BLOCK_ID:
270     switch (CodeID) {
271     default: return nullptr;
272     STRINGIFY_CODE(VST_CODE, ENTRY)
273     STRINGIFY_CODE(VST_CODE, BBENTRY)
274     STRINGIFY_CODE(VST_CODE, FNENTRY)
275     STRINGIFY_CODE(VST_CODE, COMBINED_FNENTRY)
276     }
277   case bitc::MODULE_STRTAB_BLOCK_ID:
278     switch (CodeID) {
279     default: return nullptr;
280     STRINGIFY_CODE(MST_CODE, ENTRY)
281     }
282   case bitc::FUNCTION_SUMMARY_BLOCK_ID:
283     switch (CodeID) {
284     default: return nullptr;
285     STRINGIFY_CODE(FS_CODE, PERMODULE_ENTRY)
286     STRINGIFY_CODE(FS_CODE, COMBINED_ENTRY)
287     }
288   case bitc::METADATA_ATTACHMENT_ID:
289     switch(CodeID) {
290     default:return nullptr;
291       STRINGIFY_CODE(METADATA, ATTACHMENT)
292     }
293   case bitc::METADATA_BLOCK_ID:
294     switch(CodeID) {
295     default:return nullptr;
296       STRINGIFY_CODE(METADATA, STRING)
297       STRINGIFY_CODE(METADATA, NAME)
298       STRINGIFY_CODE(METADATA, KIND)
299       STRINGIFY_CODE(METADATA, NODE)
300       STRINGIFY_CODE(METADATA, VALUE)
301       STRINGIFY_CODE(METADATA, OLD_NODE)
302       STRINGIFY_CODE(METADATA, OLD_FN_NODE)
303       STRINGIFY_CODE(METADATA, NAMED_NODE)
304       STRINGIFY_CODE(METADATA, DISTINCT_NODE)
305       STRINGIFY_CODE(METADATA, LOCATION)
306       STRINGIFY_CODE(METADATA, GENERIC_DEBUG)
307       STRINGIFY_CODE(METADATA, SUBRANGE)
308       STRINGIFY_CODE(METADATA, ENUMERATOR)
309       STRINGIFY_CODE(METADATA, BASIC_TYPE)
310       STRINGIFY_CODE(METADATA, FILE)
311       STRINGIFY_CODE(METADATA, DERIVED_TYPE)
312       STRINGIFY_CODE(METADATA, COMPOSITE_TYPE)
313       STRINGIFY_CODE(METADATA, SUBROUTINE_TYPE)
314       STRINGIFY_CODE(METADATA, COMPILE_UNIT)
315       STRINGIFY_CODE(METADATA, SUBPROGRAM)
316       STRINGIFY_CODE(METADATA, LEXICAL_BLOCK)
317       STRINGIFY_CODE(METADATA, LEXICAL_BLOCK_FILE)
318       STRINGIFY_CODE(METADATA, NAMESPACE)
319       STRINGIFY_CODE(METADATA, TEMPLATE_TYPE)
320       STRINGIFY_CODE(METADATA, TEMPLATE_VALUE)
321       STRINGIFY_CODE(METADATA, GLOBAL_VAR)
322       STRINGIFY_CODE(METADATA, LOCAL_VAR)
323       STRINGIFY_CODE(METADATA, EXPRESSION)
324       STRINGIFY_CODE(METADATA, OBJC_PROPERTY)
325       STRINGIFY_CODE(METADATA, IMPORTED_ENTITY)
326       STRINGIFY_CODE(METADATA, MODULE)
327     }
328   case bitc::USELIST_BLOCK_ID:
329     switch(CodeID) {
330     default:return nullptr;
331     case bitc::USELIST_CODE_DEFAULT: return "USELIST_CODE_DEFAULT";
332     case bitc::USELIST_CODE_BB:      return "USELIST_CODE_BB";
333     }
334   }
335 #undef STRINGIFY_CODE
336 }
337
338 struct PerRecordStats {
339   /// The number of times this record code has been seen.
340   unsigned NumInstances;
341   /// The number of times this record code has been seen abbreviated.
342   unsigned NumAbbrev;
343   /// The total number of bits used for this record on disk.
344   uint64_t TotalBits;
345   /// The number of bits that would have been used if no abbrevs were used.
346   uint64_t UnabbrevBits;
347   /// The number of bits that would be used if "good" abbreviations were used.
348   uint64_t GoodAbbrevBits;
349
350   PerRecordStats()
351       : NumInstances(0), NumAbbrev(0), TotalBits(0), UnabbrevBits(0),
352         GoodAbbrevBits(0) {}
353 };
354
355 struct PerBlockIDStats {
356   /// NumInstances - This the number of times this block ID has been seen.
357   unsigned NumInstances;
358
359   /// NumBits - The total size in bits of all of these blocks.
360   uint64_t NumBits;
361
362   /// NumSubBlocks - The total number of blocks these blocks contain.
363   unsigned NumSubBlocks;
364
365   /// NumAbbrevs - The total number of abbreviations.
366   unsigned NumAbbrevs;
367
368   /// NumRecords - The total number of records these blocks contain, and the
369   /// number that are abbreviated.
370   unsigned NumRecords, NumAbbreviatedRecords;
371
372   /// CodeFreq - Keep track of the number of times we see each code.
373   std::vector<PerRecordStats> CodeFreq;
374
375   PerBlockIDStats()
376     : NumInstances(0), NumBits(0),
377       NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {}
378 };
379
380 static std::map<unsigned, PerBlockIDStats> BlockIDStats;
381
382
383
384 /// Error - All bitcode analysis errors go through this function, making this a
385 /// good place to breakpoint if debugging.
386 static bool Error(const Twine &Err) {
387   errs() << Err << "\n";
388   return true;
389 }
390
391 static unsigned computeVBR6Bits(uint64_t Val) {
392   unsigned Bits = 0;
393   do {
394     Bits += 6;
395   } while (Val >>= 5);
396   return Bits;
397 }
398
399 static void addBlobSize(uint64_t &Bits, StringRef Blob) {
400   // Blob size is always VBR6.
401   Bits += computeVBR6Bits(Blob.size());
402
403   // Blob is always 32-bit aligned, and padded to a multiple of 32 bits.
404   RoundUpToAlignment(Bits, 32);
405   Bits += Blob.size() * 8;
406   RoundUpToAlignment(Bits, 32);
407 }
408
409 /// \brief Compute the number of bits that would be used by the record if it
410 /// were unabbreviated.
411 static uint64_t computeUnabbrevBits(unsigned AbbrevIDWidth, unsigned Code,
412                                     ArrayRef<uint64_t> Record, StringRef Blob) {
413   uint64_t Bits =
414       AbbrevIDWidth + computeVBR6Bits(Code) + computeVBR6Bits(Record.size());
415   // Use VBR6 for all fields.
416   for (uint64_t Val : Record)
417     Bits += computeVBR6Bits(Val);
418   // Assume Blob representation for the blob, even though a Blob cannot
419   // be unabbreviated.
420   if (!Blob.empty())
421     addBlobSize(Bits, Blob);
422   return Bits;
423 }
424
425 /// \brief Compute the number of bits that would be used by the record if a
426 /// "good" abbreviation were used. We use an extremely simple heuristic for
427 /// "good"ness: pick the best abbrev that uses a Literal for the record code,
428 /// a normal Blob field for the blob (if present), and a minimal-width Fixed
429 /// field for everything else.
430 static uint64_t computeGoodAbbrevBits(unsigned AbbrevIDWidth, unsigned Code,
431                                       ArrayRef<uint64_t> Record,
432                                       StringRef Blob) {
433   uint64_t Bits = AbbrevIDWidth;
434   // Use Fixed for all fields (other than the record code).
435   for (uint64_t Val : Record)
436     Bits += 64 - llvm::countLeadingZeros(Val);
437   // Assume Blob representation for the blob.
438   if (!Blob.empty())
439     addBlobSize(Bits, Blob);
440   return Bits;
441 }
442
443 /// ParseBlock - Read a block, updating statistics, etc.
444 static bool ParseBlock(BitstreamCursor &Stream, unsigned BlockID,
445                        unsigned IndentLevel, CurStreamTypeType CurStreamType) {
446   std::string Indent(IndentLevel*2, ' ');
447   uint64_t BlockBitStart = Stream.GetCurrentBitNo();
448
449   // Get the statistics for this BlockID.
450   PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
451
452   BlockStats.NumInstances++;
453
454   // BLOCKINFO is a special part of the stream.
455   if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
456     if (Dump) outs() << Indent << "<BLOCKINFO_BLOCK/>\n";
457     if (Stream.ReadBlockInfoBlock())
458       return Error("Malformed BlockInfoBlock");
459     uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
460     BlockStats.NumBits += BlockBitEnd-BlockBitStart;
461     return false;
462   }
463
464   unsigned NumWords = 0;
465   if (Stream.EnterSubBlock(BlockID, &NumWords))
466     return Error("Malformed block record");
467
468   const char *BlockName = nullptr;
469   if (Dump) {
470     outs() << Indent << "<";
471     if ((BlockName = GetBlockName(BlockID, *Stream.getBitStreamReader(),
472                                   CurStreamType)))
473       outs() << BlockName;
474     else
475       outs() << "UnknownBlock" << BlockID;
476
477     if (NonSymbolic && BlockName)
478       outs() << " BlockID=" << BlockID;
479
480     outs() << " NumWords=" << NumWords
481            << " BlockCodeSize=" << Stream.getAbbrevIDWidth() << ">\n";
482   }
483
484   SmallVector<uint64_t, 64> Record;
485
486   // Read all the records for this block.
487   while (1) {
488     if (Stream.AtEndOfStream())
489       return Error("Premature end of bitstream");
490
491     uint64_t RecordStartBit = Stream.GetCurrentBitNo();
492
493     BitstreamEntry Entry =
494       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
495     
496     switch (Entry.Kind) {
497     case BitstreamEntry::Error:
498       return Error("malformed bitcode file");
499     case BitstreamEntry::EndBlock: {
500       uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
501       BlockStats.NumBits += BlockBitEnd-BlockBitStart;
502       if (Dump) {
503         outs() << Indent << "</";
504         if (BlockName)
505           outs() << BlockName << ">\n";
506         else
507           outs() << "UnknownBlock" << BlockID << ">\n";
508       }
509       return false;
510     }
511         
512     case BitstreamEntry::SubBlock: {
513       uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
514       if (ParseBlock(Stream, Entry.ID, IndentLevel+1, CurStreamType))
515         return true;
516       ++BlockStats.NumSubBlocks;
517       uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
518       
519       // Don't include subblock sizes in the size of this block.
520       BlockBitStart += SubBlockBitEnd-SubBlockBitStart;
521       continue;
522     }
523     case BitstreamEntry::Record:
524       // The interesting case.
525       break;
526     }
527
528     if (Entry.ID == bitc::DEFINE_ABBREV) {
529       Stream.ReadAbbrevRecord();
530       ++BlockStats.NumAbbrevs;
531       continue;
532     }
533     
534     Record.clear();
535
536     ++BlockStats.NumRecords;
537
538     StringRef Blob;
539     unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
540
541     // Increment the # occurrences of this code.
542     if (BlockStats.CodeFreq.size() <= Code)
543       BlockStats.CodeFreq.resize(Code+1);
544     BlockStats.CodeFreq[Code].NumInstances++;
545     BlockStats.CodeFreq[Code].TotalBits +=
546       Stream.GetCurrentBitNo()-RecordStartBit;
547     BlockStats.CodeFreq[Code].UnabbrevBits +=
548       computeUnabbrevBits(Stream.getAbbrevIDWidth(), Code, Record, Blob);
549     BlockStats.CodeFreq[Code].GoodAbbrevBits +=
550       computeGoodAbbrevBits(Stream.getAbbrevIDWidth(), Code, Record, Blob);
551     if (Entry.ID != bitc::UNABBREV_RECORD) {
552       BlockStats.CodeFreq[Code].NumAbbrev++;
553       ++BlockStats.NumAbbreviatedRecords;
554     }
555
556     if (Dump) {
557       outs() << Indent << "  <";
558       if (const char *CodeName =
559             GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
560                         CurStreamType))
561         outs() << CodeName;
562       else
563         outs() << "UnknownCode" << Code;
564       if (NonSymbolic &&
565           GetCodeName(Code, BlockID, *Stream.getBitStreamReader(),
566                       CurStreamType))
567         outs() << " codeid=" << Code;
568       const BitCodeAbbrev *Abbv = nullptr;
569       if (Entry.ID != bitc::UNABBREV_RECORD) {
570         Abbv = Stream.getAbbrev(Entry.ID);
571         outs() << " abbrevid=" << Entry.ID;
572       }
573
574       for (unsigned i = 0, e = Record.size(); i != e; ++i)
575         outs() << " op" << i << "=" << (int64_t)Record[i];
576
577       outs() << "/>";
578
579       if (Abbv) {
580         for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i != e; ++i) {
581           const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
582           if (!Op.isEncoding() || Op.getEncoding() != BitCodeAbbrevOp::Array)
583             continue;
584           assert(i + 2 == e && "Array op not second to last");
585           std::string Str;
586           bool ArrayIsPrintable = true;
587           for (unsigned j = i - 1, je = Record.size(); j != je; ++j) {
588             if (!isprint(static_cast<unsigned char>(Record[j]))) {
589               ArrayIsPrintable = false;
590               break;
591             }
592             Str += (char)Record[j];
593           }
594           if (ArrayIsPrintable) outs() << " record string = '" << Str << "'";
595           break;
596         }
597       }
598
599       if (Blob.data()) {
600         outs() << " blob data = ";
601         if (ShowBinaryBlobs) {
602           outs() << "'";
603           outs().write_escaped(Blob, /*hex=*/true) << "'";
604         } else {
605           bool BlobIsPrintable = true;
606           for (unsigned i = 0, e = Blob.size(); i != e; ++i)
607             if (!isprint(static_cast<unsigned char>(Blob[i]))) {
608               BlobIsPrintable = false;
609               break;
610             }
611
612           if (BlobIsPrintable)
613             outs() << "'" << Blob << "'";
614           else
615             outs() << "unprintable, " << Blob.size() << " bytes.";          
616         }
617       }
618
619       outs() << "\n";
620     }
621   }
622 }
623
624 static void PrintSize(double Bits) {
625   outs() << format("%.2f/%.2fB/%luW", Bits, Bits/8,(unsigned long)(Bits/32));
626 }
627 static void PrintSize(uint64_t Bits) {
628   outs() << format("%lub/%.2fB/%luW", (unsigned long)Bits,
629                    (double)Bits/8, (unsigned long)(Bits/32));
630 }
631
632 static bool openBitcodeFile(StringRef Path,
633                             std::unique_ptr<MemoryBuffer> &MemBuf,
634                             BitstreamReader &StreamFile,
635                             BitstreamCursor &Stream,
636                             CurStreamTypeType &CurStreamType) {
637   // Read the input file.
638   ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
639       MemoryBuffer::getFileOrSTDIN(Path);
640   if (std::error_code EC = MemBufOrErr.getError())
641     return Error(Twine("Error reading '") + Path + "': " + EC.message());
642   MemBuf = std::move(MemBufOrErr.get());
643
644   if (MemBuf->getBufferSize() & 3)
645     return Error("Bitcode stream should be a multiple of 4 bytes in length");
646
647   const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
648   const unsigned char *EndBufPtr = BufPtr + MemBuf->getBufferSize();
649
650   // If we have a wrapper header, parse it and ignore the non-bc file contents.
651   // The magic number is 0x0B17C0DE stored in little endian.
652   if (isBitcodeWrapper(BufPtr, EndBufPtr))
653     if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr, true))
654       return Error("Invalid bitcode wrapper header");
655
656   StreamFile = BitstreamReader(BufPtr, EndBufPtr);
657   Stream = BitstreamCursor(StreamFile);
658   StreamFile.CollectBlockInfoNames();
659
660   // Read the stream signature.
661   char Signature[6];
662   Signature[0] = Stream.Read(8);
663   Signature[1] = Stream.Read(8);
664   Signature[2] = Stream.Read(4);
665   Signature[3] = Stream.Read(4);
666   Signature[4] = Stream.Read(4);
667   Signature[5] = Stream.Read(4);
668
669   // Autodetect the file contents, if it is one we know.
670   CurStreamType = UnknownBitstream;
671   if (Signature[0] == 'B' && Signature[1] == 'C' &&
672       Signature[2] == 0x0 && Signature[3] == 0xC &&
673       Signature[4] == 0xE && Signature[5] == 0xD)
674     CurStreamType = LLVMIRBitstream;
675
676   return false;
677 }
678
679 /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
680 static int AnalyzeBitcode() {
681   std::unique_ptr<MemoryBuffer> StreamBuffer;
682   BitstreamReader StreamFile;
683   BitstreamCursor Stream;
684   CurStreamTypeType CurStreamType;
685   if (openBitcodeFile(InputFilename, StreamBuffer, StreamFile, Stream,
686                       CurStreamType))
687     return true;
688
689   // Read block info from BlockInfoFilename, if specified.
690   // The block info must be a top-level block.
691   if (!BlockInfoFilename.empty()) {
692     std::unique_ptr<MemoryBuffer> BlockInfoBuffer;
693     BitstreamReader BlockInfoFile;
694     BitstreamCursor BlockInfoCursor;
695     CurStreamTypeType BlockInfoStreamType;
696     if (openBitcodeFile(BlockInfoFilename, BlockInfoBuffer, BlockInfoFile,
697                         BlockInfoCursor, BlockInfoStreamType))
698       return true;
699
700     while (!BlockInfoCursor.AtEndOfStream()) {
701       unsigned Code = BlockInfoCursor.ReadCode();
702       if (Code != bitc::ENTER_SUBBLOCK)
703         return Error("Invalid record at top-level in block info file");
704
705       unsigned BlockID = BlockInfoCursor.ReadSubBlockID();
706       if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
707         if (BlockInfoCursor.ReadBlockInfoBlock())
708           return Error("Malformed BlockInfoBlock in block info file");
709         break;
710       }
711
712       BlockInfoCursor.SkipBlock();
713     }
714
715     StreamFile.takeBlockInfo(std::move(BlockInfoFile));
716   }
717
718   unsigned NumTopBlocks = 0;
719
720   // Parse the top-level structure.  We only allow blocks at the top-level.
721   while (!Stream.AtEndOfStream()) {
722     unsigned Code = Stream.ReadCode();
723     if (Code != bitc::ENTER_SUBBLOCK)
724       return Error("Invalid record at top-level");
725
726     unsigned BlockID = Stream.ReadSubBlockID();
727
728     if (ParseBlock(Stream, BlockID, 0, CurStreamType))
729       return true;
730     ++NumTopBlocks;
731   }
732
733   if (Dump) outs() << "\n\n";
734
735   uint64_t BufferSizeBits = StreamFile.getBitcodeBytes().getExtent() * CHAR_BIT;
736   // Print a summary of the read file.
737   outs() << "Summary of " << InputFilename << ":\n";
738   outs() << "         Total size: ";
739   PrintSize(BufferSizeBits);
740   outs() << "\n";
741   outs() << "        Stream type: ";
742   switch (CurStreamType) {
743   case UnknownBitstream: outs() << "unknown\n"; break;
744   case LLVMIRBitstream:  outs() << "LLVM IR\n"; break;
745   }
746   outs() << "  # Toplevel Blocks: " << NumTopBlocks << "\n";
747   outs() << "\n";
748
749   // Emit per-block stats.
750   outs() << "Per-block Summary:\n";
751   for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(),
752        E = BlockIDStats.end(); I != E; ++I) {
753     outs() << "  Block ID #" << I->first;
754     if (const char *BlockName = GetBlockName(I->first, StreamFile,
755                                              CurStreamType))
756       outs() << " (" << BlockName << ")";
757     outs() << ":\n";
758
759     const PerBlockIDStats &Stats = I->second;
760     outs() << "      Num Instances: " << Stats.NumInstances << "\n";
761     outs() << "         Total Size: ";
762     PrintSize(Stats.NumBits);
763     outs() << "\n";
764     double pct = (Stats.NumBits * 100.0) / BufferSizeBits;
765     outs() << "    Percent of file: " << format("%2.4f%%", pct) << "\n";
766     if (Stats.NumInstances > 1) {
767       outs() << "       Average Size: ";
768       PrintSize(Stats.NumBits/(double)Stats.NumInstances);
769       outs() << "\n";
770       outs() << "  Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
771              << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
772       outs() << "    Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
773              << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
774       outs() << "    Tot/Avg Records: " << Stats.NumRecords << "/"
775              << Stats.NumRecords/(double)Stats.NumInstances << "\n";
776     } else {
777       outs() << "      Num SubBlocks: " << Stats.NumSubBlocks << "\n";
778       outs() << "        Num Abbrevs: " << Stats.NumAbbrevs << "\n";
779       outs() << "        Num Records: " << Stats.NumRecords << "\n";
780     }
781     if (Stats.NumRecords) {
782       double pct = (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumRecords;
783       outs() << "    Percent Abbrevs: " << format("%2.4f%%", pct) << "\n";
784     }
785     outs() << "\n";
786
787     // Print a histogram of the codes we see.
788     if (!NoHistogram && !Stats.CodeFreq.empty()) {
789       std::vector<std::pair<uint64_t, unsigned> > FreqPairs;  // <bits,code>
790       for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
791         if (unsigned Freq = Stats.CodeFreq[i].TotalBits)
792           FreqPairs.push_back(std::make_pair(Freq, i));
793       std::stable_sort(FreqPairs.begin(), FreqPairs.end());
794       std::reverse(FreqPairs.begin(), FreqPairs.end());
795
796       outs() << "\tRecord Histogram:\n";
797       outs() << "\t\t  Count    # Bits   % Abv  % Cmp (cur/best)  Record Kind\n";
798       for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
799         const PerRecordStats &RecStats = Stats.CodeFreq[FreqPairs[i].second];
800
801         outs() << format("\t\t%7d %9lu ",
802                          RecStats.NumInstances,
803                          (unsigned long)RecStats.TotalBits);
804
805         if (RecStats.NumAbbrev)
806           outs() <<
807               format("%7.2f ",
808                      (double)RecStats.NumAbbrev/RecStats.NumInstances*100);
809         else
810           outs() << "        ";
811
812         if (RecStats.UnabbrevBits)
813           outs() << format(
814               "%7.2f / %7.2f  ",
815               (double)RecStats.TotalBits / RecStats.UnabbrevBits * 100,
816               (double)RecStats.GoodAbbrevBits / RecStats.UnabbrevBits * 100);
817         else
818           outs() << "                   ";
819
820         if (const char *CodeName =
821               GetCodeName(FreqPairs[i].second, I->first, StreamFile,
822                           CurStreamType))
823           outs() << CodeName << "\n";
824         else
825           outs() << "UnknownCode" << FreqPairs[i].second << "\n";
826       }
827       outs() << "\n";
828
829     }
830   }
831   return 0;
832 }
833
834
835 int main(int argc, char **argv) {
836   // Print a stack trace if we signal out.
837   sys::PrintStackTraceOnErrorSignal();
838   PrettyStackTraceProgram X(argc, argv);
839   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
840   cl::ParseCommandLineOptions(argc, argv, "llvm-bcanalyzer file analyzer\n");
841
842   return AnalyzeBitcode();
843 }