This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Optimisations and undefined behaviour


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)


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]