Will any compiler ever boil away a stateless function?

56 Views Asked by At

Let's say I have the following code:

function add(a, b)
    return a + b
end

num1 = add(2, 3)
num2 = add(4, 5)
num3 = add(6, 2)
…

Will any compiler out there ever compile this code as though it were this:

num1 = 2 + 3
num2 = 4 + 5
num3 = 6 + 2
…

If so, is there a way to explicitly tell them you would like them to do this? If not, why not, and is there a way to tell them to do it anyway?

The reason I am curious about such an ability to explicitly tell them to do it would allow for organizing code into functions without sacrificing performance, but if it happens automatically then I guess it's nothing to worry about.

Since "any compiler" is so ridiculously broad, feel free to narrow it down to your choice of popular languages.

Edit: As a comment below explains, compilers may do constant propagation. Consider the following code:

function add(a, b)
    return a + b
end

function doStuff(c)
    num1 = add(2, c)
    num2 = add(4, c)
    num3 = add(6, c)
    …
end

Would add() ever have a chance to be inlined here also?

0

There are 0 best solutions below