Skip to content

BUG: Avoid UB in safe_[add,sub,mul] helpers#31396

Merged
charris merged 1 commit into
numpy:mainfrom
ngoldbaum:fix-overflow-ub
May 7, 2026
Merged

BUG: Avoid UB in safe_[add,sub,mul] helpers#31396
charris merged 1 commit into
numpy:mainfrom
ngoldbaum:fix-overflow-ub

Conversation

@ngoldbaum
Copy link
Copy Markdown
Member

Over in https://github.com/numpy/numpy/pull/31378/changes#r3190759945, I noticed that these helpers can trigger UB, since the result is always computed even if overflow might happen. A sufficiently aggressive compiler might optimize functionality away if it detects the undefined behavior.

Clang and gcc both have intrinsics to handle this, which we use if available. I had to add new probes for the add and sub builtin intrinsics. For the fallback cases, I added early returns to avoid triggering overflow.

I used Claude Opus 4.7 to help with this.

@charris charris added the 09 - Backport-Candidate PRs tagged should be backported label May 7, 2026
@charris charris merged commit 11b1baa into numpy:main May 7, 2026
86 checks passed
@charris
Copy link
Copy Markdown
Member

charris commented May 7, 2026

Thanks Nathan. I marked this for backport as it seems straight forward.

@charris charris removed the 09 - Backport-Candidate PRs tagged should be backported label May 8, 2026
charris added a commit that referenced this pull request May 8, 2026
BUG: Avoid UB in safe_[add,sub,mul] helpers (#31396)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants