llvm.org GIT mirror llvm / 767b1fe
[llvm-bcanalyzer] Refactor and move to libLLVMBitReader This allows us to use the analyzer from unit tests. * Refactor the interface to use proper error handling for most functions after JF's work. * Move everything into a BitstreamAnalyzer class. * Move that to Bitcode/BitcodeAnalyzer.h. Differential Revision: https://reviews.llvm.org/D64116 git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@365286 91177308-0d34-0410-b5e6-96231b3b80d8 Francis Visoiu Mistrih a month ago
4 changed file(s) with 1129 addition(s) and 995 deletion(s). Raw diff Collapse all Expand all
0 //===- llvm/Bitcode/BitcodeAnalyzer.h - Bitcode analyzer --------*- C++ -*-===//
1 //
2 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
3 // See https://llvm.org/LICENSE.txt for license information.
4 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This header defines interfaces to analyze LLVM bitcode files/streams.
9 //
10 //===----------------------------------------------------------------------===//
11
12 #ifndef LLVM_BITCODE_BITCODE_ANALYZER_H
13 #define LLVM_BITCODE_BITCODE_ANALYZER_H
14
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/Bitstream/BitstreamReader.h"
19 #include "llvm/Support/Error.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include
22 #include
23
24 namespace llvm {
25
26 /// CurStreamTypeType - A type for CurStreamType
27 enum CurStreamTypeType {
28 UnknownBitstream,
29 LLVMIRBitstream,
30 ClangSerializedASTBitstream,
31 ClangSerializedDiagnosticsBitstream,
32 };
33
34 struct BCDumpOptions {
35 /// The stream.
36 raw_ostream &OS;
37 /// Print per-code histogram.
38 bool Histogram = false;
39 /// Don't emit numeric info in dump if symbolic info is available.
40 bool Symbolic = false;
41 /// Print binary blobs using hex escapes.
42 bool ShowBinaryBlobs = false;
43
44 BCDumpOptions(raw_ostream &OS) : OS(OS) {}
45 };
46
47 class BitcodeAnalyzer {
48 BitstreamCursor Stream;
49 BitstreamBlockInfo BlockInfo;
50 CurStreamTypeType CurStreamType;
51 Optional BlockInfoStream;
52 unsigned NumTopBlocks = 0;
53
54 struct PerRecordStats {
55 unsigned NumInstances;
56 unsigned NumAbbrev;
57 uint64_t TotalBits;
58 PerRecordStats() : NumInstances(0), NumAbbrev(0), TotalBits(0) {}
59 };
60
61 struct PerBlockIDStats {
62 /// NumInstances - This the number of times this block ID has been seen.
63 unsigned NumInstances;
64 /// NumBits - The total size in bits of all of these blocks.
65 uint64_t NumBits;
66 /// NumSubBlocks - The total number of blocks these blocks contain.
67 unsigned NumSubBlocks;
68 /// NumAbbrevs - The total number of abbreviations.
69 unsigned NumAbbrevs;
70 /// NumRecords - The total number of records these blocks contain, and the
71 /// number that are abbreviated.
72 unsigned NumRecords, NumAbbreviatedRecords;
73 /// CodeFreq - Keep track of the number of times we see each code.
74 std::vector CodeFreq;
75 PerBlockIDStats()
76 : NumInstances(0), NumBits(0), NumSubBlocks(0), NumAbbrevs(0),
77 NumRecords(0), NumAbbreviatedRecords(0) {}
78 };
79
80 std::map BlockIDStats;
81
82 public:
83 BitcodeAnalyzer(StringRef Buffer, Optional BlockInfoBuffer = None);
84 /// Analyze the bitcode file.
85 Error analyze(Optional O = None,
86 Optional CheckHash = None);
87 /// Print stats about the bitcode file.
88 void printStats(BCDumpOptions O, Optional Filename = None);
89
90 private:
91 /// Read a block, updating statistics, etc.
92 Error parseBlock(unsigned BlockID, unsigned IndentLevel,
93 Optional O = None,
94 Optional CheckHash = None);
95
96 Error decodeMetadataStringsBlob(StringRef Indent, ArrayRef Record,
97 StringRef Blob, raw_ostream &OS);
98 };
99
100 } // end namespace llvm
101
102 #endif // LLVM_BITCODE_BITCODE_ANALYZER_H
0 //===- BitcodeAnalyzer.cpp - Internal BitcodeAnalyzer implementation ------===//
1 //
2 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
3 // See https://llvm.org/LICENSE.txt for license information.
4 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "llvm/Bitcode/BitcodeAnalyzer.h"
9 #include "llvm/Bitcode/BitcodeReader.h"
10 #include "llvm/Bitcode/LLVMBitCodes.h"
11 #include "llvm/Support/Format.h"
12 #include "llvm/Support/SHA1.h"
13
14 using namespace llvm;
15
16 static Error reportError(StringRef Message) {
17 return createStringError(std::errc::illegal_byte_sequence, Message.data());
18 }
19
20 /// Return a symbolic block name if known, otherwise return null.
21 static Optional GetBlockName(unsigned BlockID,
22 const BitstreamBlockInfo &BlockInfo,
23 CurStreamTypeType CurStreamType) {
24 // Standard blocks for all bitcode files.
25 if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
26 if (BlockID == bitc::BLOCKINFO_BLOCK_ID)
27 return "BLOCKINFO_BLOCK";
28 return None;
29 }
30
31 // Check to see if we have a blockinfo record for this block, with a name.
32 if (const BitstreamBlockInfo::BlockInfo *Info =
33 BlockInfo.getBlockInfo(BlockID)) {
34 if (!Info->Name.empty())
35 return Info->Name.c_str();
36 }
37
38 if (CurStreamType != LLVMIRBitstream)
39 return None;
40
41 switch (BlockID) {
42 default:
43 return None;
44 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
45 return "OPERAND_BUNDLE_TAGS_BLOCK";
46 case bitc::MODULE_BLOCK_ID:
47 return "MODULE_BLOCK";
48 case bitc::PARAMATTR_BLOCK_ID:
49 return "PARAMATTR_BLOCK";
50 case bitc::PARAMATTR_GROUP_BLOCK_ID:
51 return "PARAMATTR_GROUP_BLOCK_ID";
52 case bitc::TYPE_BLOCK_ID_NEW:
53 return "TYPE_BLOCK_ID";
54 case bitc::CONSTANTS_BLOCK_ID:
55 return "CONSTANTS_BLOCK";
56 case bitc::FUNCTION_BLOCK_ID:
57 return "FUNCTION_BLOCK";
58 case bitc::IDENTIFICATION_BLOCK_ID:
59 return "IDENTIFICATION_BLOCK_ID";
60 case bitc::VALUE_SYMTAB_BLOCK_ID:
61 return "VALUE_SYMTAB";
62 case bitc::METADATA_BLOCK_ID:
63 return "METADATA_BLOCK";
64 case bitc::METADATA_KIND_BLOCK_ID:
65 return "METADATA_KIND_BLOCK";
66 case bitc::METADATA_ATTACHMENT_ID:
67 return "METADATA_ATTACHMENT_BLOCK";
68 case bitc::USELIST_BLOCK_ID:
69 return "USELIST_BLOCK_ID";
70 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
71 return "GLOBALVAL_SUMMARY_BLOCK";
72 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
73 return "FULL_LTO_GLOBALVAL_SUMMARY_BLOCK";
74 case bitc::MODULE_STRTAB_BLOCK_ID:
75 return "MODULE_STRTAB_BLOCK";
76 case bitc::STRTAB_BLOCK_ID:
77 return "STRTAB_BLOCK";
78 case bitc::SYMTAB_BLOCK_ID:
79 return "SYMTAB_BLOCK";
80 }
81 }
82
83 /// Return a symbolic code name if known, otherwise return null.
84 static Optional GetCodeName(unsigned CodeID, unsigned BlockID,
85 const BitstreamBlockInfo &BlockInfo,
86 CurStreamTypeType CurStreamType) {
87 // Standard blocks for all bitcode files.
88 if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
89 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
90 switch (CodeID) {
91 default:
92 return None;
93 case bitc::BLOCKINFO_CODE_SETBID:
94 return "SETBID";
95 case bitc::BLOCKINFO_CODE_BLOCKNAME:
96 return "BLOCKNAME";
97 case bitc::BLOCKINFO_CODE_SETRECORDNAME:
98 return "SETRECORDNAME";
99 }
100 }
101 return None;
102 }
103
104 // Check to see if we have a blockinfo record for this record, with a name.
105 if (const BitstreamBlockInfo::BlockInfo *Info =
106 BlockInfo.getBlockInfo(BlockID)) {
107 for (unsigned i = 0, e = Info->RecordNames.size(); i != e; ++i)
108 if (Info->RecordNames[i].first == CodeID)
109 return Info->RecordNames[i].second.c_str();
110 }
111
112 if (CurStreamType != LLVMIRBitstream)
113 return None;
114
115 #define STRINGIFY_CODE(PREFIX, CODE) \
116 case bitc::PREFIX##_##CODE: \
117 return #CODE;
118 switch (BlockID) {
119 default:
120 return None;
121 case bitc::MODULE_BLOCK_ID:
122 switch (CodeID) {
123 default:
124 return None;
125 STRINGIFY_CODE(MODULE_CODE, VERSION)
126 STRINGIFY_CODE(MODULE_CODE, TRIPLE)
127 STRINGIFY_CODE(MODULE_CODE, DATALAYOUT)
128 STRINGIFY_CODE(MODULE_CODE, ASM)
129 STRINGIFY_CODE(MODULE_CODE, SECTIONNAME)
130 STRINGIFY_CODE(MODULE_CODE, DEPLIB) // FIXME: Remove in 4.0
131 STRINGIFY_CODE(MODULE_CODE, GLOBALVAR)
132 STRINGIFY_CODE(MODULE_CODE, FUNCTION)
133 STRINGIFY_CODE(MODULE_CODE, ALIAS)
134 STRINGIFY_CODE(MODULE_CODE, GCNAME)
135 STRINGIFY_CODE(MODULE_CODE, VSTOFFSET)
136 STRINGIFY_CODE(MODULE_CODE, METADATA_VALUES_UNUSED)
137 STRINGIFY_CODE(MODULE_CODE, SOURCE_FILENAME)
138 STRINGIFY_CODE(MODULE_CODE, HASH)
139 }
140 case bitc::IDENTIFICATION_BLOCK_ID:
141 switch (CodeID) {
142 default:
143 return None;
144 STRINGIFY_CODE(IDENTIFICATION_CODE, STRING)
145 STRINGIFY_CODE(IDENTIFICATION_CODE, EPOCH)
146 }
147 case bitc::PARAMATTR_BLOCK_ID:
148 switch (CodeID) {
149 default:
150 return None;
151 // FIXME: Should these be different?
152 case bitc::PARAMATTR_CODE_ENTRY_OLD:
153 return "ENTRY";
154 case bitc::PARAMATTR_CODE_ENTRY:
155 return "ENTRY";
156 }
157 case bitc::PARAMATTR_GROUP_BLOCK_ID:
158 switch (CodeID) {
159 default:
160 return None;
161 case bitc::PARAMATTR_GRP_CODE_ENTRY:
162 return "ENTRY";
163 }
164 case bitc::TYPE_BLOCK_ID_NEW:
165 switch (CodeID) {
166 default:
167 return None;
168 STRINGIFY_CODE(TYPE_CODE, NUMENTRY)
169 STRINGIFY_CODE(TYPE_CODE, VOID)
170 STRINGIFY_CODE(TYPE_CODE, FLOAT)
171 STRINGIFY_CODE(TYPE_CODE, DOUBLE)
172 STRINGIFY_CODE(TYPE_CODE, LABEL)
173 STRINGIFY_CODE(TYPE_CODE, OPAQUE)
174 STRINGIFY_CODE(TYPE_CODE, INTEGER)
175 STRINGIFY_CODE(TYPE_CODE, POINTER)
176 STRINGIFY_CODE(TYPE_CODE, ARRAY)
177 STRINGIFY_CODE(TYPE_CODE, VECTOR)
178 STRINGIFY_CODE(TYPE_CODE, X86_FP80)
179 STRINGIFY_CODE(TYPE_CODE, FP128)
180 STRINGIFY_CODE(TYPE_CODE, PPC_FP128)
181 STRINGIFY_CODE(TYPE_CODE, METADATA)
182 STRINGIFY_CODE(TYPE_CODE, STRUCT_ANON)
183 STRINGIFY_CODE(TYPE_CODE, STRUCT_NAME)
184 STRINGIFY_CODE(TYPE_CODE, STRUCT_NAMED)
185 STRINGIFY_CODE(TYPE_CODE, FUNCTION)
186 }
187
188 case bitc::CONSTANTS_BLOCK_ID:
189 switch (CodeID) {
190 default:
191 return None;
192 STRINGIFY_CODE(CST_CODE, SETTYPE)
193 STRINGIFY_CODE(CST_CODE, NULL)
194 STRINGIFY_CODE(CST_CODE, UNDEF)
195 STRINGIFY_CODE(CST_CODE, INTEGER)
196 STRINGIFY_CODE(CST_CODE, WIDE_INTEGER)
197 STRINGIFY_CODE(CST_CODE, FLOAT)
198 STRINGIFY_CODE(CST_CODE, AGGREGATE)
199 STRINGIFY_CODE(CST_CODE, STRING)
200 STRINGIFY_CODE(CST_CODE, CSTRING)
201 STRINGIFY_CODE(CST_CODE, CE_BINOP)
202 STRINGIFY_CODE(CST_CODE, CE_CAST)
203 STRINGIFY_CODE(CST_CODE, CE_GEP)
204 STRINGIFY_CODE(CST_CODE, CE_INBOUNDS_GEP)
205 STRINGIFY_CODE(CST_CODE, CE_SELECT)
206 STRINGIFY_CODE(CST_CODE, CE_EXTRACTELT)
207 STRINGIFY_CODE(CST_CODE, CE_INSERTELT)
208 STRINGIFY_CODE(CST_CODE, CE_SHUFFLEVEC)
209 STRINGIFY_CODE(CST_CODE, CE_CMP)
210 STRINGIFY_CODE(CST_CODE, INLINEASM)
211 STRINGIFY_CODE(CST_CODE, CE_SHUFVEC_EX)
212 STRINGIFY_CODE(CST_CODE, CE_UNOP)
213 case bitc::CST_CODE_BLOCKADDRESS:
214 return "CST_CODE_BLOCKADDRESS";
215 STRINGIFY_CODE(CST_CODE, DATA)
216 }
217 case bitc::FUNCTION_BLOCK_ID:
218 switch (CodeID) {
219 default:
220 return None;
221 STRINGIFY_CODE(FUNC_CODE, DECLAREBLOCKS)
222 STRINGIFY_CODE(FUNC_CODE, INST_BINOP)
223 STRINGIFY_CODE(FUNC_CODE, INST_CAST)
224 STRINGIFY_CODE(FUNC_CODE, INST_GEP_OLD)
225 STRINGIFY_CODE(FUNC_CODE, INST_INBOUNDS_GEP_OLD)
226 STRINGIFY_CODE(FUNC_CODE, INST_SELECT)
227 STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTELT)
228 STRINGIFY_CODE(FUNC_CODE, INST_INSERTELT)
229 STRINGIFY_CODE(FUNC_CODE, INST_SHUFFLEVEC)
230 STRINGIFY_CODE(FUNC_CODE, INST_CMP)
231 STRINGIFY_CODE(FUNC_CODE, INST_RET)
232 STRINGIFY_CODE(FUNC_CODE, INST_BR)
233 STRINGIFY_CODE(FUNC_CODE, INST_SWITCH)
234 STRINGIFY_CODE(FUNC_CODE, INST_INVOKE)
235 STRINGIFY_CODE(FUNC_CODE, INST_UNOP)
236 STRINGIFY_CODE(FUNC_CODE, INST_UNREACHABLE)
237 STRINGIFY_CODE(FUNC_CODE, INST_CLEANUPRET)
238 STRINGIFY_CODE(FUNC_CODE, INST_CATCHRET)
239 STRINGIFY_CODE(FUNC_CODE, INST_CATCHPAD)
240 STRINGIFY_CODE(FUNC_CODE, INST_PHI)
241 STRINGIFY_CODE(FUNC_CODE, INST_ALLOCA)
242 STRINGIFY_CODE(FUNC_CODE, INST_LOAD)
243 STRINGIFY_CODE(FUNC_CODE, INST_VAARG)
244 STRINGIFY_CODE(FUNC_CODE, INST_STORE)
245 STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTVAL)
246 STRINGIFY_CODE(FUNC_CODE, INST_INSERTVAL)
247 STRINGIFY_CODE(FUNC_CODE, INST_CMP2)
248 STRINGIFY_CODE(FUNC_CODE, INST_VSELECT)
249 STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC_AGAIN)
250 STRINGIFY_CODE(FUNC_CODE, INST_CALL)
251 STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC)
252 STRINGIFY_CODE(FUNC_CODE, INST_GEP)
253 STRINGIFY_CODE(FUNC_CODE, OPERAND_BUNDLE)
254 STRINGIFY_CODE(FUNC_CODE, INST_FENCE)
255 STRINGIFY_CODE(FUNC_CODE, INST_ATOMICRMW)
256 STRINGIFY_CODE(FUNC_CODE, INST_LOADATOMIC)
257 STRINGIFY_CODE(FUNC_CODE, INST_STOREATOMIC)
258 STRINGIFY_CODE(FUNC_CODE, INST_CMPXCHG)
259 STRINGIFY_CODE(FUNC_CODE, INST_CALLBR)
260 }
261 case bitc::VALUE_SYMTAB_BLOCK_ID:
262 switch (CodeID) {
263 default:
264 return None;
265 STRINGIFY_CODE(VST_CODE, ENTRY)
266 STRINGIFY_CODE(VST_CODE, BBENTRY)
267 STRINGIFY_CODE(VST_CODE, FNENTRY)
268 STRINGIFY_CODE(VST_CODE, COMBINED_ENTRY)
269 }
270 case bitc::MODULE_STRTAB_BLOCK_ID:
271 switch (CodeID) {
272 default:
273 return None;
274 STRINGIFY_CODE(MST_CODE, ENTRY)
275 STRINGIFY_CODE(MST_CODE, HASH)
276 }
277 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
278 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
279 switch (CodeID) {
280 default:
281 return None;
282 STRINGIFY_CODE(FS, PERMODULE)
283 STRINGIFY_CODE(FS, PERMODULE_PROFILE)
284 STRINGIFY_CODE(FS, PERMODULE_RELBF)
285 STRINGIFY_CODE(FS, PERMODULE_GLOBALVAR_INIT_REFS)
286 STRINGIFY_CODE(FS, PERMODULE_VTABLE_GLOBALVAR_INIT_REFS)
287 STRINGIFY_CODE(FS, COMBINED)
288 STRINGIFY_CODE(FS, COMBINED_PROFILE)
289 STRINGIFY_CODE(FS, COMBINED_GLOBALVAR_INIT_REFS)
290 STRINGIFY_CODE(FS, ALIAS)
291 STRINGIFY_CODE(FS, COMBINED_ALIAS)
292 STRINGIFY_CODE(FS, COMBINED_ORIGINAL_NAME)
293 STRINGIFY_CODE(FS, VERSION)
294 STRINGIFY_CODE(FS, FLAGS)
295 STRINGIFY_CODE(FS, TYPE_TESTS)
296 STRINGIFY_CODE(FS, TYPE_TEST_ASSUME_VCALLS)
297 STRINGIFY_CODE(FS, TYPE_CHECKED_LOAD_VCALLS)
298 STRINGIFY_CODE(FS, TYPE_TEST_ASSUME_CONST_VCALL)
299 STRINGIFY_CODE(FS, TYPE_CHECKED_LOAD_CONST_VCALL)
300 STRINGIFY_CODE(FS, VALUE_GUID)
301 STRINGIFY_CODE(FS, CFI_FUNCTION_DEFS)
302 STRINGIFY_CODE(FS, CFI_FUNCTION_DECLS)
303 STRINGIFY_CODE(FS, TYPE_ID)
304 STRINGIFY_CODE(FS, TYPE_ID_METADATA)
305 }
306 case bitc::METADATA_ATTACHMENT_ID:
307 switch (CodeID) {
308 default:
309 return None;
310 STRINGIFY_CODE(METADATA, ATTACHMENT)
311 }
312 case bitc::METADATA_BLOCK_ID:
313 switch (CodeID) {
314 default:
315 return None;
316 STRINGIFY_CODE(METADATA, STRING_OLD)
317 STRINGIFY_CODE(METADATA, VALUE)
318 STRINGIFY_CODE(METADATA, NODE)
319 STRINGIFY_CODE(METADATA, NAME)
320 STRINGIFY_CODE(METADATA, DISTINCT_NODE)
321 STRINGIFY_CODE(METADATA, KIND) // Older bitcode has it in a MODULE_BLOCK
322 STRINGIFY_CODE(METADATA, LOCATION)
323 STRINGIFY_CODE(METADATA, OLD_NODE)
324 STRINGIFY_CODE(METADATA, OLD_FN_NODE)
325 STRINGIFY_CODE(METADATA, NAMED_NODE)
326 STRINGIFY_CODE(METADATA, GENERIC_DEBUG)
327 STRINGIFY_CODE(METADATA, SUBRANGE)
328 STRINGIFY_CODE(METADATA, ENUMERATOR)
329 STRINGIFY_CODE(METADATA, BASIC_TYPE)
330 STRINGIFY_CODE(METADATA, FILE)
331 STRINGIFY_CODE(METADATA, DERIVED_TYPE)
332 STRINGIFY_CODE(METADATA, COMPOSITE_TYPE)
333 STRINGIFY_CODE(METADATA, SUBROUTINE_TYPE)
334 STRINGIFY_CODE(METADATA, COMPILE_UNIT)
335 STRINGIFY_CODE(METADATA, SUBPROGRAM)
336 STRINGIFY_CODE(METADATA, LEXICAL_BLOCK)
337 STRINGIFY_CODE(METADATA, LEXICAL_BLOCK_FILE)
338 STRINGIFY_CODE(METADATA, NAMESPACE)
339 STRINGIFY_CODE(METADATA, TEMPLATE_TYPE)
340 STRINGIFY_CODE(METADATA, TEMPLATE_VALUE)
341 STRINGIFY_CODE(METADATA, GLOBAL_VAR)
342 STRINGIFY_CODE(METADATA, LOCAL_VAR)
343 STRINGIFY_CODE(METADATA, EXPRESSION)
344 STRINGIFY_CODE(METADATA, OBJC_PROPERTY)
345 STRINGIFY_CODE(METADATA, IMPORTED_ENTITY)
346 STRINGIFY_CODE(METADATA, MODULE)
347 STRINGIFY_CODE(METADATA, MACRO)
348 STRINGIFY_CODE(METADATA, MACRO_FILE)
349 STRINGIFY_CODE(METADATA, STRINGS)
350 STRINGIFY_CODE(METADATA, GLOBAL_DECL_ATTACHMENT)
351 STRINGIFY_CODE(METADATA, GLOBAL_VAR_EXPR)
352 STRINGIFY_CODE(METADATA, INDEX_OFFSET)
353 STRINGIFY_CODE(METADATA, INDEX)
354 }
355 case bitc::METADATA_KIND_BLOCK_ID:
356 switch (CodeID) {
357 default:
358 return None;
359 STRINGIFY_CODE(METADATA, KIND)
360 }
361 case bitc::USELIST_BLOCK_ID:
362 switch (CodeID) {
363 default:
364 return None;
365 case bitc::USELIST_CODE_DEFAULT:
366 return "USELIST_CODE_DEFAULT";
367 case bitc::USELIST_CODE_BB:
368 return "USELIST_CODE_BB";
369 }
370
371 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
372 switch (CodeID) {
373 default:
374 return None;
375 case bitc::OPERAND_BUNDLE_TAG:
376 return "OPERAND_BUNDLE_TAG";
377 }
378 case bitc::STRTAB_BLOCK_ID:
379 switch (CodeID) {
380 default:
381 return None;
382 case bitc::STRTAB_BLOB:
383 return "BLOB";
384 }
385 case bitc::SYMTAB_BLOCK_ID:
386 switch (CodeID) {
387 default:
388 return None;
389 case bitc::SYMTAB_BLOB:
390 return "BLOB";
391 }
392 }
393 #undef STRINGIFY_CODE
394 }
395
396 static void printSize(raw_ostream &OS, double Bits) {
397 OS << format("%.2f/%.2fB/%luW", Bits, Bits / 8, (unsigned long)(Bits / 32));
398 }
399 static void printSize(raw_ostream &OS, uint64_t Bits) {
400 OS << format("%lub/%.2fB/%luW", (unsigned long)Bits, (double)Bits / 8,
401 (unsigned long)(Bits / 32));
402 }
403
404 static Expected ReadSignature(BitstreamCursor &Stream) {
405 auto tryRead = [&Stream](char &Dest, size_t size) -> Error {
406 if (Expected MaybeWord = Stream.Read(size))
407 Dest = MaybeWord.get();
408 else
409 return MaybeWord.takeError();
410 return Error::success();
411 };
412
413 char Signature[6];
414 if (Error Err = tryRead(Signature[0], 8))
415 return std::move(Err);
416 if (Error Err = tryRead(Signature[1], 8))
417 return std::move(Err);
418
419 // Autodetect the file contents, if it is one we know.
420 if (Signature[0] == 'C' && Signature[1] == 'P') {
421 if (Error Err = tryRead(Signature[2], 8))
422 return std::move(Err);
423 if (Error Err = tryRead(Signature[3], 8))
424 return std::move(Err);
425 if (Signature[2] == 'C' && Signature[3] == 'H')
426 return ClangSerializedASTBitstream;
427 } else if (Signature[0] == 'D' && Signature[1] == 'I') {
428 if (Error Err = tryRead(Signature[2], 8))
429 return std::move(Err);
430 if (Error Err = tryRead(Signature[3], 8))
431 return std::move(Err);
432 if (Signature[2] == 'A' && Signature[3] == 'G')
433 return ClangSerializedDiagnosticsBitstream;
434 } else {
435 if (Error Err = tryRead(Signature[2], 4))
436 return std::move(Err);
437 if (Error Err = tryRead(Signature[3], 4))
438 return std::move(Err);
439 if (Error Err = tryRead(Signature[4], 4))
440 return std::move(Err);
441 if (Error Err = tryRead(Signature[5], 4))
442 return std::move(Err);
443 if (Signature[0] == 'B' && Signature[1] == 'C' && Signature[2] == 0x0 &&
444 Signature[3] == 0xC && Signature[4] == 0xE && Signature[5] == 0xD)
445 return LLVMIRBitstream;
446 }
447 return UnknownBitstream;
448 }
449
450 static Expected analyzeHeader(Optional O,
451 BitstreamCursor &Stream) {
452 ArrayRef Bytes = Stream.getBitcodeBytes();
453 const unsigned char *BufPtr = (const unsigned char *)Bytes.data();
454 const unsigned char *EndBufPtr = BufPtr + Bytes.size();
455
456 // If we have a wrapper header, parse it and ignore the non-bc file
457 // contents. The magic number is 0x0B17C0DE stored in little endian.
458 if (isBitcodeWrapper(BufPtr, EndBufPtr)) {
459 if (Bytes.size() < BWH_HeaderSize)
460 return reportError("Invalid bitcode wrapper header");
461
462 if (O) {
463 unsigned Magic = support::endian::read32le(&BufPtr[BWH_MagicField]);
464 unsigned Version = support::endian::read32le(&BufPtr[BWH_VersionField]);
465 unsigned Offset = support::endian::read32le(&BufPtr[BWH_OffsetField]);
466 unsigned Size = support::endian::read32le(&BufPtr[BWH_SizeField]);
467 unsigned CPUType = support::endian::read32le(&BufPtr[BWH_CPUTypeField]);
468
469 O->OS << "
470 << " Magic=" << format_hex(Magic, 10)
471 << " Version=" << format_hex(Version, 10)
472 << " Offset=" << format_hex(Offset, 10)
473 << " Size=" << format_hex(Size, 10)
474 << " CPUType=" << format_hex(CPUType, 10) << "/>\n";
475 }
476
477 if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr, true))
478 return reportError("Invalid bitcode wrapper header");
479 }
480
481 // Use the cursor modified by skipping the wrapper header.
482 Stream = BitstreamCursor(ArrayRef(BufPtr, EndBufPtr));
483
484 return ReadSignature(Stream);
485 }
486
487 static bool canDecodeBlob(unsigned Code, unsigned BlockID) {
488 return BlockID == bitc::METADATA_BLOCK_ID && Code == bitc::METADATA_STRINGS;
489 }
490
491 Error BitcodeAnalyzer::decodeMetadataStringsBlob(StringRef Indent,
492 ArrayRef Record,
493 StringRef Blob,
494 raw_ostream &OS) {
495 if (Blob.empty())
496 return reportError("Cannot decode empty blob.");
497
498 if (Record.size() != 2)
499 return reportError(
500 "Decoding metadata strings blob needs two record entries.");
501
502 unsigned NumStrings = Record[0];
503 unsigned StringsOffset = Record[1];
504 OS << " num-strings = " << NumStrings << " {\n";
505
506 StringRef Lengths = Blob.slice(0, StringsOffset);
507 SimpleBitstreamCursor R(Lengths);
508 StringRef Strings = Blob.drop_front(StringsOffset);
509 do {
510 if (R.AtEndOfStream())
511 return reportError("bad length");
512
513 Expected MaybeSize = R.ReadVBR(6);
514 if (!MaybeSize)
515 return MaybeSize.takeError();
516 uint32_t Size = MaybeSize.get();
517 if (Strings.size() < Size)
518 return reportError("truncated chars");
519
520 OS << Indent << " '";
521 OS.write_escaped(Strings.slice(0, Size), /*hex=*/true);
522 OS << "'\n";
523 Strings = Strings.drop_front(Size);
524 } while (--NumStrings);
525
526 OS << Indent << " }";
527 return Error::success();
528 }
529
530 BitcodeAnalyzer::BitcodeAnalyzer(StringRef Buffer,
531 Optional BlockInfoBuffer)
532 : Stream(Buffer) {
533 if (BlockInfoBuffer)
534 BlockInfoStream.emplace(*BlockInfoBuffer);
535 }
536
537 Error BitcodeAnalyzer::analyze(Optional O,
538 Optional CheckHash) {
539 if (Expected H = analyzeHeader(O, Stream))
540 CurStreamType = *H;
541
542 Stream.setBlockInfo(&BlockInfo);
543
544 // Read block info from BlockInfoStream, if specified.
545 // The block info must be a top-level block.
546 if (BlockInfoStream) {
547 BitstreamCursor BlockInfoCursor(*BlockInfoStream);
548 CurStreamTypeType BlockInfoStreamType;
549 Expected H = analyzeHeader(O, BlockInfoCursor);
550 if (!H)
551 return H.takeError();
552 BlockInfoStreamType = *H;
553
554 while (!BlockInfoCursor.AtEndOfStream()) {
555 Expected MaybeCode = BlockInfoCursor.ReadCode();
556 if (!MaybeCode)
557 return MaybeCode.takeError();
558 if (MaybeCode.get() != bitc::ENTER_SUBBLOCK)
559 return reportError("Invalid record at top-level in block info file");
560
561 Expected MaybeBlockID = BlockInfoCursor.ReadSubBlockID();
562 if (!MaybeBlockID)
563 return MaybeBlockID.takeError();
564 if (MaybeBlockID.get() == bitc::BLOCKINFO_BLOCK_ID) {
565 Expected> MaybeNewBlockInfo =
566 BlockInfoCursor.ReadBlockInfoBlock(/*ReadBlockInfoNames=*/true);
567 if (!MaybeNewBlockInfo)
568 return MaybeNewBlockInfo.takeError();
569 Optional NewBlockInfo =
570 std::move(MaybeNewBlockInfo.get());
571 if (!NewBlockInfo)
572 return reportError("Malformed BlockInfoBlock in block info file");
573 BlockInfo = std::move(*NewBlockInfo);
574 break;
575 }
576
577 if (Error Err = BlockInfoCursor.SkipBlock())
578 return Err;
579 }
580 }
581
582 // Parse the top-level structure. We only allow blocks at the top-level.
583 while (!Stream.AtEndOfStream()) {
584 Expected MaybeCode = Stream.ReadCode();
585 if (!MaybeCode)
586 return MaybeCode.takeError();
587 if (MaybeCode.get() != bitc::ENTER_SUBBLOCK)
588 return reportError("Invalid record at top-level");
589
590 Expected MaybeBlockID = Stream.ReadSubBlockID();
591 if (!MaybeBlockID)
592 return MaybeBlockID.takeError();
593
594 if (Error E = parseBlock(MaybeBlockID.get(), 0, O, CheckHash))
595 return E;
596 ++NumTopBlocks;
597 }
598
599 return Error::success();
600 }
601
602 void BitcodeAnalyzer::printStats(BCDumpOptions O,
603 Optional Filename) {
604 uint64_t BufferSizeBits = Stream.getBitcodeBytes().size() * CHAR_BIT;
605 // Print a summary of the read file.
606 O.OS << "Summary ";
607 if (Filename)
608 O.OS << "of " << Filename->data() << ":\n";
609 O.OS << " Total size: ";
610 printSize(O.OS, BufferSizeBits);
611 O.OS << "\n";
612 O.OS << " Stream type: ";
613 switch (CurStreamType) {
614 case UnknownBitstream:
615 O.OS << "unknown\n";
616 break;
617 case LLVMIRBitstream:
618 O.OS << "LLVM IR\n";
619 break;
620 case ClangSerializedASTBitstream:
621 O.OS << "Clang Serialized AST\n";
622 break;
623 case ClangSerializedDiagnosticsBitstream:
624 O.OS << "Clang Serialized Diagnostics\n";
625 break;
626 }
627 O.OS << " # Toplevel Blocks: " << NumTopBlocks << "\n";
628 O.OS << "\n";
629
630 // Emit per-block stats.
631 O.OS << "Per-block Summary:\n";
632 for (std::map::iterator I = BlockIDStats.begin(),
633 E = BlockIDStats.end();
634 I != E; ++I) {
635 O.OS << " Block ID #" << I->first;
636 if (Optional BlockName =
637 GetBlockName(I->first, BlockInfo, CurStreamType))
638 O.OS << " (" << *BlockName << ")";
639 O.OS << ":\n";
640
641 const PerBlockIDStats &Stats = I->second;
642 O.OS << " Num Instances: " << Stats.NumInstances << "\n";
643 O.OS << " Total Size: ";
644 printSize(O.OS, Stats.NumBits);
645 O.OS << "\n";
646 double pct = (Stats.NumBits * 100.0) / BufferSizeBits;
647 O.OS << " Percent of file: " << format("%2.4f%%", pct) << "\n";
648 if (Stats.NumInstances > 1) {
649 O.OS << " Average Size: ";
650 printSize(O.OS, Stats.NumBits / (double)Stats.NumInstances);
651 O.OS << "\n";
652 O.OS << " Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
653 << Stats.NumSubBlocks / (double)Stats.NumInstances << "\n";
654 O.OS << " Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
655 << Stats.NumAbbrevs / (double)Stats.NumInstances << "\n";
656 O.OS << " Tot/Avg Records: " << Stats.NumRecords << "/"
657 << Stats.NumRecords / (double)Stats.NumInstances << "\n";
658 } else {
659 O.OS << " Num SubBlocks: " << Stats.NumSubBlocks << "\n";
660 O.OS << " Num Abbrevs: " << Stats.NumAbbrevs << "\n";
661 O.OS << " Num Records: " << Stats.NumRecords << "\n";
662 }
663 if (Stats.NumRecords) {
664 double pct = (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumRecords;
665 O.OS << " Percent Abbrevs: " << format("%2.4f%%", pct) << "\n";
666 }
667 O.OS << "\n";
668
669 // Print a histogram of the codes we see.
670 if (O.Histogram && !Stats.CodeFreq.empty()) {
671 std::vector> FreqPairs; //
672 for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
673 if (unsigned Freq = Stats.CodeFreq[i].NumInstances)
674 FreqPairs.push_back(std::make_pair(Freq, i));
675 llvm::stable_sort(FreqPairs);
676 std::reverse(FreqPairs.begin(), FreqPairs.end());
677
678 O.OS << "\tRecord Histogram:\n";
679 O.OS << "\t\t Count # Bits b/Rec % Abv Record Kind\n";
680 for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
681 const PerRecordStats &RecStats = Stats.CodeFreq[FreqPairs[i].second];
682
683 O.OS << format("\t\t%7d %9lu", RecStats.NumInstances,
684 (unsigned long)RecStats.TotalBits);
685
686 if (RecStats.NumInstances > 1)
687 O.OS << format(" %9.1f",
688 (double)RecStats.TotalBits / RecStats.NumInstances);
689 else
690 O.OS << " ";
691
692 if (RecStats.NumAbbrev)
693 O.OS << format(" %7.2f", (double)RecStats.NumAbbrev /
694 RecStats.NumInstances * 100);
695 else
696 O.OS << " ";
697
698 O.OS << " ";
699 if (Optional CodeName = GetCodeName(
700 FreqPairs[i].second, I->first, BlockInfo, CurStreamType))
701 O.OS << *CodeName << "\n";
702 else
703 O.OS << "UnknownCode" << FreqPairs[i].second << "\n";
704 }
705 O.OS << "\n";
706 }
707 }
708 }
709
710 Error BitcodeAnalyzer::parseBlock(unsigned BlockID, unsigned IndentLevel,
711 Optional O,
712 Optional CheckHash) {
713 std::string Indent(IndentLevel * 2, ' ');
714 uint64_t BlockBitStart = Stream.GetCurrentBitNo();
715
716 // Get the statistics for this BlockID.
717 PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
718
719 BlockStats.NumInstances++;
720
721 // BLOCKINFO is a special part of the stream.
722 bool DumpRecords = O.hasValue();
723 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
724 if (O)
725 O->OS << Indent << "\n";
726 Expected> MaybeNewBlockInfo =
727 Stream.ReadBlockInfoBlock(/*ReadBlockInfoNames=*/true);
728 if (!MaybeNewBlockInfo)
729 return MaybeNewBlockInfo.takeError();
730 Optional NewBlockInfo =
731 std::move(MaybeNewBlockInfo.get());
732 if (!NewBlockInfo)
733 return reportError("Malformed BlockInfoBlock");
734 BlockInfo = std::move(*NewBlockInfo);
735 if (Error Err = Stream.JumpToBit(BlockBitStart))
736 return Err;
737 // It's not really interesting to dump the contents of the blockinfo
738 // block.
739 DumpRecords = false;
740 }
741
742 unsigned NumWords = 0;
743 if (Error Err = Stream.EnterSubBlock(BlockID, &NumWords))
744 return Err;
745
746 // Keep it for later, when we see a MODULE_HASH record
747 uint64_t BlockEntryPos = Stream.getCurrentByteNo();
748
749 Optional BlockName = None;
750 if (DumpRecords) {
751 O->OS << Indent << "<";
752 if ((BlockName = GetBlockName(BlockID, BlockInfo, CurStreamType)))
753 O->OS << *BlockName;
754 else
755 O->OS << "UnknownBlock" << BlockID;
756
757 if (!O->Symbolic && BlockName)
758 O->OS << " BlockID=" << BlockID;
759
760 O->OS << " NumWords=" << NumWords
761 << " BlockCodeSize=" << Stream.getAbbrevIDWidth() << ">\n";
762 }
763
764 SmallVector Record;
765
766 // Keep the offset to the metadata index if seen.
767 uint64_t MetadataIndexOffset = 0;
768
769 // Read all the records for this block.
770 while (1) {
771 if (Stream.AtEndOfStream())
772 return reportError("Premature end of bitstream");
773
774 uint64_t RecordStartBit = Stream.GetCurrentBitNo();
775
776 Expected MaybeEntry =
777 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
778 if (!MaybeEntry)
779 return MaybeEntry.takeError();
780 BitstreamEntry Entry = MaybeEntry.get();
781
782 switch (Entry.Kind) {
783 case BitstreamEntry::Error:
784 return reportError("malformed bitcode file");
785 case BitstreamEntry::EndBlock: {
786 uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
787 BlockStats.NumBits += BlockBitEnd - BlockBitStart;
788 if (DumpRecords) {
789 O->OS << Indent << "
790 if (BlockName)
791 O->OS << *BlockName << ">\n";
792 else
793 O->OS << "UnknownBlock" << BlockID << ">\n";
794 }
795 return Error::success();
796 }
797
798 case BitstreamEntry::SubBlock: {
799 uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
800 if (Error E = parseBlock(Entry.ID, IndentLevel + 1, O, CheckHash))
801 return E;
802 ++BlockStats.NumSubBlocks;
803 uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
804
805 // Don't include subblock sizes in the size of this block.
806 BlockBitStart += SubBlockBitEnd - SubBlockBitStart;
807 continue;
808 }
809 case BitstreamEntry::Record:
810 // The interesting case.
811 break;
812 }
813
814 if (Entry.ID == bitc::DEFINE_ABBREV) {
815 if (Error Err = Stream.ReadAbbrevRecord())
816 return Err;
817 ++BlockStats.NumAbbrevs;
818 continue;
819 }
820
821 Record.clear();
822
823 ++BlockStats.NumRecords;
824
825 StringRef Blob;
826 uint64_t CurrentRecordPos = Stream.GetCurrentBitNo();
827 Expected MaybeCode = Stream.readRecord(Entry.ID, Record, &Blob);
828 if (!MaybeCode)
829 return MaybeCode.takeError();
830 unsigned Code = MaybeCode.get();
831
832 // Increment the # occurrences of this code.
833 if (BlockStats.CodeFreq.size() <= Code)
834 BlockStats.CodeFreq.resize(Code + 1);
835 BlockStats.CodeFreq[Code].NumInstances++;
836 BlockStats.CodeFreq[Code].TotalBits +=
837 Stream.GetCurrentBitNo() - RecordStartBit;
838 if (Entry.ID != bitc::UNABBREV_RECORD) {
839 BlockStats.CodeFreq[Code].NumAbbrev++;
840 ++BlockStats.NumAbbreviatedRecords;
841 }
842
843 if (DumpRecords) {
844 O->OS << Indent << " <";
845 Optional CodeName =
846 GetCodeName(Code, BlockID, BlockInfo, CurStreamType);
847 if (CodeName)
848 O->OS << *CodeName;
849 else
850 O->OS << "UnknownCode" << Code;
851 if (!O->Symbolic && CodeName)
852 O->OS << " codeid=" << Code;
853 const BitCodeAbbrev *Abbv = nullptr;
854 if (Entry.ID != bitc::UNABBREV_RECORD) {
855 Abbv = Stream.getAbbrev(Entry.ID);
856 O->OS << " abbrevid=" << Entry.ID;
857 }
858
859 for (unsigned i = 0, e = Record.size(); i != e; ++i)
860 O->OS << " op" << i << "=" << (int64_t)Record[i];
861
862 // If we found a metadata index, let's verify that we had an offset
863 // before and validate its forward reference offset was correct!
864 if (BlockID == bitc::METADATA_BLOCK_ID) {
865 if (Code == bitc::METADATA_INDEX_OFFSET) {
866 if (Record.size() != 2)
867 O->OS << "(Invalid record)";
868 else {
869 auto Offset = Record[0] + (Record[1] << 32);
870 MetadataIndexOffset = Stream.GetCurrentBitNo() + Offset;
871 }
872 }
873 if (Code == bitc::METADATA_INDEX) {
874 O->OS << " (offset ";
875 if (MetadataIndexOffset == RecordStartBit)
876 O->OS << "match)";
877 else
878 O->OS << "mismatch: " << MetadataIndexOffset << " vs "
879 << RecordStartBit << ")";
880 }
881 }
882
883 // If we found a module hash, let's verify that it matches!
884 if (BlockID == bitc::MODULE_BLOCK_ID && Code == bitc::MODULE_CODE_HASH &&
885 CheckHash.hasValue()) {
886 if (Record.size() != 5)
887 O->OS << " (invalid)";
888 else {
889 // Recompute the hash and compare it to the one in the bitcode
890 SHA1 Hasher;
891 StringRef Hash;
892 Hasher.update(*CheckHash);
893 {
894 int BlockSize = (CurrentRecordPos / 8) - BlockEntryPos;
895 auto Ptr = Stream.getPointerToByte(BlockEntryPos, BlockSize);
896 Hasher.update(ArrayRef(Ptr, BlockSize));
897 Hash = Hasher.result();
898 }
899 SmallString<20> RecordedHash;
900 RecordedHash.resize(20);
901 int Pos = 0;
902 for (auto &Val : Record) {
903 assert(!(Val >> 32) && "Unexpected high bits set");
904 RecordedHash[Pos++] = (Val >> 24) & 0xFF;
905 RecordedHash[Pos++] = (Val >> 16) & 0xFF;
906 RecordedHash[Pos++] = (Val >> 8) & 0xFF;
907 RecordedHash[Pos++] = (Val >> 0) & 0xFF;
908 }
909 if (Hash == RecordedHash)
910 O->OS << " (match)";
911 else
912 O->OS << " (!mismatch!)";
913 }
914 }
915
916 O->OS << "/>";
917
918 if (Abbv) {
919 for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i != e; ++i) {
920 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
921 if (!Op.isEncoding() || Op.getEncoding() != BitCodeAbbrevOp::Array)
922 continue;
923 assert(i + 2 == e && "Array op not second to last");
924 std::string Str;
925 bool ArrayIsPrintable = true;
926 for (unsigned j = i - 1, je = Record.size(); j != je; ++j) {
927 if (!isPrint(static_cast(Record[j]))) {
928 ArrayIsPrintable = false;
929 break;
930 }
931 Str += (char)Record[j];
932 }
933 if (ArrayIsPrintable)
934 O->OS << " record string = '" << Str << "'";
935 break;
936 }
937 }
938
939 if (Blob.data()) {
940 if (canDecodeBlob(Code, BlockID)) {
941 if (Error E = decodeMetadataStringsBlob(Indent, Record, Blob, O->OS))
942 return E;
943 } else {
944 O->OS << " blob data = ";
945 if (O->ShowBinaryBlobs) {
946 O->OS << "'";
947 O->OS.write_escaped(Blob, /*hex=*/true) << "'";
948 } else {
949 bool BlobIsPrintable = true;
950 for (unsigned i = 0, e = Blob.size(); i != e; ++i)
951 if (!isPrint(static_cast(Blob[i]))) {
952 BlobIsPrintable = false;
953 break;
954 }
955
956 if (BlobIsPrintable)
957 O->OS << "'" << Blob << "'";
958 else
959 O->OS << "unprintable, " << Blob.size() << " bytes.";
960 }
961 }
962 }
963
964 O->OS << "\n";
965 }
966
967 // Make sure that we can skip the current record.
968 if (Error Err = Stream.JumpToBit(CurrentRecordPos))
969 return Err;
970 if (Expected Skipped = Stream.skipRecord(Entry.ID))
971 ; // Do nothing.
972 else
973 return Skipped.takeError();
974 }
975 }
976
0 add_llvm_library(LLVMBitReader
1 BitcodeAnalyzer.cpp
12 BitReader.cpp
23 BitcodeReader.cpp
34 MetadataLoader.cpp
2525 //
2626 //===----------------------------------------------------------------------===//
2727
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/Bitcode/BitcodeReader.h"
30 #include "llvm/Bitstream/BitstreamReader.h"
31 #include "llvm/Bitcode/LLVMBitCodes.h"
28 #include "llvm/ADT/Optional.h"
29 #include "llvm/Bitcode/BitcodeAnalyzer.h"
3230 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Format.h"
31 #include "llvm/Support/Error.h"
3432 #include "llvm/Support/InitLLVM.h"
35 #include "llvm/Support/ManagedStatic.h"
3633 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/SHA1.h"
38 #include "llvm/Support/WithColor.h"
3934 #include "llvm/Support/raw_ostream.h"
35 #include
4036 using namespace llvm;
4137
4238 static cl::opt
43 InputFilename(cl::Positional, cl::desc(""), cl::init("-"));
39 InputFilename(cl::Positional, cl::desc(""), cl::init("-"));
4440
4541 static cl::opt Dump("dump", cl::desc("Dump low level bitcode trace"));
4642
5147 static cl::opt NoHistogram("disable-histogram",
5248 cl::desc("Do not print per-code histogram"));
5349
54 static cl::opt
55 NonSymbolic("non-symbolic",
56 cl::desc("Emit numeric info in dump even if"
57 " symbolic info is available"));
50 static cl::opt NonSymbolic("non-symbolic",
51 cl::desc("Emit numeric info in dump even if"
52 " symbolic info is available"));
5853
5954 static cl::opt
60 BlockInfoFilename("block-info",
61 cl::desc("Use the BLOCK_INFO from the given file"));
55 BlockInfoFilename("block-info",
56 cl::desc("Use the BLOCK_INFO from the given file"));
6257
6358 static cl::opt
64 ShowBinaryBlobs("show-binary-blobs",
65 cl::desc("Print binary blobs using hex escapes"));
59 ShowBinaryBlobs("show-binary-blobs",
60 cl::desc("Print binary blobs using hex escapes"));
6661
6762 static cl::opt CheckHash(
6863 "check-hash",
6964 cl::desc("Check module hash using the argument as a string table"));
7065
71 namespace {
72
73 /// CurStreamTypeType - A type for CurStreamType
74 enum CurStreamTypeType {
75 UnknownBitstream,
76 LLVMIRBitstream,
77 ClangSerializedASTBitstream,
78 ClangSerializedDiagnosticsBitstream,
79 };
80
66 static Error reportError(StringRef Message) {
67 return createStringError(std::errc::illegal_byte_sequence, Message.data());
8168 }
8269
83 /// GetBlockName - Return a symbolic block name if known, otherwise return
84 /// null.
85 static const char *GetBlockName(unsigned BlockID,
86 const BitstreamBlockInfo &BlockInfo,
87 CurStreamTypeType CurStreamType) {
88 // Standard blocks for all bitcode files.
89 if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
90 if (BlockID == bitc::BLOCKINFO_BLOCK_ID)
91 return "BLOCKINFO_BLOCK";
92 return nullptr;
93 }
70 static Expected> openBitcodeFile(StringRef Path) {
71 // Read the input file.
72 Expected> MemBufOrErr =
73 errorOrToExpected(MemoryBuffer::getFileOrSTDIN(Path));
74 if (Error E = MemBufOrErr.takeError())
75 return std::move(E);
9476
95 // Check to see if we have a blockinfo record for this block, with a name.
96 if (const BitstreamBlockInfo::BlockInfo *Info =
97 BlockInfo.getBlockInfo(BlockID)) {
98 if (!Info->Name.empty())
99 return Info->Name.c_str();
100 }
101
102
103 if (CurStreamType != LLVMIRBitstream) return nullptr;
104
105 switch (BlockID) {
106 default: return nullptr;
107 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID: return "OPERAND_BUNDLE_TAGS_BLOCK";
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::IDENTIFICATION_BLOCK_ID:
115 return "IDENTIFICATION_BLOCK_ID";
116 case bitc::VALUE_SYMTAB_BLOCK_ID: return "VALUE_SYMTAB";
117 case bitc::METADATA_BLOCK_ID: return "METADATA_BLOCK";
118 case bitc::METADATA_KIND_BLOCK_ID: return "METADATA_KIND_BLOCK";
119 case bitc::METADATA_ATTACHMENT_ID: return "METADATA_ATTACHMENT_BLOCK";
120 case bitc::USELIST_BLOCK_ID: return "USELIST_BLOCK_ID";
121 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
122 return "GLOBALVAL_SUMMARY_BLOCK";
123 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
124 return "FULL_LTO_GLOBALVAL_SUMMARY_BLOCK";
125 case bitc::MODULE_STRTAB_BLOCK_ID: return "MODULE_STRTAB_BLOCK";
126 case bitc::STRTAB_BLOCK_ID: return "STRTAB_BLOCK";
127 case bitc::SYMTAB_BLOCK_ID: return "SYMTAB_BLOCK";
128 }
129 }
130
131 /// GetCodeName - Return a symbolic code name if known, otherwise return
132 /// null.
133 static const char *GetCodeName(unsigned CodeID, unsigned BlockID,
134 const BitstreamBlockInfo &BlockInfo,
135 CurStreamTypeType CurStreamType) {
136 // Standard blocks for all bitcode files.
137 if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
138 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
139 switch (CodeID) {
140 default: return nullptr;
141 case bitc::BLOCKINFO_CODE_SETBID: return "SETBID";
142 case bitc::BLOCKINFO_CODE_BLOCKNAME: return "BLOCKNAME";
143 case bitc::BLOCKINFO_CODE_SETRECORDNAME: return "SETRECORDNAME";
144 }
145 }
146 return nullptr;
147 }
148
149 // Check to see if we have a blockinfo record for this record, with a name.
150 if (const BitstreamBlockInfo::BlockInfo *Info =
151 BlockInfo.getBlockInfo(BlockID)) {
152 for (unsigned i = 0, e = Info->RecordNames.size(); i != e; ++i)
153 if (Info->RecordNames[i].first == CodeID)
154 return Info->RecordNames[i].second.c_str();
155 }
156
157
158 if (CurStreamType != LLVMIRBitstream) return nullptr;
159
160 #define STRINGIFY_CODE(PREFIX, CODE) \
161 case bitc::PREFIX##_##CODE: \
162 return #CODE;
163 switch (BlockID) {
164 default: return nullptr;
165 case bitc::MODULE_BLOCK_ID:
166 switch (CodeID) {
167 default: return nullptr;
168 STRINGIFY_CODE(MODULE_CODE, VERSION)
169 STRINGIFY_CODE(MODULE_CODE, TRIPLE)
170 STRINGIFY_CODE(MODULE_CODE, DATALAYOUT)
171 STRINGIFY_CODE(MODULE_CODE, ASM)
172 STRINGIFY_CODE(MODULE_CODE, SECTIONNAME)
173 STRINGIFY_CODE(MODULE_CODE, DEPLIB) // FIXME: Remove in 4.0
174 STRINGIFY_CODE(MODULE_CODE, GLOBALVAR)
175 STRINGIFY_CODE(MODULE_CODE, FUNCTION)
176 STRINGIFY_CODE(MODULE_CODE, ALIAS)
177 STRINGIFY_CODE(MODULE_CODE, GCNAME)
178 STRINGIFY_CODE(MODULE_CODE, VSTOFFSET)
179 STRINGIFY_CODE(MODULE_CODE, METADATA_VALUES_UNUSED)
180 STRINGIFY_CODE(MODULE_CODE, SOURCE_FILENAME)
181 STRINGIFY_CODE(MODULE_CODE, HASH)
182 }
183 case bitc::IDENTIFICATION_BLOCK_ID:
184 switch (CodeID) {
185 default:
186 return nullptr;
187 STRINGIFY_CODE(IDENTIFICATION_CODE, STRING)
188 STRINGIFY_CODE(IDENTIFICATION_CODE, EPOCH)
189 }
190 case bitc::PARAMATTR_BLOCK_ID:
191 switch (CodeID) {
192 default: return nullptr;
193 // FIXME: Should these be different?
194 case bitc::PARAMATTR_CODE_ENTRY_OLD: return "ENTRY";
195 case bitc::PARAMATTR_CODE_ENTRY: return "ENTRY";
196 }
197 case bitc::PARAMATTR_GROUP_BLOCK_ID:
198 switch (CodeID) {
199 default: return nullptr;
200 case bitc::PARAMATTR_GRP_CODE_ENTRY: return "ENTRY";
201 }
202 case bitc::TYPE_BLOCK_ID_NEW:
203 switch (CodeID) {
204 default: return nullptr;
205 STRINGIFY_CODE(TYPE_CODE, NUMENTRY)
206 STRINGIFY_CODE(TYPE_CODE, VOID)
207 STRINGIFY_CODE(TYPE_CODE, FLOAT)
208 STRINGIFY_CODE(TYPE_CODE, DOUBLE)
209 STRINGIFY_CODE(TYPE_CODE, LABEL)
210 STRINGIFY_CODE(TYPE_CODE, OPAQUE)
211 STRINGIFY_CODE(TYPE_CODE, INTEGER)
212 STRINGIFY_CODE(TYPE_CODE, POINTER)
213 STRINGIFY_CODE(TYPE_CODE, ARRAY)
214 STRINGIFY_CODE(TYPE_CODE, VECTOR)
215 STRINGIFY_CODE(TYPE_CODE, X86_FP80)
216 STRINGIFY_CODE(TYPE_CODE, FP128)
217 STRINGIFY_CODE(TYPE_CODE, PPC_FP128)
218 STRINGIFY_CODE(TYPE_CODE, METADATA)
219 STRINGIFY_CODE(TYPE_CODE, STRUCT_ANON)
220 STRINGIFY_CODE(TYPE_CODE, STRUCT_NAME)
221 STRINGIFY_CODE(TYPE_CODE, STRUCT_NAMED)
222 STRINGIFY_CODE(TYPE_CODE, FUNCTION)
223 }
224
225 case bitc::CONSTANTS_BLOCK_ID:
226 switch (CodeID) {
227 default: return nullptr;
228 STRINGIFY_CODE(CST_CODE, SETTYPE)
229 STRINGIFY_CODE(CST_CODE, NULL)
230 STRINGIFY_CODE(CST_CODE, UNDEF)
231 STRINGIFY_CODE(CST_CODE, INTEGER)
232 STRINGIFY_CODE(CST_CODE, WIDE_INTEGER)
233 STRINGIFY_CODE(CST_CODE, FLOAT)
234 STRINGIFY_CODE(CST_CODE, AGGREGATE)
235 STRINGIFY_CODE(CST_CODE, STRING)
236 STRINGIFY_CODE(CST_CODE, CSTRING)
237 STRINGIFY_CODE(CST_CODE, CE_BINOP)
238 STRINGIFY_CODE(CST_CODE, CE_CAST)
239 STRINGIFY_CODE(CST_CODE, CE_GEP)
240 STRINGIFY_CODE(CST_CODE, CE_INBOUNDS_GEP)
241 STRINGIFY_CODE(CST_CODE, CE_SELECT)
242 STRINGIFY_CODE(CST_CODE, CE_EXTRACTELT)
243 STRINGIFY_CODE(CST_CODE, CE_INSERTELT)
244 STRINGIFY_CODE(CST_CODE, CE_SHUFFLEVEC)
245 STRINGIFY_CODE(CST_CODE, CE_CMP)
246 STRINGIFY_CODE(CST_CODE, INLINEASM)
247 STRINGIFY_CODE(CST_CODE, CE_SHUFVEC_EX)
248 STRINGIFY_CODE(CST_CODE, CE_UNOP)
249 case bitc::CST_CODE_BLOCKADDRESS: return "CST_CODE_BLOCKADDRESS";
250 STRINGIFY_CODE(CST_CODE, DATA)
251 }
252 case bitc::FUNCTION_BLOCK_ID:
253 switch (CodeID) {
254 default: return nullptr;
255 STRINGIFY_CODE(FUNC_CODE, DECLAREBLOCKS)
256 STRINGIFY_CODE(FUNC_CODE, INST_BINOP)
257 STRINGIFY_CODE(FUNC_CODE, INST_CAST)
258 STRINGIFY_CODE(FUNC_CODE, INST_GEP_OLD)
259 STRINGIFY_CODE(FUNC_CODE, INST_INBOUNDS_GEP_OLD)
260 STRINGIFY_CODE(FUNC_CODE, INST_SELECT)
261 STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTELT)
262 STRINGIFY_CODE(FUNC_CODE, INST_INSERTELT)
263 STRINGIFY_CODE(FUNC_CODE, INST_SHUFFLEVEC)
264 STRINGIFY_CODE(FUNC_CODE, INST_CMP)
265 STRINGIFY_CODE(FUNC_CODE, INST_RET)
266 STRINGIFY_CODE(FUNC_CODE, INST_BR)
267 STRINGIFY_CODE(FUNC_CODE, INST_SWITCH)
268 STRINGIFY_CODE(FUNC_CODE, INST_INVOKE)
269 STRINGIFY_CODE(FUNC_CODE, INST_UNOP)
270 STRINGIFY_CODE(FUNC_CODE, INST_UNREACHABLE)
271 STRINGIFY_CODE(FUNC_CODE, INST_CLEANUPRET)
272 STRINGIFY_CODE(FUNC_CODE, INST_CATCHRET)
273 STRINGIFY_CODE(FUNC_CODE, INST_CATCHPAD)
274 STRINGIFY_CODE(FUNC_CODE, INST_PHI)
275 STRINGIFY_CODE(FUNC_CODE, INST_ALLOCA)
276 STRINGIFY_CODE(FUNC_CODE, INST_LOAD)
277 STRINGIFY_CODE(FUNC_CODE, INST_VAARG)
278 STRINGIFY_CODE(FUNC_CODE, INST_STORE)
279 STRINGIFY_CODE(FUNC_CODE, INST_EXTRACTVAL)
280 STRINGIFY_CODE(FUNC_CODE, INST_INSERTVAL)
281 STRINGIFY_CODE(FUNC_CODE, INST_CMP2)
282 STRINGIFY_CODE(FUNC_CODE, INST_VSELECT)
283 STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC_AGAIN)
284 STRINGIFY_CODE(FUNC_CODE, INST_CALL)
285 STRINGIFY_CODE(FUNC_CODE, DEBUG_LOC)
286 STRINGIFY_CODE(FUNC_CODE, INST_GEP)
287 STRINGIFY_CODE(FUNC_CODE, OPERAND_BUNDLE)
288 STRINGIFY_CODE(FUNC_CODE, INST_FENCE)
289 STRINGIFY_CODE(FUNC_CODE, INST_ATOMICRMW)
290 STRINGIFY_CODE(FUNC_CODE, INST_LOADATOMIC)
291 STRINGIFY_CODE(FUNC_CODE, INST_STOREATOMIC)
292 STRINGIFY_CODE(FUNC_CODE, INST_CMPXCHG)
293 STRINGIFY_CODE(FUNC_CODE, INST_CALLBR)
294 }
295 case bitc::VALUE_SYMTAB_BLOCK_ID:
296 switch (CodeID) {
297 default: return nullptr;
298 STRINGIFY_CODE(VST_CODE, ENTRY)
299 STRINGIFY_CODE(VST_CODE, BBENTRY)
300 STRINGIFY_CODE(VST_CODE, FNENTRY)
301 STRINGIFY_CODE(VST_CODE, COMBINED_ENTRY)
302 }
303 case bitc::MODULE_STRTAB_BLOCK_ID:
304 switch (CodeID) {
305 default:
306 return nullptr;
307 STRINGIFY_CODE(MST_CODE, ENTRY)
308 STRINGIFY_CODE(MST_CODE, HASH)
309 }
310 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
311 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
312 switch (CodeID) {
313 default:
314 return nullptr;
315 STRINGIFY_CODE(FS, PERMODULE)
316 STRINGIFY_CODE(FS, PERMODULE_PROFILE)
317 STRINGIFY_CODE(FS, PERMODULE_RELBF)
318 STRINGIFY_CODE(FS, PERMODULE_GLOBALVAR_INIT_REFS)
319 STRINGIFY_CODE(FS, PERMODULE_VTABLE_GLOBALVAR_INIT_REFS)
320 STRINGIFY_CODE(FS, COMBINED)
321 STRINGIFY_CODE(FS, COMBINED_PROFILE)
322 STRINGIFY_CODE(FS, COMBINED_GLOBALVAR_INIT_REFS)
323 STRINGIFY_CODE(FS, ALIAS)
324 STRINGIFY_CODE(FS, COMBINED_ALIAS)
325 STRINGIFY_CODE(FS, COMBINED_ORIGINAL_NAME)
326 STRINGIFY_CODE(FS, VERSION)
327 STRINGIFY_CODE(FS, FLAGS)
328 STRINGIFY_CODE(FS, TYPE_TESTS)
329 STRINGIFY_CODE(FS, TYPE_TEST_ASSUME_VCALLS)
330 STRINGIFY_CODE(FS, TYPE_CHECKED_LOAD_VCALLS)
331 STRINGIFY_CODE(FS, TYPE_TEST_ASSUME_CONST_VCALL)
332 STRINGIFY_CODE(FS, TYPE_CHECKED_LOAD_CONST_VCALL)
333 STRINGIFY_CODE(FS, VALUE_GUID)
334 STRINGIFY_CODE(FS, CFI_FUNCTION_DEFS)
335 STRINGIFY_CODE(FS, CFI_FUNCTION_DECLS)
336 STRINGIFY_CODE(FS, TYPE_ID)
337 STRINGIFY_CODE(FS, TYPE_ID_METADATA)
338 }
339 case bitc::METADATA_ATTACHMENT_ID:
340 switch(CodeID) {
341 default:return nullptr;
342 STRINGIFY_CODE(METADATA, ATTACHMENT)
343 }
344 case bitc::METADATA_BLOCK_ID:
345 switch(CodeID) {
346 default:return nullptr;
347 STRINGIFY_CODE(METADATA, STRING_OLD)
348 STRINGIFY_CODE(METADATA, VALUE)
349 STRINGIFY_CODE(METADATA, NODE)
350 STRINGIFY_CODE(METADATA, NAME)
351 STRINGIFY_CODE(METADATA, DISTINCT_NODE)
352 STRINGIFY_CODE(METADATA, KIND) // Older bitcode has it in a MODULE_BLOCK
353 STRINGIFY_CODE(METADATA, LOCATION)
354 STRINGIFY_CODE(METADATA, OLD_NODE)
355 STRINGIFY_CODE(METADATA, OLD_FN_NODE)
356 STRINGIFY_CODE(METADATA, NAMED_NODE)
357 STRINGIFY_CODE(METADATA, GENERIC_DEBUG)
358 STRINGIFY_CODE(METADATA, SUBRANGE)
359 STRINGIFY_CODE(METADATA, ENUMERATOR)
360 STRINGIFY_CODE(METADATA, BASIC_TYPE)
361 STRINGIFY_CODE(METADATA, FILE)
362 STRINGIFY_CODE(METADATA, DERIVED_TYPE)
363 STRINGIFY_CODE(METADATA, COMPOSITE_TYPE)
364 STRINGIFY_CODE(METADATA, SUBROUTINE_TYPE)
365 STRINGIFY_CODE(METADATA, COMPILE_UNIT)
366 STRINGIFY_CODE(METADATA, SUBPROGRAM)
367 STRINGIFY_CODE(METADATA, LEXICAL_BLOCK)
368 STRINGIFY_CODE(METADATA, LEXICAL_BLOCK_FILE)
369 STRINGIFY_CODE(METADATA, NAMESPACE)
370 STRINGIFY_CODE(METADATA, TEMPLATE_TYPE)
371 STRINGIFY_CODE(METADATA, TEMPLATE_VALUE)
372 STRINGIFY_CODE(METADATA, GLOBAL_VAR)
373 STRINGIFY_CODE(METADATA, LOCAL_VAR)
374 STRINGIFY_CODE(METADATA, EXPRESSION)
375 STRINGIFY_CODE(METADATA, OBJC_PROPERTY)
376 STRINGIFY_CODE(METADATA, IMPORTED_ENTITY)
377 STRINGIFY_CODE(METADATA, MODULE)
378 STRINGIFY_CODE(METADATA, MACRO)
379 STRINGIFY_CODE(METADATA, MACRO_FILE)
380 STRINGIFY_CODE(METADATA, STRINGS)
381 STRINGIFY_CODE(METADATA, GLOBAL_DECL_ATTACHMENT)
382 STRINGIFY_CODE(METADATA, GLOBAL_VAR_EXPR)
383 STRINGIFY_CODE(METADATA, INDEX_OFFSET)
384 STRINGIFY_CODE(METADATA, INDEX)
385 }
386 case bitc::METADATA_KIND_BLOCK_ID:
387 switch (CodeID) {
388 default:
389 return nullptr;
390 STRINGIFY_CODE(METADATA, KIND)
391 }
392 case bitc::USELIST_BLOCK_ID:
393 switch(CodeID) {
394 default:return nullptr;
395 case bitc::USELIST_CODE_DEFAULT: return "USELIST_CODE_DEFAULT";
396 case bitc::USELIST_CODE_BB: return "USELIST_CODE_BB";
397 }
398
399 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
400 switch(CodeID) {
401 default: return nullptr;
402 case bitc::OPERAND_BUNDLE_TAG: return "OPERAND_BUNDLE_TAG";
403 }
404 case bitc::STRTAB_BLOCK_ID:
405 switch(CodeID) {
406 default: return nullptr;
407 case bitc::STRTAB_BLOB: return "BLOB";
408 }
409 case bitc::SYMTAB_BLOCK_ID:
410 switch(CodeID) {
411 default: return nullptr;
412 case bitc::SYMTAB_BLOB: return "BLOB";
413 }
414 }
415 #undef STRINGIFY_CODE
416 }
417
418 struct PerRecordStats {
419 unsigned NumInstances;
420 unsigned NumAbbrev;
421 uint64_t TotalBits;
422
423 PerRecordStats() : NumInstances(0), NumAbbrev(0), TotalBits(0) {}
424 };
425
426 struct PerBlockIDStats {
427 /// NumInstances - This the number of times this block ID has been seen.
428 unsigned NumInstances;
429
430 /// NumBits - The total size in bits of all of these blocks.
431 uint64_t NumBits;
432
433 /// NumSubBlocks - The total number of blocks these blocks contain.
434 unsigned NumSubBlocks;
435
436 /// NumAbbrevs - The total number of abbreviations.
437 unsigned NumAbbrevs;
438
439 /// NumRecords - The total number of records these blocks contain, and the
440 /// number that are abbreviated.
441 unsigned NumRecords, NumAbbreviatedRecords;
442
443 /// CodeFreq - Keep track of the number of times we see each code.
444 std::vector CodeFreq;
445
446 PerBlockIDStats()
447 : NumInstances(0), NumBits(0),
448 NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {}
449 };
450
451 static std::map BlockIDStats;
452
453 /// All bitcode analysis errors go through this function, making this a good
454 /// place to breakpoint if debugging.
455 static bool ReportError(const Twine &Err) {
456 WithColor::error() << Err << "\n";
457 return true;
458 }
459
460 static bool ReportError(Error &&Err) {
461 return ReportError(toString(std::move(Err)));
462 }
463
464 static bool decodeMetadataStringsBlob(StringRef Indent,
465 ArrayRef Record,
466 StringRef Blob) {
467 if (Blob.empty())
468 return true;
469
470 if (Record.size() != 2)
471 return true;
472
473 unsigned NumStrings = Record[0];
474 unsigned StringsOffset = Record[1];
475 outs() << " num-strings = " << NumStrings << " {\n";
476
477 StringRef Lengths = Blob.slice(0, StringsOffset);
478 SimpleBitstreamCursor R(Lengths);
479 StringRef Strings = Blob.drop_front(StringsOffset);
480 do {
481 if (R.AtEndOfStream())
482 return ReportError("bad length");
483
484 Expected MaybeSize = R.ReadVBR(6);
485 if (!MaybeSize)
486 return ReportError(MaybeSize.takeError());
487 uint32_t Size = MaybeSize.get();
488 if (Strings.size() < Size)
489 return ReportError("truncated chars");
490
491 outs() << Indent << " '";
492 outs().write_escaped(Strings.slice(0, Size), /*hex=*/true);
493 outs() << "'\n";
494 Strings = Strings.drop_front(Size);
495 } while (--NumStrings);
496
497 outs() << Indent << " }";
498 return false;
499 }
500
501 static bool decodeBlob(unsigned Code, unsigned BlockID, StringRef Indent,
502 ArrayRef Record, StringRef Blob) {
503 if (BlockID != bitc::METADATA_BLOCK_ID)
504 return true;
505 if (Code != bitc::METADATA_STRINGS)
506 return true;
507
508 return decodeMetadataStringsBlob(Indent, Record, Blob);
509 }
510
511 /// ParseBlock - Read a block, updating statistics, etc.
512 static bool ParseBlock(BitstreamCursor &Stream, BitstreamBlockInfo &BlockInfo,
513 unsigned BlockID, unsigned IndentLevel,
514 CurStreamTypeType CurStreamType) {
515 std::string Indent(IndentLevel*2, ' ');
516 uint64_t BlockBitStart = Stream.GetCurrentBitNo();
517
518 // Get the statistics for this BlockID.
519 PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
520
521 BlockStats.NumInstances++;
522
523 // BLOCKINFO is a special part of the stream.
524 bool DumpRecords = Dump;
525 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
526 if (Dump) outs() << Indent << "\n";
527 Expected> MaybeNewBlockInfo =
528 Stream.ReadBlockInfoBlock(/*ReadBlockInfoNames=*/true);
529 if (!MaybeNewBlockInfo)
530 return ReportError(MaybeNewBlockInfo.takeError());
531 Optional NewBlockInfo =
532 std::move(MaybeNewBlockInfo.get());
533 if (!NewBlockInfo)
534 return ReportError("Malformed BlockInfoBlock");
535 BlockInfo = std::move(*NewBlockInfo);
536 if (Error Err = Stream.JumpToBit(BlockBitStart))
537 return ReportError(std::move(Err));
538 // It's not really interesting to dump the contents of the blockinfo block.
539 DumpRecords = false;
540 }
541
542 unsigned NumWords = 0;
543 if (Error Err = Stream.EnterSubBlock(BlockID, &NumWords))
544 return ReportError(std::move(Err));
545
546 // Keep it for later, when we see a MODULE_HASH record
547 uint64_t BlockEntryPos = Stream.getCurrentByteNo();
548
549 const char *BlockName = nullptr;
550 if (DumpRecords) {
551 outs() << Indent << "<";
552 if ((BlockName = GetBlockName(BlockID, BlockInfo, CurStreamType)))
553 outs() << BlockName;
554 else
555 outs() << "UnknownBlock" << BlockID;
556
557 if (NonSymbolic && BlockName)
558 outs() << " BlockID=" << BlockID;
559
560 outs() << " NumWords=" << NumWords
561 << " BlockCodeSize=" << Stream.getAbbrevIDWidth() << ">\n";
562 }
563
564 SmallVector Record;
565
566 // Keep the offset to the metadata index if seen.
567 uint64_t MetadataIndexOffset = 0;
568
569 // Read all the records for this block.
570 while (1) {
571 if (Stream.AtEndOfStream())
572 return ReportError("Premature end of bitstream");
573
574 uint64_t RecordStartBit = Stream.GetCurrentBitNo();
575
576 Expected MaybeEntry =
577 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
578 if (!MaybeEntry)
579 return ReportError(MaybeEntry.takeError());
580 BitstreamEntry Entry = MaybeEntry.get();
581
582 switch (Entry.Kind) {
583 case BitstreamEntry::Error:
584 return ReportError("malformed bitcode file");
585 case BitstreamEntry::EndBlock: {
586 uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
587 BlockStats.NumBits += BlockBitEnd-BlockBitStart;
588 if (DumpRecords) {
589 outs() << Indent << "
590 if (BlockName)
591 outs() << BlockName << ">\n";
592 else
593 outs() << "UnknownBlock" << BlockID << ">\n";
594 }
595 return false;
596 }
597
598 case BitstreamEntry::SubBlock: {
599 uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
600 if (ParseBlock(Stream, BlockInfo, Entry.ID, IndentLevel + 1,
601 CurStreamType))
602 return true;
603 ++BlockStats.NumSubBlocks;
604 uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
605
606 // Don't include subblock sizes in the size of this block.
607 BlockBitStart += SubBlockBitEnd-SubBlockBitStart;
608 continue;
609 }
610 case BitstreamEntry::Record:
611 // The interesting case.
612 break;
613 }
614
615 if (Entry.ID == bitc::DEFINE_ABBREV) {
616 if (Error Err = Stream.ReadAbbrevRecord())
617 return ReportError(std::move(Err));
618 ++BlockStats.NumAbbrevs;
619 continue;
620 }
621
622 Record.clear();
623
624 ++BlockStats.NumRecords;
625
626 StringRef Blob;
627 uint64_t CurrentRecordPos = Stream.GetCurrentBitNo();
628 Expected MaybeCode = Stream.readRecord(Entry.ID, Record, &Blob);
629 if (!MaybeCode)
630 return ReportError(MaybeCode.takeError());
631 unsigned Code = MaybeCode.get();
632
633 // Increment the # occurrences of this code.
634 if (BlockStats.CodeFreq.size() <= Code)
635 BlockStats.CodeFreq.resize(Code+1);
636 BlockStats.CodeFreq[Code].NumInstances++;
637 BlockStats.CodeFreq[Code].TotalBits +=
638 Stream.GetCurrentBitNo()-RecordStartBit;
639 if (Entry.ID != bitc::UNABBREV_RECORD) {
640 BlockStats.CodeFreq[Code].NumAbbrev++;
641 ++BlockStats.NumAbbreviatedRecords;
642 }
643
644 if (DumpRecords) {
645 outs() << Indent << " <";
646 if (const char *CodeName =
647 GetCodeName(Code, BlockID, BlockInfo, CurStreamType))
648 outs() << CodeName;
649 else
650 outs() << "UnknownCode" << Code;
651 if (NonSymbolic && GetCodeName(Code, BlockID, BlockInfo, CurStreamType))
652 outs() << " codeid=" << Code;
653 const BitCodeAbbrev *Abbv = nullptr;
654 if (Entry.ID != bitc::UNABBREV_RECORD) {
655 Abbv = Stream.getAbbrev(Entry.ID);
656 outs() << " abbrevid=" << Entry.ID;
657 }
658
659 for (unsigned i = 0, e = Record.size(); i != e; ++i)
660 outs() << " op" << i << "=" << (int64_t)Record[i];
661
662 // If we found a metadata index, let's verify that we had an offset before
663 // and validate its forward reference offset was correct!
664 if (BlockID == bitc::METADATA_BLOCK_ID) {
665 if (Code == bitc::METADATA_INDEX_OFFSET) {
666 if (Record.size() != 2)
667 outs() << "(Invalid record)";
668 else {
669 auto Offset = Record[0] + (Record[1] << 32);
670 MetadataIndexOffset = Stream.GetCurrentBitNo() + Offset;
671 }
672 }
673 if (Code == bitc::METADATA_INDEX) {
674 outs() << " (offset ";
675 if (MetadataIndexOffset == RecordStartBit)
676 outs() << "match)";
677 else
678 outs() << "mismatch: " << MetadataIndexOffset << " vs "
679 << RecordStartBit << ")";
680 }
681 }
682
683 // If we found a module hash, let's verify that it matches!
684 if (BlockID == bitc::MODULE_BLOCK_ID && Code == bitc::MODULE_CODE_HASH &&
685 !CheckHash.empty()) {
686 if (Record.size() != 5)
687 outs() << " (invalid)";
688 else {
689 // Recompute the hash and compare it to the one in the bitcode
690 SHA1 Hasher;
691 StringRef Hash;
692 Hasher.update(CheckHash);
693 {
694 int BlockSize = (CurrentRecordPos / 8) - BlockEntryPos;
695 auto Ptr = Stream.getPointerToByte(BlockEntryPos, BlockSize);
696 Hasher.update(ArrayRef(Ptr, BlockSize));
697 Hash = Hasher.result();
698 }
699 SmallString<20> RecordedHash;
700 RecordedHash.resize(20);
701 int Pos = 0;
702 for (auto &Val : Record) {
703 assert(!(Val >> 32) && "Unexpected high bits set");
704 RecordedHash[Pos++] = (Val >> 24) & 0xFF;
705 RecordedHash[Pos++] = (Val >> 16) & 0xFF;
706 RecordedHash[Pos++] = (Val >> 8) & 0xFF;
707 RecordedHash[Pos++] = (Val >> 0) & 0xFF;
708 }
709 if (Hash == RecordedHash)
710 outs() << " (match)";
711 else
712 outs() << " (!mismatch!)";
713 }
714 }
715
716 outs() << "/>";
717
718 if (Abbv) {
719 for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i != e; ++i) {
720 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
721 if (!Op.isEncoding() || Op.getEncoding() != BitCodeAbbrevOp::Array)
722 continue;
723 assert(i + 2 == e && "Array op not second to last");
724 std::string Str;
725 bool ArrayIsPrintable = true;
726 for (unsigned j = i - 1, je = Record.size(); j != je; ++j) {
727 if (!isPrint(static_cast(Record[j]))) {
728 ArrayIsPrintable = false;
729 break;
730 }
731 Str += (char)Record[j];
732 }
733 if (ArrayIsPrintable)
734 outs() << " record string = '" << Str << "'";
735 break;
736 }
737 }
738
739 if (Blob.data() && decodeBlob(Code, BlockID, Indent, Record, Blob)) {
740 outs() << " blob data = ";
741 if (ShowBinaryBlobs) {
742 outs() << "'";
743 outs().write_escaped(Blob, /*hex=*/true) << "'";
744 } else {
745 bool BlobIsPrintable = true;
746 for (unsigned i = 0, e = Blob.size(); i != e; ++i)
747 if (!isPrint(static_cast(Blob[i]))) {
748 BlobIsPrintable = false;
749 break;
750 }
751
752 if (BlobIsPrintable)
753 outs() << "'" << Blob << "'";
754 else
755 outs() << "unprintable, " << Blob.size() << " bytes.";
756 }
757 }
758
759 outs() << "\n";
760 }
761
762 // Make sure that we can skip the current record.
763 if (Error Err = Stream.JumpToBit(CurrentRecordPos))
764 return ReportError(std::move(Err));
765 if (Expected Skipped = Stream.skipRecord(Entry.ID))
766 ; // Do nothing.
767 else
768 return ReportError(Skipped.takeError());
769 }
770 }
771
772 static void PrintSize(double Bits) {
773 outs() << format("%.2f/%.2fB/%luW", Bits, Bits/8,(unsigned long)(Bits/32));
774 }
775 static void PrintSize(uint64_t Bits) {
776 outs() << format("%lub/%.2fB/%luW", (unsigned long)Bits,
777 (double)Bits/8, (unsigned long)(Bits/32));
778 }
779
780 static Expected ReadSignature(BitstreamCursor &Stream) {
781 auto tryRead = [&Stream](char &Dest, size_t size) -> Error {
782 if (Expected MaybeWord = Stream.Read(size))
783 Dest = MaybeWord.get();
784 else
785 return MaybeWord.takeError();
786 return Error::success();
787 };
788
789 char Signature[6];
790 if (Error Err = tryRead(Signature[0], 8))
791 return std::move(Err);
792 if (Error Err = tryRead(Signature[1], 8))
793 return std::move(Err);
794
795 // Autodetect the file contents, if it is one we know.
796 if (Signature[0] == 'C' && Signature[1] == 'P') {
797 if (Error Err = tryRead(Signature[2], 8))
798 return std::move(Err);
799 if (Error Err = tryRead(Signature[3], 8))
800 return std::move(Err);
801 if (Signature[2] == 'C' && Signature[3] == 'H')
802 return ClangSerializedASTBitstream;
803 } else if (Signature[0] == 'D' && Signature[1] == 'I') {
804 if (Error Err = tryRead(Signature[2], 8))
805 return std::move(Err);
806 if (Error Err = tryRead(Signature[3], 8))
807 return std::move(Err);
808 if (Signature[2] == 'A' && Signature[3] == 'G')
809 return ClangSerializedDiagnosticsBitstream;
810 } else {
811 if (Error Err = tryRead(Signature[2], 4))
812 return std::move(Err);
813 if (Error Err = tryRead(Signature[3], 4))
814 return std::move(Err);
815 if (Error Err = tryRead(Signature[4], 4))
816 return std::move(Err);
817 if (Error Err = tryRead(Signature[5], 4))
818 return std::move(Err);
819 if (Signature[0] == 'B' && Signature[1] == 'C' &&
820 Signature[2] == 0x0 && Signature[3] == 0xC &&
821 Signature[4] == 0xE && Signature[5] == 0xD)
822 return LLVMIRBitstream;
823 }
824 return UnknownBitstream;
825 }
826
827 static bool openBitcodeFile(StringRef Path,
828 std::unique_ptr &MemBuf,
829 BitstreamCursor &Stream,
830 CurStreamTypeType &CurStreamType) {
831 // Read the input file.
832 ErrorOr> MemBufOrErr =
833 MemoryBuffer::getFileOrSTDIN(Path);
834 if (std::error_code EC = MemBufOrErr.getError())
835 return ReportError(Twine("ReportError reading '") + Path + "': " + EC.message());
836 MemBuf = std::move(MemBufOrErr.get());
77 std::unique_ptr MemBuf = std::move(*MemBufOrErr);
83778
83879 if (MemBuf->getBufferSize() & 3)
839 return ReportError("Bitcode stream should be a multiple of 4 bytes in length");
840
841 const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
842 const unsigned char *EndBufPtr = BufPtr + MemBuf->getBufferSize();
843
844 // If we have a wrapper header, parse it and ignore the non-bc file contents.
845 // The magic number is 0x0B17C0DE stored in little endian.
846 if (isBitcodeWrapper(BufPtr, EndBufPtr)) {
847 if (MemBuf->getBufferSize() < BWH_HeaderSize)
848 return ReportError("Invalid bitcode wrapper header");
849
850 if (Dump) {
851 unsigned Magic = support::endian::read32le(&BufPtr[BWH_MagicField]);
852 unsigned Version = support::endian::read32le(&BufPtr[BWH_VersionField]);
853 unsigned Offset = support::endian::read32le(&BufPtr[BWH_OffsetField]);
854 unsigned Size = support::endian::read32le(&BufPtr[BWH_SizeField]);
855 unsigned CPUType = support::endian::read32le(&BufPtr[BWH_CPUTypeField]);
856
857 outs() << "
858 << " Magic=" << format_hex(Magic, 10)
859 << " Version=" << format_hex(Version, 10)
860 << " Offset=" << format_hex(Offset, 10)
861 << " Size=" << format_hex(Size, 10)
862 << " CPUType=" << format_hex(CPUType, 10) << "/>\n";
863 }
864
865 if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr, true))
866 return ReportError("Invalid bitcode wrapper header");
867 }
868
869 Stream = BitstreamCursor(ArrayRef(BufPtr, EndBufPtr));
870 Expected MaybeSignature = ReadSignature(Stream);
871 if (!MaybeSignature)
872 return ReportError(MaybeSignature.takeError());
873 CurStreamType = std::move(MaybeSignature.get());
874
875 return false;
80 return reportError(
81 "Bitcode stream should be a multiple of 4 bytes in length");
82 return std::move(MemBuf);
87683 }
877
878 /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
879 static int AnalyzeBitcode() {
880 std::unique_ptr StreamBuffer;
881 BitstreamCursor Stream;
882 BitstreamBlockInfo BlockInfo;
883 CurStreamTypeType CurStreamType;
884 if (openBitcodeFile(InputFilename, StreamBuffer, Stream, CurStreamType))
885 return true;
886 Stream.setBlockInfo(&BlockInfo);
887
888 // Read block info from BlockInfoFilename, if specified.
889 // The block info must be a top-level block.
890 if (!BlockInfoFilename.empty()) {
891 std::unique_ptr BlockInfoBuffer;
892 BitstreamCursor BlockInfoCursor;
893 CurStreamTypeType BlockInfoStreamType;
894 if (openBitcodeFile(BlockInfoFilename, BlockInfoBuffer, BlockInfoCursor,
895 BlockInfoStreamType))
896 return true;
897
898 while (!BlockInfoCursor.AtEndOfStream()) {
899 Expected MaybeCode = BlockInfoCursor.ReadCode();
900 if (!MaybeCode)
901 return ReportError(MaybeCode.takeError());
902 if (MaybeCode.get() != bitc::ENTER_SUBBLOCK)
903 return ReportError("Invalid record at top-level in block info file");
904
905 Expected MaybeBlockID = BlockInfoCursor.ReadSubBlockID();
906 if (!MaybeBlockID)
907 return ReportError(MaybeBlockID.takeError());
908 if (MaybeBlockID.get() == bitc::BLOCKINFO_BLOCK_ID) {
909 Expected> MaybeNewBlockInfo =
910 BlockInfoCursor.ReadBlockInfoBlock(/*ReadBlockInfoNames=*/true);
911 if (!MaybeNewBlockInfo)
912 return ReportError(MaybeNewBlockInfo.takeError());
913 Optional NewBlockInfo =
914 std::move(MaybeNewBlockInfo.get());
915 if (!NewBlockInfo)
916 return ReportError("Malformed BlockInfoBlock in block info file");
917 BlockInfo = std::move(*NewBlockInfo);
918 break;
919 }
920
921 if (Error Err = BlockInfoCursor.SkipBlock())
922 return ReportError(std::move(Err));
923 }
924 }
925
926 unsigned NumTopBlocks = 0;
927
928 // Parse the top-level structure. We only allow blocks at the top-level.
929 while (!Stream.AtEndOfStream()) {
930 Expected MaybeCode = Stream.ReadCode();
931 if (!MaybeCode)
932 return ReportError(MaybeCode.takeError());
933 if (MaybeCode.get() != bitc::ENTER_SUBBLOCK)
934 return ReportError("Invalid record at top-level");
935
936 Expected MaybeBlockID = Stream.ReadSubBlockID();
937 if (!MaybeBlockID)
938 return ReportError(MaybeBlockID.takeError());
939
940 if (ParseBlock(Stream, BlockInfo, MaybeBlockID.get(), 0, CurStreamType))
941 return true;
942 ++NumTopBlocks;
943 }
944
945 if (Dump) outs() << "\n\n";
946
947 uint64_t BufferSizeBits = Stream.getBitcodeBytes().size() * CHAR_BIT;
948 // Print a summary of the read file.
949 outs() << "Summary of " << InputFilename << ":\n";
950 outs() << " Total size: ";
951 PrintSize(BufferSizeBits);
952 outs() << "\n";
953 outs() << " Stream type: ";
954 switch (CurStreamType) {
955 case UnknownBitstream:
956 outs() << "unknown\n";
957 break;
958 case LLVMIRBitstream:
959 outs() << "LLVM IR\n";
960 break;
961 case ClangSerializedASTBitstream:
962 outs() << "Clang Serialized AST\n";
963 break;
964 case ClangSerializedDiagnosticsBitstream:
965 outs() << "Clang Serialized Diagnostics\n";
966 break;
967 }
968 outs() << " # Toplevel Blocks: " << NumTopBlocks << "\n";
969 outs() << "\n";
970
971 // Emit per-block stats.
972 outs() << "Per-block Summary:\n";
973 for (std::map::iterator I = BlockIDStats.begin(),
974 E = BlockIDStats.end(); I != E; ++I) {
975 outs() << " Block ID #" << I->first;
976 if (const char *BlockName =
977 GetBlockName(I->first, BlockInfo, CurStreamType))
978 outs() << " (" << BlockName << ")";
979 outs() << ":\n";
980
981 const PerBlockIDStats &Stats = I->second;
982 outs() << " Num Instances: " << Stats.NumInstances << "\n";
983 outs() << " Total Size: ";
984 PrintSize(Stats.NumBits);
985 outs() << "\n";
986 double pct = (Stats.NumBits * 100.0) / BufferSizeBits;
987 outs() << " Percent of file: " << format("%2.4f%%", pct) << "\n";
988 if (Stats.NumInstances > 1) {
989 outs() << " Average Size: ";
990 PrintSize(Stats.NumBits/(double)Stats.NumInstances);
991 outs() << "\n";
992 outs() << " Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
993 << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
994 outs() << " Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
995 << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
996 outs() << " Tot/Avg Records: " << Stats.NumRecords << "/"
997 << Stats.NumRecords/(double)Stats.NumInstances << "\n";
998 } else {
999 outs() << " Num SubBlocks: " << Stats.NumSubBlocks << "\n";
1000 outs() << " Num Abbrevs: " << Stats.NumAbbrevs << "\n";
1001 outs() << " Num Records: " << Stats.NumRecords << "\n";
1002 }
1003 if (Stats.NumRecords) {
1004 double pct = (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumRecords;
1005 outs() << " Percent Abbrevs: " << format("%2.4f%%", pct) << "\n";
1006 }
1007 outs() << "\n";
1008
1009 // Print a histogram of the codes we see.
1010 if (!NoHistogram && !Stats.CodeFreq.empty()) {
1011 std::vector > FreqPairs; //
1012 for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
1013 if (unsigned Freq = Stats.CodeFreq[i].NumInstances)
1014 FreqPairs.push_back(std::make_pair(Freq, i));
1015 llvm::stable_sort(FreqPairs);
1016 std::reverse(FreqPairs.begin(), FreqPairs.end());
1017
1018 outs() << "\tRecord Histogram:\n";
1019 outs() << "\t\t Count # Bits b/Rec % Abv Record Kind\n";
1020 for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
1021 const PerRecordStats &RecStats = Stats.CodeFreq[FreqPairs[i].second];
1022
1023 outs() << format("\t\t%7d %9lu",
1024 RecStats.NumInstances,
1025 (unsigned long)RecStats.TotalBits);
1026
1027 if (RecStats.NumInstances > 1)
1028 outs() << format(" %9.1f",
1029 (double)RecStats.TotalBits/RecStats.NumInstances);
1030 else
1031 outs() << " ";
1032
1033 if (RecStats.NumAbbrev)
1034 outs() <<
1035 format(" %7.2f",
1036 (double)RecStats.NumAbbrev/RecStats.NumInstances*100);
1037 else
1038 outs() << " ";
1039
1040 outs() << " ";
1041 if (const char *CodeName = GetCodeName(FreqPairs[i].second, I->first,
1042 BlockInfo, CurStreamType))
1043 outs() << CodeName << "\n";
1044 else
1045 outs() << "UnknownCode" << FreqPairs[i].second << "\n";
1046 }
1047 outs() << "\n";
1048
1049 }
1050 }
1051 return 0;
1052 }
1053
105484
105585 int main(int argc, char **argv) {
105686 InitLLVM X(argc, argv);
105787 cl::ParseCommandLineOptions(argc, argv, "llvm-bcanalyzer file analyzer\n");
1058 return AnalyzeBitcode();
88 ExitOnError ExitOnErr("llvm-bcanalyzer: ");
89
90 std::unique_ptr MB = ExitOnErr(openBitcodeFile(InputFilename));
91 std::unique_ptr BlockInfoMB = nullptr;
92 if (!BlockInfoFilename.empty())
93 BlockInfoMB = ExitOnErr(openBitcodeFile(BlockInfoFilename));
94
95 BitcodeAnalyzer BA(MB->getBuffer(),
96 BlockInfoMB ? Optional(BlockInfoMB->getBuffer())
97 : None);
98
99 BCDumpOptions O(outs());
100 O.Histogram = !NoHistogram;
101 O.Symbolic = !NonSymbolic;
102 O.ShowBinaryBlobs = ShowBinaryBlobs;
103
104 ExitOnErr(
105 BA.analyze(O, CheckHash.empty() ? None : Optional(CheckHash)));
106
107 if (Dump)
108 outs() << "\n\n";
109
110 BA.printStats(O, StringRef(InputFilename.getValue()));
111 return 0;
1059112 }