
GCC code generation for C++ Weekly Ep 43 example - matt_d
https://kristerw.blogspot.com/2017/01/gcc-code-generation-for-c-weekly-ep-43.html
======
krona
After a quick investigation, clang (3.9, x86-64) doesn't seem to suffer from
the same problem:

[https://godbolt.org/g/Uvo7iO](https://godbolt.org/g/Uvo7iO)

~~~
tcbawo
Calling with 46 arguments seems to move this onto the stack:
[https://godbolt.org/g/tbKtGz](https://godbolt.org/g/tbKtGz)

~~~
rurban
No. It hits the constant folding threshold and calls the sum function with the
args.

------
haberman
This surprises me. This makes it sound like inlining and vectorizztion are
performed independently of constant folding. It seems like the compiler should
be able to recognize when a function depends only on its inputs. Then constant
folding should be able to inline / evaluate any code that can be compile-time
evaluated, no matter how much code that is. It doesn't seem like this should
be left up to chance.

~~~
DannyBee
It's likely just a typical pass ordering problem

------
harpocrates
Is there no way to indicate to GCC when you want something fully evaluated at
compile-time? Maybe some pragmas? 98% of the time I probably don't care
whether GCC does a good job optimizing this properly, but for the times I do
care: what should I do?

~~~
lultimouomo
c++ has constexpr for this. a constexpr expression will be evaluated at
compile time if the result is used in a constant expression (i.e. assignd to
an enum constant or a constexpr variable), or an error will be generated if it
is not possible to do so (the expression does not fulfill the requirements to
be constexpr).

~~~
krona
working example: [https://godbolt.org/g/EXdQx1](https://godbolt.org/g/EXdQx1)

~~~
TillE
Your example still gets calculated at compile time if you remove the
constexpr. However, if you change -O3 to -O2, then there's a difference.

------
TwoBit
VC++ 2015 (the latest released version as of this writing) can't optimize this
for any number of arguments, even just one.

~~~
DannyBee
VC has always been good at code gen but not middle optimizations. Though they
are working on it, this kind of thing takes years to build and tune well

~~~
winter_blue
> VC has always been good at code gen

Well, target code gen _is the job_ of a compiler. Optimization is a plus. It's
like saying VC is good at compiling, but not optimizing.

~~~
DannyBee
i'm really not sure what point you are trying to make. Yes, VC is good at
compiling but not optimizing.

Given people expect both from their compilers these days ...

