Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Drop misleading comments about undefined behavior #17532

Merged
merged 1 commit into from
Jan 26, 2025

Conversation

cmb69
Copy link
Member

@cmb69 cmb69 commented Jan 20, 2025

There is no undefined behavior here. If BitScan*() returns zero, the value written to the first parameter is undefined, but we return a reasonable value.


This came up in #17527.

While having a closer look, I found that zend_ulong_ntz() and zend_ulong_nlz() are documented to behave differently if the argument is zero. While the latter states that for zero the result is undefined, the former states that for zero, LEN would be returned:

/* Number of trailing zero bits (0x01 -> 0; 0x40 -> 6; 0x00 -> LEN) */

While this is actually true on Windows, and for the fallback implementation, it is apparently not the case when __builtin_ctzl() or __builtin_ctzll() are used. From https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html:

Returns the number of trailing 0-bits in x, starting at the least significant bit position. If x is 0, the result is undefined.

So at least the comment should be fixed, and I would put in assert regarding the pre-condition, but see #17506 (comment) (I'm not sure whether all callers use the function accordingly). Also, in that case the Windows implementation would not need to check the return value.

Possible alternative: define the functions for num == 0.

There is no undefined behavior here.  If `BitScan*()` returns zero, the
value written to the first parameter is undefined, but we return a
reasonable value.
@cmb69 cmb69 marked this pull request as ready for review January 23, 2025 17:55
Copy link
Member

@nielsdos nielsdos left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, the comment likely meant "written value to index is undefined" but confused this with UB...

@cmb69 cmb69 merged commit ab99693 into php:master Jan 26, 2025
10 checks passed
@cmb69 cmb69 deleted the cmb/bitset-comments branch January 26, 2025 21:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants