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