llvm / llvm/llvm-project

[InstCombine] Missed sadd.sat operand-bound compare under nonnegative RHS guard

Open
#202,510 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

llvm:instcombine missed-optimization
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

InstCombine folds the analogous add nsw case, but misses the same operand-bound fact for signed saturating addition.

Reduced IR:

define i1 @sat(i32 %x, i32 %y) {
entry:
  %ynonneg = icmp sge i32 %y, 0
  %s = call i32 @llvm.sadd.sat.i32(i32 %x, i32 %y)
  %ok = icmp sge i32 %s, %x
  %ret = select i1 %ynonneg, i1 %ok, i1 true
  ret i1 %ret
}

Expected (alive2: https://alive2.llvm.org/ce/z/bc3iF9):

define i1 @sat(i32 %x, i32 %y) {
entry:
  ret i1 true
}

Current result with opt -S -passes=instcombine keeps the dynamic test (https://godbolt.org/z/Y1qv6G8Yx):

define i1 @sat(i32 %x, i32 %y) {
entry:
  %ynonneg = icmp slt i32 %y, 0
  %s = tail call i32 @llvm.sadd.sat.i32(i32 %x, i32 %y)
  %ok = icmp sge i32 %s, %x
  %ret = select i1 %ynonneg, i1 true, i1 %ok
  ret i1 %ret
}

This is a missed opt for the analogous add nsw case is already handled:

define i1 @nsw(i32 %x, i32 %y) {
entry:
  %ynonneg = icmp sge i32 %y, 0
  %s = add nsw i32 %x, %y
  %ok = icmp sge i32 %s, %x
  %ret = select i1 %ynonneg, i1 %ok, i1 true
  ret i1 %ret
}

opt -S -passes=instcombine folds this to (https://godbolt.org/z/a6qafEx7a):

define i1 @nsw(i32 %x, i32 %y) {
entry:
  ret i1 true
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running opt -S -passes=instcombine on the reduced IR and tracing the existing analogous add nsw handling in InstCombine. The work is done when the signed saturating-add case folds to ret i1 true under the nonnegative RHS guard and a regression test covers the reduction.

Written by the indexing model from the issue text.

Assessment

Domain
compilers
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
62/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.