Andy Glew's comp-arch.net wiki, http://semipublic.comp-arch.net
If you are reading this elsewhere, e.g. at site waboba.info, it is an unauthorized copy, and probably a malware site.
comp-arch.net wiki on hold from October 17, 2011
Absolute value (ABS)
ABS, Absolute value instructions
It is often necessary to take the absolute value.
Calculating this with a branch
if(v < 0 ) v = -v
costs extra instructions, and may produce costly branch mispredictions.
In IEEE FP representations, calculating the absolute value may involve just AND-masking off the sign bit. NaNs may make this more complicated.
In 2's compliment integer representation, calculating the absolute value without a branch is a bit more complicated.
The instruction count overhead of branchless absolute value, in combination with branch mispredictions, and NaN and overflow semantics, motivates a special instruction.
2's complement branchless ABS
result = (v ^ (v>>31)) - (v>>31)
supposedly patented. TBD find patent.
- scalar ABS
- dest := ABS(src)
- scalar ABSDIFF
- dest := ABS(src1-src2)
- since ABS is often found right after a SUBtract
- vector ABS
- destV := vector-ABS( v1 - v2 )
- vector SAD - sum-of-absolute-difference
- destV := SUM-reduce( vector-ABS( vector-SUB( v1 - v2 )))
- accumulating vector SAD sum-of-absolute-difference
- Acc += SUM-reduce( vector-ABS( vector-SUB( v1 - v2 )))
- See MPSADBW
Issue: signed integer ABS overflow
N-bit 2's compliment integers range from -2^(N-1) to +2^(N-1)-1. This means that ABS of the most negative integer is not representable as a signed 2's compliment integer
There are several ways of handling this.
One way is to consider ABS(signed)->unsigned, which removes the possibility of overflow - or at least defers it to the next calculations.
Another way would be to throw to throw an exception; barring that, treat the ABS instruction as returning an unsigned integer
unsigned ABS( signed );
and to return the bit pattern 10...00, which is the appropraite unsigned value.
It may be desirable to set a condition code to indicate this condition. This is particularly appropriate for ABS instruction flavours such as accumulating-sum-of-absolute-differences
Acc += SUM-reduce( vector-ABS( vector-SUB( v1 - v2 )))
where you may want to distinguish overflow of the accumulator from possible
Occasionally one sees negative absolute value (NEGABS) and NEGABSDIFF and sum-neg-absdiff (SNAD) instructions, to cope with the fact that in standard 2's complement there is one more negative value than there is a positive value. I.i. ABS and ABSDIFF can overflow, but NAGABS and NEGABSDIFF cannot.
Cyrix 6x86MX's PMAGW instruction is an interesting variant on ABS instructions: it does, for all vector elements i
vdest[i] := ( abs(src1[i]) > abs(src2[i]) ? src1[i] : src2[i]
i.e. it compares absolute values, without saturation, and then selects the non-absolute value that is greatest.
rather like an abs-select-max.