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