diff --git a/llvm/lib/Bitcode/Reader/BitcodeReader.cpp b/llvm/lib/Bitcode/Reader/BitcodeReader.cpp --- a/llvm/lib/Bitcode/Reader/BitcodeReader.cpp +++ b/llvm/lib/Bitcode/Reader/BitcodeReader.cpp @@ -5394,6 +5394,36 @@ } } + // "Upgrade" older incorrect branch weights by dropping them. + for (auto &I : instructions(F)) { + if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) { + if (MD->getOperand(0) != nullptr && isa(MD->getOperand(0))) { + MDString *MDS = cast(MD->getOperand(0)); + StringRef ProfName = MDS->getString(); + // Check consistency of !prof branch_weights metadata. + if (!ProfName.equals("branch_weights")) + continue; + unsigned ExpectedNumOperands = 0; + if (BranchInst *BI = dyn_cast(&I)) + ExpectedNumOperands = BI->getNumSuccessors(); + else if (SwitchInst *SI = dyn_cast(&I)) + ExpectedNumOperands = SI->getNumSuccessors(); + else if (isa(&I)) + ExpectedNumOperands = 1; + else if (IndirectBrInst *IBI = dyn_cast(&I)) + ExpectedNumOperands = IBI->getNumDestinations(); + else if (isa(&I)) + ExpectedNumOperands = 2; + else + continue; // ignore and continue. + + // If branch weight doesn't match, just strip branch weight. + if (MD->getNumOperands() != 1 + ExpectedNumOperands) + I.setMetadata(LLVMContext::MD_prof, nullptr); + } + } + } + // Look for functions that rely on old function attribute behavior. UpgradeFunctionAttributes(*F); diff --git a/llvm/test/Bitcode/Inputs/branch-weight.bc b/llvm/test/Bitcode/Inputs/branch-weight.bc new file mode 100644 index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 GIT binary patch literal 0 Hc$@