diff --git a/llvm/lib/IR/Verifier.cpp b/llvm/lib/IR/Verifier.cpp --- a/llvm/lib/IR/Verifier.cpp +++ b/llvm/lib/IR/Verifier.cpp @@ -813,6 +813,9 @@ if (!MDNodes.insert(&MD).second) return; + Assert(&MD.getContext() == &Context, + "MDNode context does not match Module context!", &MD); + switch (MD.getMetadataID()) { default: llvm_unreachable("Invalid MDNode subclass"); diff --git a/llvm/unittests/IR/VerifierTest.cpp b/llvm/unittests/IR/VerifierTest.cpp --- a/llvm/unittests/IR/VerifierTest.cpp +++ b/llvm/unittests/IR/VerifierTest.cpp @@ -238,5 +238,20 @@ } } +TEST(VerifierTest, MDNodeWrongContext) { + LLVMContext C1, C2; + auto Node = MDNode::get(C1, None); + + Module M("M", C2); + auto NamedNode = M.getOrInsertNamedMetadata("test"); + NamedNode->addOperand(Node); + + std::string Error; + raw_string_ostream ErrorOS(Error); + EXPECT_TRUE(verifyModule(M, &ErrorOS)); + EXPECT_TRUE(StringRef(ErrorOS.str()) + .startswith("MDNode context does not match Module context!")); +} + } // end anonymous namespace } // end namespace llvm