[cfe-dev] "You don't pay for what you don't use" principle violation?

David Blaikie dblaikie at gmail.com
Sun May 4 15:27:16 PDT 2014


On Sun, May 4, 2014 at 3:08 PM, Fernando Pelliccioni
<fpelliccioni at gmail.com> wrote:
> Hi all,
>
> Is there any reason why the following code produces the attached assembly
> code?
>
>     struct X { int v; };
>
>     int func( X** x, int n )
>     {
>         int sum = 0;
>
>         while ( n > 0 )
>         {
>             sum += (*x)->v;
>             ++x;
>             --n;
>         }
>         return sum;
>     }

This is an externally visible function - it can't be omitted from the
object file as it may be used by some other object file that will be
linked in. (it could be a global ctor, so the absence of code in
'main' doesn't indicate that it will never be used)

LTO can remove functions like this.

>     int main() {}
>
> The "func" function is not used, I think it should be omitted by the
> compiler.
>
> If I change the function to a template function
>
>     template <typename T>
>     int func( T** x, int n )
>     {
>         int sum = 0;
>
>         while ( n > 0 )
>         {
>             sum += (*x)->v;
>             ++x;
>             --n;
>         }
>         return sum;
>     }
>
> Then, no code is generated.

Since there's no call, there's no template instantiation, and no code.
The C++ language requires callers in other translation units to have
an instantiation of the template somewhere, it just doesn't have to be
here.

>
>
> Compiled using:
>     clang++ -S -O3 -std=c++11 -S code.cpp
>
> clang++ --version
>     clang version 3.5 (trunk 200620)
>     Target: x86_64-apple-darwin13.1.0
>     Thread model: posix
>
>
> Best,
> Fernando.
>
> _______________________________________________
> cfe-dev mailing list
> cfe-dev at cs.uiuc.edu
> http://lists.cs.uiuc.edu/mailman/listinfo/cfe-dev
>



More information about the cfe-dev mailing list