[llvm] [CodeGenPrepare] Fix infinite loop with same-type bitcasts (PR #176694)
via llvm-commits
llvm-commits at lists.llvm.org
Sun Jan 18 22:42:04 PST 2026
https://github.com/nataliakokoromyti updated https://github.com/llvm/llvm-project/pull/176694
>From 8ce60f3aa54a6f65daebe2e75a3109f7247638a8 Mon Sep 17 00:00:00 2001
From: nataliakokoromyti <nataliakokoromyti at gmail.com>
Date: Sun, 18 Jan 2026 22:10:34 -0800
Subject: [PATCH] [CodeGenPrepare] Fix infinite loop with same-type bitcasts
OptimizeNoopCopyExpression was sinking same-type bitcasts (e.g. bitcast
i32 to i32) which would then be reintroduced by optimizePhiType, causing
an infinite loop.
Fix this by detecting casts where source and destination types are
identical and replacing them with their operand instead of sinking.
Fixes #176688
---
llvm/lib/CodeGen/CodeGenPrepare.cpp | 9 +++++++
.../X86/codegenprepare-hang-bitcast-phi.ll | 25 +++++++++++++++++++
2 files changed, 34 insertions(+)
create mode 100644 llvm/test/CodeGen/X86/codegenprepare-hang-bitcast-phi.ll
diff --git a/llvm/lib/CodeGen/CodeGenPrepare.cpp b/llvm/lib/CodeGen/CodeGenPrepare.cpp
index 1b3fbe45bdb55..2b54a3b6f6d17 100644
--- a/llvm/lib/CodeGen/CodeGenPrepare.cpp
+++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp
@@ -1468,6 +1468,15 @@ static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
return false;
}
+ // If the cast is between identical types, just replace it with its operand.
+ // This avoids infinite loops with optimizePhiType which may reintroduce such
+ // casts.
+ if (CI->getOperand(0)->getType() == CI->getType()) {
+ CI->replaceAllUsesWith(CI->getOperand(0));
+ CI->eraseFromParent();
+ return true;
+ }
+
// If this is a noop copy,
EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
EVT DstVT = TLI.getValueType(DL, CI->getType());
diff --git a/llvm/test/CodeGen/X86/codegenprepare-hang-bitcast-phi.ll b/llvm/test/CodeGen/X86/codegenprepare-hang-bitcast-phi.ll
new file mode 100644
index 0000000000000..0a289d8a42da8
--- /dev/null
+++ b/llvm/test/CodeGen/X86/codegenprepare-hang-bitcast-phi.ll
@@ -0,0 +1,25 @@
+; RUN: llc -O2 -march=x86-64 -o /dev/null %s
+; Check that CodeGenPrepare does not hang on this input.
+; This was caused by an infinite loop between OptimizeNoopCopyExpression
+; and optimizePhiType when handling same-type bitcasts.
+
+define void @foo(ptr %p) {
+entry:
+ %val = load i32, ptr %p
+ br i1 undef, label %bb1, label %bb2
+
+bb1:
+ %c1 = bitcast i32 %val to i32
+ br label %bb3
+
+bb2:
+ %c2 = bitcast i32 %val to i32
+ %c3 = bitcast i32 %c2 to i32
+ br label %bb3
+
+bb3:
+ %phi = phi i32 [%c3, %bb2], [%c1, %bb1]
+ %c4 = bitcast i32 %phi to i32
+ store i32 %c4, ptr %p
+ ret void
+}
More information about the llvm-commits
mailing list