0
votes

I had an idea for a compiler optimisation for expressions:

If I have the following expression y = x + x + x I can simplify it to be y = 3*x

However after doing some research I came across this blog post about operators costs, stating that:

The cheapest of the cheapest, in this order: addition, subtraction, comparison (1) abs (2) multiplication (4)

Where the number is a weight cost to each operator.

This being said, is it a common practice to simplify expressions in compilers using common algebraic techniques? According to the blog post, in the example I gave it would only be worth simplifying with a multiplication operator if there is more then 4 addition operators.

1
You should keep in mind that 3*x is not necessarily equivalent to x+x+x. Consider the overflow case (if x is integer), for example. Also, cost of multiplication may vary wildly, so I'd rather leave this sort of optimisations until the very microarchitecture-specific instruction scheduling step.SK-logic

1 Answers

2
votes

It is useful because e.g. x86 can do *3 efficiently by using lea (lea eax,[edi+edi*2]). If *3 cannot be encoded efficiently, the compiler can easily decide in later stages that the *3 should be replaced by two addition operations or a shift and an addition.