patternMinor
Can CPU's 'shortcut' adding 0, multiplying by 1, and multiplying by 0?
Viewed 0 times
canshortcutmultiplyingaddingandcpu
Problem
I am currently writing a program where a lot of adding 0 to numbers and multiplying by 1 and 0 occurs and it got me to wondering if the CPU 'shortcuts' (drops), these operations. I'm a CS student and this hasn't been brought up ever.
Can a CPU do this? What are the trade-offs in designing a CPU that detects +1, 1 and 0 and executes them faster?
Can a CPU do this? What are the trade-offs in designing a CPU that detects +1, 1 and 0 and executes them faster?
Solution
Yes, there are processors which detect some kind of do-nothing operations, handle them specially so that they take less time than what they would take if they were handled naïvely. In some cases, there are even recommended instructions to use for NOP (NOP are sometimes useful to align the code with a memory boundary, having NOP of various lengths available help the relieve the decoding part), the wikipedia page for NOP has a list which gives the normal meaning for some of them.
But
-
what you think as a do-nothing operation may not be one if you take into account things like resetting flags or the side effects of memory accesses -- and a processor should behave correctly in such matter;
-
I'd not rely on this as an optimization; more as an encoding trick or as a way to reduce the op-code pressure; they are working when the operands are statically known to have no effect and in such cases, the code writer -- human or compiler -- should avoid the operation if possible;
-
detecting dynamically that the value has no effect is probably more costly than what would be gained by doing so. That said, some relatively simple processors have operations which take a time which depend on the arguments (for arithmetic operations, don't think I've seen this for something else than integer multiplication and division, or for floating point operations)
But
-
what you think as a do-nothing operation may not be one if you take into account things like resetting flags or the side effects of memory accesses -- and a processor should behave correctly in such matter;
-
I'd not rely on this as an optimization; more as an encoding trick or as a way to reduce the op-code pressure; they are working when the operands are statically known to have no effect and in such cases, the code writer -- human or compiler -- should avoid the operation if possible;
-
detecting dynamically that the value has no effect is probably more costly than what would be gained by doing so. That said, some relatively simple processors have operations which take a time which depend on the arguments (for arithmetic operations, don't think I've seen this for something else than integer multiplication and division, or for floating point operations)
Context
StackExchange Computer Science Q#70880, answer score: 4
Revisions (0)
No revisions yet.