Skip to content

Commit 5b75d5d

Browse files
Fix crash when printing instructions that have a metadata attached but no parent. (microsoft#7036)
Applying patch from upstream LLVM: llvm/llvm-project@b9b50aa#diff-69d28d03f6d27b8c800ff1dafb34ede6999a3165c109263e7da48dbbdf964f0aR9 --------- Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
1 parent d39324e commit 5b75d5d

File tree

3 files changed

+39
-1
lines changed

3 files changed

+39
-1
lines changed

lib/IR/AsmWriter.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3049,7 +3049,7 @@ void AssemblyWriter::printMetadataAttachments(
30493049
return;
30503050

30513051
if (MDNames.empty())
3052-
TheModule->getMDKindNames(MDNames);
3052+
MDs[0].second->getContext().getMDKindNames(MDNames);
30533053

30543054
for (const auto &I : MDs) {
30553055
unsigned Kind = I.first;

unittests/IR/AsmWriterTest.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
//===- llvm/unittest/IR/AsmWriter.cpp - AsmWriter tests -------------------===//
2+
//
3+
// The LLVM Compiler Infrastructure
4+
//
5+
// This file is distributed under the University of Illinois Open Source
6+
// License. See LICENSE.TXT for details.
7+
//
8+
//===----------------------------------------------------------------------===//
9+
#include "llvm/IR/Function.h"
10+
#include "llvm/IR/IRBuilder.h"
11+
#include "llvm/IR/LLVMContext.h"
12+
#include "llvm/IR/MDBuilder.h"
13+
#include "llvm/IR/Module.h"
14+
#include "gtest/gtest.h"
15+
16+
using namespace llvm;
17+
18+
namespace {
19+
20+
TEST(AsmWriterTest, DebugPrintDetachedInstruction) {
21+
22+
// PR24852: Ensure that an instruction can be printed even when it
23+
// has metadata attached but no parent.
24+
LLVMContext Ctx;
25+
auto Ty = Type::getInt32Ty(Ctx);
26+
auto Undef = UndefValue::get(Ty);
27+
std::unique_ptr<BinaryOperator> Add(BinaryOperator::CreateAdd(Undef, Undef));
28+
Add->setMetadata(
29+
"", MDNode::get(Ctx, {ConstantAsMetadata::get(ConstantInt::get(Ty, 1))}));
30+
std::string S;
31+
raw_string_ostream OS(S);
32+
Add->print(OS);
33+
std::size_t r = OS.str().find("<badref> = add i32 undef, undef, !<empty");
34+
EXPECT_TRUE(r != std::string::npos);
35+
}
36+
37+
} // namespace

unittests/IR/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ set(LLVM_LINK_COMPONENTS
77
)
88

99
set(IRSources
10+
AsmWriterTest.cpp
1011
AttributesTest.cpp
1112
ConstantRangeTest.cpp
1213
ConstantsTest.cpp

0 commit comments

Comments
 (0)