This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Optimisations and undefined behaviour
- From: Vincent Lefevre <vincent+gcc at vinc17 dot org>
- To: David Brown <david dot brown at hesbynett dot no>
- Cc: Andrew Haley <aph at redhat dot com>, "[gcc-help]" <gcc-help at gcc dot gnu dot org>
- Date: Sun, 8 Nov 2015 18:17:15 +0100
- Subject: Re: Optimisations and undefined behaviour
- Authentication-results: sourceware.org; auth=none
- References: <563BC190 dot 7080406 at hesbynett dot no> <563C7EB6 dot 9050401 at redhat dot com> <563C9DD3 dot 9030407 at hesbynett dot no> <563CAE52 dot 9080309 at redhat dot com> <563CBCD5 dot 90900 at hesbynett dot no> <563CCBB3 dot 50806 at redhat dot com> <563F66F0 dot 6090506 at hesbynett dot no>
On 2015-11-08 16:14:56 +0100, David Brown wrote:
> I got close with a dont_care() :
>
> static inline int dont_care(void) {
> int x;
> asm ("" : "=r" (x) : );
> return x;
> }
>
> This lets gcc "generate" an int without any instructions. But the compiler
> doesn't know that you don't care what value it has, so this won't let the
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> compiler eliminate the conditional in :
>
> int foo(int x) {
> if (x < 1000) {
> return x * x * x;
> } else {
> return dont_care();
> }
> }
I don't think that this is the problem here. First, the conditional
could be eliminated only if the code is in the x < 1000 case does not
have side effects (such as traps in case of overflow). Moreover, even
if the compiler knows that it is safe to do the transformation, would
it know that doing it would yield faster code? This is not obvious.
IMHO, the right thing to do is to have a way to instruct the compiler
that the multiplication has some defined behavior even in case of
overflow. Something like -fwrapv. However, the problems with -fwrapv
is that it is not part of the semantic of the code and that it is
global.
> Another option is:
>
> static inline int dont_care2(void) {
> int x = x;
> return x;
> }
>
> But that sometimes ends up with an unnecessary setting of x to 0.
And this is also undefined behavior.
--
Vincent Lefèvre <vincent@vinc17.net> - Web: <https://www.vinc17.net/>
100% accessible validated (X)HTML - Blog: <https://www.vinc17.net/blog/>
Work: CR INRIA - computer arithmetic / AriC project (LIP, ENS-Lyon)