From a4ed9f3b548896870248d1c6cf4b407cc138f89e Mon Sep 17 00:00:00 2001 From: sergei Date: Sun, 7 Feb 2016 11:18:31 +0000 Subject: [PATCH] * Improved sign(x) functions to be branchless in most cases. Resolves #14206. git-svn-id: trunk@33067 - --- rtl/objpas/math.pp | 38 ++++++++++++++------------------------ 1 file changed, 14 insertions(+), 24 deletions(-) diff --git a/rtl/objpas/math.pp b/rtl/objpas/math.pp index 5b87356b2e..541e0eaf0a 100644 --- a/rtl/objpas/math.pp +++ b/rtl/objpas/math.pp @@ -638,35 +638,35 @@ end; function Sign(const AValue: Integer): TValueSign;inline; begin - If Avalue<0 then - Result:=NegativeValue - else If Avalue>0 then - Result:=PositiveValue - else - Result:=ZeroValue; + result:=TValueSign( + SarLongint(AValue,sizeof(AValue)*8-1) or { gives -1 for negative values, 0 otherwise } + (-AValue shr (sizeof(AValue)*8-1)) { gives 1 for positive values, 0 otherwise } + ); end; function Sign(const AValue: Int64): TValueSign;inline; begin +{$ifdef cpu64} + result:=TValueSign( + SarInt64(AValue,sizeof(AValue)*8-1) or + (-AValue shr (sizeof(AValue)*8-1)) + ); +{$else cpu64} If Avalue<0 then Result:=NegativeValue else If Avalue>0 then Result:=PositiveValue else Result:=ZeroValue; +{$endif} end; {$ifdef FPC_HAS_TYPE_SINGLE} function Sign(const AValue: Single): TValueSign;inline; begin - If Avalue<0.0 then - Result:=NegativeValue - else If Avalue>0.0 then - Result:=PositiveValue - else - Result:=ZeroValue; + Result:=ord(AValue>0.0)-ord(AValue<0.0); end; {$endif} @@ -674,24 +674,14 @@ end; function Sign(const AValue: Double): TValueSign;inline; begin - If Avalue<0.0 then - Result:=NegativeValue - else If Avalue>0.0 then - Result:=PositiveValue - else - Result:=ZeroValue; + Result:=ord(AValue>0.0)-ord(AValue<0.0); end; {$ifdef FPC_HAS_TYPE_EXTENDED} function Sign(const AValue: Extended): TValueSign;inline; begin - If Avalue<0.0 then - Result:=NegativeValue - else If Avalue>0.0 then - Result:=PositiveValue - else - Result:=ZeroValue; + Result:=ord(AValue>0.0)-ord(AValue<0.0); end; {$endif}