I am wondering there is any optimization option in Clang or GCC for escape analysis on std::vector
in C++.
Since std::vector<int>
in the example below does not require the actual data of v
to be allocated in the heap or stack. Compiler can actually allocate v.data()
on stack for better performance.
Assume that Clang/GCC does not do escape analysis, is there any particular motivation to not to use escape analysis?
Assume that Clang/GCC does escape analysis, why value of
v.data()
and&x
so different?
#include<cstdio>
#include<vector>
int main() {
int x = 0;
std::vector<int> v(3, 0);
std::printf("&x: %p\n", &x);
//std::printf("&v: %p\n", &v); // we intentionally don't print the pointer to v here.
std::printf("v.data(): %p\n", v.data());
return x + v[0]; // we want compiler not to optimize everything out
}
Expected result
&x: <some address>
v.data(): <some address> + 4
Actual result from Clang and GCC
[*****@localhost test]$ g++ test.cc -O3
[khanh@localhost test]$ ./a.out
&x: 0x7ffe2af5a59c
v.data(): 0xadde70
[*****@localhost test]$ clang++ test.cc -O3
[*****@localhost test]$ ./a.out
&x: 0x7fff66ce1ab4
v.data(): 0xfeee70
Thanks!
There exists escape analysis on Clang compiler.
Sample code: from @geza https://godbolt.org/z/N1GLUI
GCC
Clang