Commit a3fe685
math.h BottomNBits: Fix integer underflow (facebook#14231)
Summary:
When running make check on aarch64, hash_test reports an integer underflows:
util/math.h:44:46: runtime error: signed integer overflow:
-2147483648 - 1 cannot be represented in type 'int'
util/math.h:44:46: runtime error: signed integer overflow:
-9223372036854775808 - 1 cannot be represented in type 'long long'
util/math.h:44:46: runtime error: signed integer overflow:
-9223372036854775808 - 1 cannot be represented in type 'long'
The issue is when BottomNBits(int32 value, 31) does not use BMI2, it executes the following:
return static_cast<T>(v & ((T{1} << nbits) - 1));
For int32_t, (1 << 31) is the minimum value, and -1 is an integer underflow. The fix is to cast T to an unsigned type and use that for the bit manipulation.
I used Compiler Explorer to verify that this still compiles to the BZHI instruction mentioned in the comment with -march=x86-64-v3: https://godbolt.org/z/8bcTE8xbf
To reproduce these errors on x86-64, disable the BMI code path:
```
USE_CLANG=1 PORTABLE=x86-64-v2 LDFLAGS=-fsanitize=undefined CXXFLAGS=-fsanitize=undefined make -j20 hash_test
```
Pull Request resolved: facebook#14231
Reviewed By: mszeszko-meta
Differential Revision: D91353147
Pulled By: pdillinger
fbshipit-source-id: 64cc191ccb9ecba20c260fab759e8881e30d23521 parent cc69112 commit a3fe685
2 files changed
Lines changed: 15 additions & 1 deletion
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
615 | 615 | | |
616 | 616 | | |
617 | 617 | | |
| 618 | + | |
| 619 | + | |
| 620 | + | |
| 621 | + | |
| 622 | + | |
| 623 | + | |
| 624 | + | |
618 | 625 | | |
619 | 626 | | |
620 | 627 | | |
| |||
623 | 630 | | |
624 | 631 | | |
625 | 632 | | |
| 633 | + | |
| 634 | + | |
| 635 | + | |
| 636 | + | |
| 637 | + | |
626 | 638 | | |
627 | 639 | | |
628 | 640 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
41 | 41 | | |
42 | 42 | | |
43 | 43 | | |
44 | | - | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
45 | 47 | | |
46 | 48 | | |
47 | 49 | | |
| |||
0 commit comments