Skip to content

Commit

Permalink
Fix bounds inference for uint -> int casts
Browse files Browse the repository at this point in the history
Fixes #7807
Fixes #7811
  • Loading branch information
abadams committed Aug 28, 2023
1 parent fcc1c3b commit 05ba843
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/Bounds.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -281,9 +281,10 @@ class Bounds : public IRVisitor {
bool could_overflow = true;
if (to.can_represent(from) || to.is_float()) {
could_overflow = false;
} else if (to.is_int() && to.bits() >= 32) {
// If we cast to an int32 or greater, assume that it won't
// overflow. Signed 32-bit integer overflow is undefined.
} else if (from.is_float() && to.is_int() && to.bits() >= 32) {
// If we cast from float to an int32 or greater, assume that it
// won't overflow. Signed 32-bit integer overflow on floating point
// casts is undefined. (Casting from uint is defined to wrap).
could_overflow = false;
} else if (a.is_bounded()) {
if (from.can_represent(to)) {
Expand Down
13 changes: 13 additions & 0 deletions test/correctness/bounds_of_abs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,19 @@ int main(int argc, char **argv) {
f5 = lambda(x, input(cast<int>(clamp(abs(1.0f / (x + .1f)), -50, 50))));
check(f5, input, 0, 51);

// Verify that casting the result of abs of a uint32 back to an int32 is
// considered unbounded below - it may produce the most negative int if the
// cast wraps. We won't phrase this like the tests above, because we would
// expect it to fail to compile with an unbounded access error.
Internal::Scope<Internal::Interval> scope;
scope.push(x.name(), Internal::Interval::everything());
Internal::Interval i =
Internal::bounds_of_expr_in_scope(cast<int>(abs(x)), scope);
if (i.has_lower_bound()) {
printf("Interval should not have had a lower bound\n");
return 1;
}

printf("Success!\n");
return 0;
}

0 comments on commit 05ba843

Please sign in to comment.