From: Sanjay Patel Date: Tue, 22 May 2018 15:36:50 +0000 (+0000) Subject: [CodeGen] produce the LLVM canonical form of abs X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=98de0f5c7b7656fff13d0345fb77f4784369db7b;p=clang [CodeGen] produce the LLVM canonical form of abs We chose the 'slt' form as canonical in IR with: rL332819 ...so we should generate that form directly for efficiency. git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@332989 91177308-0d34-0410-b5e6-96231b3b80d8 --- diff --git a/lib/CodeGen/CGBuiltin.cpp b/lib/CodeGen/CGBuiltin.cpp index c6f0b30bc7..7f1e125560 100644 --- a/lib/CodeGen/CGBuiltin.cpp +++ b/lib/CodeGen/CGBuiltin.cpp @@ -1251,16 +1251,12 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, case Builtin::BI__builtin_abs: case Builtin::BI__builtin_labs: case Builtin::BI__builtin_llabs: { + // X < 0 ? -X : X Value *ArgValue = EmitScalarExpr(E->getArg(0)); - Value *NegOp = Builder.CreateNeg(ArgValue, "neg"); - Value *CmpResult = - Builder.CreateICmpSGE(ArgValue, - llvm::Constant::getNullValue(ArgValue->getType()), - "abscond"); - Value *Result = - Builder.CreateSelect(CmpResult, ArgValue, NegOp, "abs"); - + Constant *Zero = llvm::Constant::getNullValue(ArgValue->getType()); + Value *CmpResult = Builder.CreateICmpSLT(ArgValue, Zero, "abscond"); + Value *Result = Builder.CreateSelect(CmpResult, NegOp, ArgValue, "abs"); return RValue::get(Result); } case Builtin::BI__builtin_conj: diff --git a/test/CodeGen/builtin-abs.c b/test/CodeGen/builtin-abs.c index b68d465d2f..a6ae36c8fb 100644 --- a/test/CodeGen/builtin-abs.c +++ b/test/CodeGen/builtin-abs.c @@ -3,8 +3,8 @@ int absi(int x) { // CHECK-LABEL: @absi( // CHECK: [[NEG:%.*]] = sub i32 0, [[X:%.*]] -// CHECK: [[CMP:%.*]] = icmp sge i32 [[X]], 0 -// CHECK: [[SEL:%.*]] = select i1 [[CMP]], i32 [[X]], i32 [[NEG]] +// CHECK: [[CMP:%.*]] = icmp slt i32 [[X]], 0 +// CHECK: [[SEL:%.*]] = select i1 [[CMP]], i32 [[NEG]], i32 [[X]] // return __builtin_abs(x); } @@ -12,8 +12,8 @@ int absi(int x) { long absl(long x) { // CHECK-LABEL: @absl( // CHECK: [[NEG:%.*]] = sub i64 0, [[X:%.*]] -// CHECK: [[CMP:%.*]] = icmp sge i64 [[X]], 0 -// CHECK: [[SEL:%.*]] = select i1 [[CMP]], i64 [[X]], i64 [[NEG]] +// CHECK: [[CMP:%.*]] = icmp slt i64 [[X]], 0 +// CHECK: [[SEL:%.*]] = select i1 [[CMP]], i64 [[NEG]], i64 [[X]] // return __builtin_labs(x); } @@ -21,8 +21,8 @@ long absl(long x) { long long absll(long long x) { // CHECK-LABEL: @absll( // CHECK: [[NEG:%.*]] = sub i64 0, [[X:%.*]] -// CHECK: [[CMP:%.*]] = icmp sge i64 [[X]], 0 -// CHECK: [[SEL:%.*]] = select i1 [[CMP]], i64 [[X]], i64 [[NEG]] +// CHECK: [[CMP:%.*]] = icmp slt i64 [[X]], 0 +// CHECK: [[SEL:%.*]] = select i1 [[CMP]], i64 [[NEG]], i64 [[X]] // return __builtin_llabs(x); }