问题
#include <iostream>
int foo(int i){
return foo(i + 1);
}
int main(int argc,char * argv[]){
if(argc != 2){
return 1;
}
std::cout << foo(std::atoi(argv[1])) << std::endl;
}
% clang++ -O2 test.cc
% time ./a.out 42
1490723512
./a.out 42 0.00s user 0.00s system 69% cpu 0.004 total
% time ./a.out 42
1564058296
./a.out 42 0.00s user 0.00s system 56% cpu 0.006 total
% g++ -O2 test.cc
% ./a.out 42 #infinte recursion
^C
% clang++ --version
clang version 3.3 (tags/RELEASE_33/final)
Target: x86_64-apple-darwin12.4.0
Thread model: posix
% g++ --version
i686-apple-darwin11-llvm-g++-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)
Copyright (C) 2007 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
So is it a bug or a feature of clang++?
回答1:
While both g++ and clang++ are able to compile C++98 and C++11 code, clang++ was designed from the start as a C++11 compiler and has some C++11 behaviors embedded in its DNA (so to speak).
With C++11 the C++ standard became thread aware, and that means that now there are some specific thread behavior. In particular 1.10/24 states:
The implementation may assume that any thread will eventually do one of the following:
— terminate,
— make a call to a library I/O function,
— access or modify a volatile object, or
— perform a synchronization operation or an atomic operation.
[Note: This is intended to allow compiler transformations such as removal of empty loops, even when termination cannot be proven. — end note ]
And that is precisely what clang++ is doing when optimizing. It sees that the function has no side effects and removes it even if it does not terminate.
来源:https://stackoverflow.com/questions/18478078/clang-infinite-tail-recursion-optimization