[clang] [clang][Sema] Fix for enums overflowing (#24667) (PR #78742)

Aaron Ballman via cfe-commits cfe-commits at lists.llvm.org
Mon Feb 12 05:51:58 PST 2024


AaronBallman wrote:

> @AaronBallman I am a little confused about what is the correct behavior for one the the cases in the test file for c.
> 
> ```c++
> enum PR4515 {PR4515a=1u,PR4515b=(PR4515a-2)/2};
> int CheckPR4515[PR4515b==0?1:-1];
> ```
> 
> At present since everything is ints this works fine, but some things are not clear to me once the enum is allowed to be an unsigned type https://godbolt.org/z/8bfr8s3n5
> 
> ```c++
> enum PR4515 {PR4515a=1u,PR4515b=(PR4515a-2)/2};
>  auto a = PR4515a;
>  auto b = PR4515b;
>  auto c = (1 - 2)/2;
>  auto d = (1u - 2)/2;
>  auto e = (PR4515a-2)/2;
> ```
> 
> values
> 
> ```
> a:
>         .long   1                               # 0x1
> 
> b:
>         .long   0                               # 0x0
> 
> c:
>         .long   0                               # 0x0
> 
> d:
>         .long   2147483647                      # 0x7fffffff
> 
> e:
>         .long   0                               # 0x0
> ```
> 
> specifically around the value for `PR4515b=(PR4515a-2)/2` if `PR4515a` has type unsigned int, then the value of this expression is 2147483647 see `d`, but if it has type int then it has value of 0 see `c` which is the expected value for the test. However, with the new change the enum type would be unsigned since it was specified as unsigned, which I believe is the new behavior.

I think the enumeration constant type is `int` and not `unsigned int`, per 6.7.2.2p12 bullet 4: `int, if given explicitly with = and the value of the integer constant expression is representable by an int; or,`

```
enum PR4515 {
  PR4515a=1u,             // has type int per 6.7.2.2p12 bullet 4 because 1 is representable by an int
  PR4515b=(PR4515a-2)/2   // has type int per 6.7.2.2p12 bullet 4 because (1 - 2) / 2 is representable by an int
};
```
WDYT?

https://github.com/llvm/llvm-project/pull/78742


More information about the cfe-commits mailing list