Skip to content

Missed optimization: remap sadd.sat(x, C) constant compares to input-side checks #9

Description

@ParkHanbum

Summary

LLVM appears to miss folds for constant comparisons against signed saturating
add with a constant RHS:

%sat = call iN @llvm.sadd.sat.iN(iN %x, iN C)
%cmp = icmp pred iN %sat, K

Because signed saturating add by a constant is monotonic, many constant
comparisons can be remapped to direct threshold compares or small range checks
on %x.

Examples

sadd.sat(x, -1) > -1  ->  x > 0
sadd.sat(x,  8) <  0  ->  x < -8
sadd.sat(x,  4) >  0  ->  x > -4
sadd.sat(x, -1) u> 15 ->  x < 1 || x > 16

The last case is a corpus-backed unsigned comparison against the signed
saturating-add result; it becomes a range-complement check rather than a single
signed threshold compare.

Minimal IR

declare i32 @llvm.sadd.sat.i32(i32, i32)
declare i64 @llvm.sadd.sat.i64(i64, i64)

define i1 @current_sgt(i32 %x) {
entry:
  %sat = call i32 @llvm.sadd.sat.i32(i32 %x, i32 -1)
  %cmp = icmp sgt i32 %sat, -1
  ret i1 %cmp
}

define i1 @folded_sgt(i32 %x) {
entry:
  %cmp = icmp sgt i32 %x, 0
  ret i1 %cmp
}

define i1 @current_slt(i64 %x) {
entry:
  %sat = call i64 @llvm.sadd.sat.i64(i64 %x, i64 8)
  %cmp = icmp slt i64 %sat, 0
  ret i1 %cmp
}

define i1 @folded_slt(i64 %x) {
entry:
  %cmp = icmp slt i64 %x, -8
  ret i1 %cmp
}

The local POC also includes the ugt range-complement case.

Corpus Evidence

Full optimized corpus scan found 207 reviewed true positives across 6 files and
4 projects.

Project distribution:

  • yara-x-rs: 176
  • llvm: 27
  • icu: 3
  • zed-rs: 1

Predicate distribution:

  • slt: 189
  • sgt: 17
  • ugt: 1

Saturating-add constant distribution:

  • 2: 112
  • 8: 32
  • 14: 32
  • -1: 23
  • 1: 6
  • -2: 1
  • 4: 1

Representative locations:

Project File Line Predicate C
icu bench/icu/optimized/number_decimalquantity.ll 5687 sgt -1
icu bench/icu/optimized/number_decimalquantity.ll 5701 ugt -1
llvm bench/llvm/optimized/AArch64TargetTransformInfo.ll 5689 sgt 4
llvm bench/llvm/optimized/RISCVTargetTransformInfo.ll 3730 slt 1
yara-x-rs bench/yara-x-rs/optimized/98ju2vcu3mcgze6k61u00b6zf.ll 28227 slt 8

Suggested Fold Scope

Initial scope:

  • signed saturating add intrinsic;
  • constant RHS C;
  • constant compare threshold K;
  • predicates represented by the corpus: slt, sgt, and range-derived ugt.

Non-Goals

This draft does not claim unsigned saturating-add folds, variable C, variable
compare thresholds, or an LLVM implementation strategy.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions