Skip to content

Optimizing functions that compute absolute values of x #61613

Closed
@k-arrows

Description

@k-arrows

Test code:

#include <stdlib.h>
#include <math.h>

float f1(float x)
{
    return fabsf(x);
}

float f2(float x)
{
    return sqrtf(x * x);
}

float f3(float x)
{
    return (x >= 0.0f) ? x : -x;
}

float f4(float x)
{
    if(x >= 0.0f) return x;
    else return -x;
}

GCC:

f1:
        fabs    s0, s0
        ret
f2:
        fmul    s0, s0, s0
        fsqrt   s0, s0
        ret
f3:
        fabs    s0, s0
        ret
f4:
        fabs    s0, s0
        ret

Clang:

f1:                                     // @f1
        fabs    s0, s0
        ret
f2:                                     // @f2
        fabs    s0, s0
        ret
f3:                                     // @f3
        fabs    s0, s0
        ret
f4:                                     // @f4
        fneg    s1, s0
        fcmp    s0, #0.0
        fcsel   s0, s1, s0, lt
        ret

https://godbolt.org/z/EercfYfnd

Interestingly, Clang generates different code for f4 and so does GCC for f2.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions