logoalt Hacker News

Joker_vD • today at 6:38 PM • 1 reply • view on HN

Once upon a time testing whether all bits of a number are zero was slower than checking a single sign bit. Even when MIPS was originally designed, Hennessy and his team had some trouble with making BEQZ/BNEZ fast enough for their intended pipeline.


Replies

adrian_b • today at 7:05 PM

This happens because testing the sign bit needs just a wire from that bit to the flags, while testing if a register is zero requires a wide OR gate with as many inputs as there are bits.

In CMOS you cannot have an OR gate so wide, so it must be synthesized from a cascade of narrower gates, which add several levels of delays.

While in modern CPU technologies the speed of generating a zero flag is not a problem, when designing with FPGAs, which are much slower, it is useful to be aware that testing for the sign is cheaper than testing for a wide zero.

Many CPUs have an instruction for implementing loops like decrement-and-jump-if-not-zero (which is LOOP in x86-64). When implementing a simple CPU in an FPGA it is cheaper and faster to replace that instruction with 2 instructions for loops like increment-and-jump-if-negative and decrement-and-jump-if-not-negative (it is good to have both these instructions to be able to access an array both in forward order and in reverse order, while using the loop counter also as index register).

The same applies when making a counter in FPGAs, it can count at higher frequencies if you test for the sign bit to determine the end of the counting, instead of testing when the count reaches zero.