Author: spatel Date: Tue May 22 16:02:13 2018 New Revision: 333038 URL: http://llvm.org/viewvc/llvm-project?rev=333038&view=rev Log: [CodeGen] use nsw negation for builtin abs
The clang builtins have the same semantics as the stdlib functions. The stdlib functions are defined in section 7.20.6.1 of the C standard with: "If the result cannot be represented, the behavior is undefined." That lets us mark the negation with 'nsw' because "sub i32 0, INT_MIN" would be UB/poison. Differential Revision: https://reviews.llvm.org/D47202 Modified: cfe/trunk/lib/CodeGen/CGBuiltin.cpp cfe/trunk/test/CodeGen/builtin-abs.c Modified: cfe/trunk/lib/CodeGen/CGBuiltin.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBuiltin.cpp?rev=333038&r1=333037&r2=333038&view=diff ============================================================================== --- cfe/trunk/lib/CodeGen/CGBuiltin.cpp (original) +++ cfe/trunk/lib/CodeGen/CGBuiltin.cpp Tue May 22 16:02:13 2018 @@ -1252,8 +1252,9 @@ RValue CodeGenFunction::EmitBuiltinExpr( case Builtin::BI__builtin_labs: case Builtin::BI__builtin_llabs: { // X < 0 ? -X : X + // The negation has 'nsw' because abs of INT_MIN is undefined. Value *ArgValue = EmitScalarExpr(E->getArg(0)); - Value *NegOp = Builder.CreateNeg(ArgValue, "neg"); + Value *NegOp = Builder.CreateNSWNeg(ArgValue, "neg"); Constant *Zero = llvm::Constant::getNullValue(ArgValue->getType()); Value *CmpResult = Builder.CreateICmpSLT(ArgValue, Zero, "abscond"); Value *Result = Builder.CreateSelect(CmpResult, NegOp, ArgValue, "abs"); Modified: cfe/trunk/test/CodeGen/builtin-abs.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/builtin-abs.c?rev=333038&r1=333037&r2=333038&view=diff ============================================================================== --- cfe/trunk/test/CodeGen/builtin-abs.c (original) +++ cfe/trunk/test/CodeGen/builtin-abs.c Tue May 22 16:02:13 2018 @@ -2,7 +2,7 @@ int absi(int x) { // CHECK-LABEL: @absi( -// CHECK: [[NEG:%.*]] = sub i32 0, [[X:%.*]] +// CHECK: [[NEG:%.*]] = sub nsw i32 0, [[X:%.*]] // CHECK: [[CMP:%.*]] = icmp slt i32 [[X]], 0 // CHECK: [[SEL:%.*]] = select i1 [[CMP]], i32 [[NEG]], i32 [[X]] // @@ -11,7 +11,7 @@ int absi(int x) { long absl(long x) { // CHECK-LABEL: @absl( -// CHECK: [[NEG:%.*]] = sub i64 0, [[X:%.*]] +// CHECK: [[NEG:%.*]] = sub nsw i64 0, [[X:%.*]] // CHECK: [[CMP:%.*]] = icmp slt i64 [[X]], 0 // CHECK: [[SEL:%.*]] = select i1 [[CMP]], i64 [[NEG]], i64 [[X]] // @@ -20,7 +20,7 @@ long absl(long x) { long long absll(long long x) { // CHECK-LABEL: @absll( -// CHECK: [[NEG:%.*]] = sub i64 0, [[X:%.*]] +// CHECK: [[NEG:%.*]] = sub nsw i64 0, [[X:%.*]] // CHECK: [[CMP:%.*]] = icmp slt i64 [[X]], 0 // CHECK: [[SEL:%.*]] = select i1 [[CMP]], i64 [[NEG]], i64 [[X]] // _______________________________________________ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits