Tom
Tom

Reputation: 1291

Compiler design: Is it worth simplifying an expression?

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.

Upvotes: 0

Views: 280

Answers (1)

FPK
FPK

Reputation: 2098

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.

Upvotes: 2

Related Questions