Skip to content

[InstCombine] Fix miscompilation in sinkNotIntoLogicalOp #142727

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4513,6 +4513,12 @@ bool InstCombinerImpl::sinkNotIntoLogicalOp(Instruction &I) {
if (Op0 == Op1)
return false;

// If one of the operands is a user of the other,
// freelyInvert->freelyInvertAllUsersOf will change the operands of I, which
// may cause miscompilation.
if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
return false;

Instruction::BinaryOps NewOpc =
match(&I, m_LogicalAnd()) ? Instruction::Or : Instruction::And;
bool IsBinaryOp = isa<BinaryOperator>(I);
Expand Down
43 changes: 43 additions & 0 deletions llvm/test/Transforms/InstCombine/pr142518.ll
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
; NOTE: Assertions have been autogenerated by utils/update_test_checks.py UTC_ARGS: --version 5
; RUN: opt -S -passes=instcombine < %s | FileCheck %s

define i8 @pr142518(ptr %p, i8 %x, i1 %c) "instcombine-no-verify-fixpoint" {
; CHECK-LABEL: define i8 @pr142518(
; CHECK-SAME: ptr [[P:%.*]], i8 [[X:%.*]], i1 [[C:%.*]]) #[[ATTR0:[0-9]+]] {
; CHECK-NEXT: [[ENTRY:.*:]]
; CHECK-NEXT: [[CMP1:%.*]] = icmp slt i8 [[X]], -1
; CHECK-NEXT: br label %[[LOOP:.*]]
; CHECK: [[LOOP]]:
; CHECK-NEXT: [[NOT1:%.*]] = xor i1 [[CMP1]], true
; CHECK-NEXT: [[OR:%.*]] = or i1 [[CMP1]], [[NOT1]]
; CHECK-NEXT: [[CMP:%.*]] = xor i1 [[OR]], true
; CHECK-NEXT: [[EXT2:%.*]] = zext i1 [[CMP]] to i8
; CHECK-NEXT: store i8 [[EXT2]], ptr [[P]], align 1
; CHECK-NEXT: br i1 false, label %[[LOOP]], label %[[EXIT:.*]]
; CHECK: [[EXIT]]:
; CHECK-NEXT: [[NOT3:%.*]] = xor i1 [[OR]], true
; CHECK-NEXT: [[EXT3:%.*]] = zext i1 [[NOT3]] to i8
; CHECK-NEXT: ret i8 [[EXT3]]
;
entry:
%flag = alloca i8, align 1
%cmp = icmp slt i8 %x, -1
br label %loop

loop:
%phi = phi i1 [ %cmp, %entry ], [ %c, %loop ]
%not1 = xor i1 %phi, true
%or = or i1 %cmp, %not1
%not2 = xor i1 %or, true
%ext2 = zext i1 %not2 to i8
store i8 %ext2, ptr %p, align 1
store i8 1, ptr %flag, align 1
%flagv = load i8, ptr %flag, align 1
%cond = icmp eq i8 %flagv, 0
br i1 %cond, label %loop, label %exit

exit:
%not3 = xor i1 %or, true
%ext3 = zext i1 %not3 to i8
ret i8 %ext3
}
Loading