Bug 116193 - enhancement: type attribute that causes overflow for unsigned integer types to trap
Summary: enhancement: type attribute that causes overflow for unsigned integer types t...
Status: WAITING
Alias: None
Product: gcc
Classification: Unclassified
Component: c (show other bugs)
Version: unknown
: P3 enhancement
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2024-08-02 09:44 UTC by uecker
Modified: 2024-08-02 16:10 UTC (History)
3 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed: 2024-08-02 00:00:00


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description uecker 2024-08-02 09:44:41 UTC
It would be nice to have an attribute that one can add to an unsigned integer type that makes overflow trap.

typedef unsigned int __attribute__ ((__overflow__)) positive_int;
Comment 1 Andrew Pinski 2024-08-02 10:00:27 UTC
Huh? Is this thinking about being added to the C standard?
I suspect this will be abused just as clang's "unsigned overflow" ubsan has been abused and incorrect bug reports to library developers has happened (e.g. one to libstdc++ for some psedu-random code where it uses wrapping).
Comment 2 Jakub Jelinek 2024-08-02 10:02:03 UTC
That opens the door of issues how you can actually subtract those things validly.
Would x - y and x + (-y) then behave differently for it?
Comment 3 uecker 2024-08-02 10:56:53 UTC
It came up  as a possibility in various discussions, including on the kernel mailing list or inside WG14.   I personally use signed type if I want to detect overflow and unsigned only if I want modulo behavior, and I am relatively happy with this.  But others like to  (or have code that does) use unsigned types also for positive numbers such as sizes or indices where wraparound often leads to bugs.

I don't see the risk of misuse as much as with the sanitizer, as it would be opt-in for specific types, so can be introduced on where it is clear that wraparound is not intended.

I would say x - y would be different than x + (-y) and the later should trap. Although I guess (-y) could already be diagnosed in the FE, so for middle end this would not matter.
Comment 4 Richard Biener 2024-08-02 11:19:47 UTC
-y is OK when y == 0

I hope you are not suggesting that it's UB to overflow though.  The attribute
should make the frontend to lower operations according to semantics and leave
everything in the middle-end unaffected.
Comment 5 Martin Uecker 2024-08-02 16:06:54 UTC
I agree this could be done completely in the FE.