Skip to content

[InstCombine] optimize compares of abs/nabs into union/intersection of compares #38866

@rotateright

Description

@rotateright
Bugzilla Link 39518
Version trunk
OS All
CC @RKSimon

Extended Description

Adjusting the bug-inducing code from bug 39510 to the more likely (?) pattern shows an opportunity:

define i1 @​abs_test(i32 %a) {
%cmp = icmp slt i32 %a, 0
%sub = sub nsw i32 0, %a
%abs = select i1 %cmp, i32 %sub, i32 %a
%r = icmp eq i32 %abs, 2
ret i1 %r
}

This can be reduced to logic-of-icmps:

https://rise4fun.com/Alive/FjLJ

define i1 @​abs_test_better(i32 %a) {
%cmp1 = icmp eq i32 %a, 2
%cmp2 = icmp eq i32 %a, -2
%r = or i1 %cmp1, %cmp2
ret i1 %r
}


More generally, we should be forming union/intersection patterns:
https://rise4fun.com/Alive/Rqq0

Name: union
%cmp = icmp slt i32 %a, 0
%sub = sub nsw i32 0, %a
%abs = select i1 %cmp, i32 %sub, i32 %a
%r = icmp sgt i32 %abs, 42
=>
%cmp1 = icmp sgt i32 %a, 42
%cmp2 = icmp slt i32 %a, -42
%r = or i1 %cmp1, %cmp2

Name: intersection
%cmp = icmp slt i32 %a, 0
%sub = sub nsw i32 0, %a
%abs = select i1 %cmp, i32 %sub, i32 %a
%r = icmp slt i32 %abs, 42
=>
%cmp1 = icmp slt i32 %a, 42
%cmp2 = icmp sgt i32 %a, -42
%r = and i1 %cmp1, %cmp2


I don't have an immediate plan to work on this, but it probably needs a codegen reversal before the IR canonicalization based on whether a target has a legal ISD::ABS node.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugzillaIssues migrated from bugzillallvm:instcombineCovers the InstCombine, InstSimplify and AggressiveInstCombine passes

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions