This is the mail archive of the gcc-patches@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: avoid generating casts for bools


> Dan Nicolaescu <dann@godzilla.ics.uci.edu> writes:
>
>  > As shown in the thread starting at:
>  > http://gcc.gnu.org/ml/gcc/2004-04/msg01027.html
>  > bools are unnecessarily cast to int. The tree optimizers cannot get
>  > rid of the extra casts.
>
>  > Special casing bools in convert_to_integer seems to do the trick,
>  > the spurious casts are avoided. The patch to do this is below, it
> > might be more conservative than it needs to be.
>
> This patch together with the one avoiding the casts for return values
> in "start_function" was bootstrapped on x84_64-linux.
>
> There is one regression for C: an extra warning for c99-bool-1.c
>
> ./cc1 -O2 c99-bool-1.c
> c99-bool-1.c: In function `main':
> c99-bool-1.c:231: warning: comparison is always true due to limited range of
> data type
>
> The code in question is:
>
>  _Bool u;
>  u  = 1;
>  if ((u ^= 3) != 1)
>    abort ();
> 
> I am not sure if the warning is correct.

To my understanding, as the operands to ^ need only be promoted to the
smallest common integer type (not necessarily int) capable of representing
its operand's values; which in this case would likely be an 'unsigned char'
(assuming _Bool is not larger than char) which correctly computes the result
value 2, which when assigned to u is 1 'true' (as any value other than 0
assigned to a bool is logically equivalent to 'true' == 1), which when
compared != 1 (i.e.!= 'true') returns 0 'false', therefore the final
comparison's result is correspondingly always 'false', it would seem.

(but I suspect the warning is coming from u ^= 3; warning that u = 2 will
 always result in 1 'true', which seems a bit excessive, as bool values are
 obviously 'true' if not assigned a 0 'false', and not easy to quiet without
 without restructuring the expression, so suspect this warning should most
 reasonably only be a -pedantic warning, and not enabled by default.)

In general, my understanding is that all enum, char, short arguments smaller
than int need only be promoted to the smallest common integer type capable
of preserving their values, which need not be as large as an int; and in
most cases, need actually be no larger than the rank of the target of an
assignment, often enabling the demotion of it's operands, with no loss of
correctness or standard compliance, as may be helpful in circumstances where
the otherwise implied computation is wider than the width of a target
machine's natural word size. 



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