Skip to content

Commit 7c2d220

Browse files
committed
[InstCombine] Prevent infinite loop with two shifts
The following pattern: `(C2 << X) << C1` will usually be transformed into `(C2 << C1) << X`, essentially swapping `X` and `C1`. However, this should not only done when `C1` is an immediate constant, otherwise this can lead to both constants being swapped forever This fixes #118798
1 parent ff78cd5 commit 7c2d220

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -427,7 +427,8 @@ Instruction *InstCombinerImpl::commonShiftTransforms(BinaryOperator &I) {
427427
if (Instruction *R = FoldOpIntoSelect(I, SI))
428428
return R;
429429

430-
if (Constant *CUI = dyn_cast<Constant>(Op1))
430+
Constant *CUI;
431+
if (match(Op1, m_ImmConstant(CUI)))
431432
if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
432433
return Res;
433434

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
2+
; RUN: opt < %s -passes=instcombine -S | FileCheck %s
3+
4+
@c = external constant i8
5+
@c2 = external constant i8
6+
7+
define i16 @testfunc() {
8+
; CHECK-LABEL: @testfunc(
9+
; CHECK-NEXT: entry:
10+
; CHECK-NEXT: [[TMP0:%.*]] = shl nuw i64 1, ptrtoint (ptr @c2 to i64)
11+
; CHECK-NEXT: [[TMP1:%.*]] = shl i64 [[TMP0]], ptrtoint (ptr @c to i64)
12+
; CHECK-NEXT: [[TMP2:%.*]] = inttoptr i64 [[TMP1]] to ptr
13+
; CHECK-NEXT: [[TMP3:%.*]] = load i16, ptr [[TMP2]], align 1
14+
; CHECK-NEXT: ret i16 [[TMP3]]
15+
;
16+
entry:
17+
%0 = shl i64 1, ptrtoint (ptr @c2 to i64)
18+
%1 = shl i64 %0, ptrtoint (ptr @c to i64)
19+
%2 = inttoptr i64 %1 to ptr
20+
%3 = load i16, ptr %2, align 1
21+
ret i16 %3
22+
}

0 commit comments

Comments
 (0)