Skip to content

Simplify equality over address-of with offset #7704

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

Merged
merged 1 commit into from
May 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions regression/cbmc/Pointer_comparison5/main.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
int main()
{
int A[2];
int b;

int *ptr = &A[1];

if(ptr == &b)
{
__CPROVER_assert(0, "unreachable");
}
else if((unsigned long long)ptr == (unsigned long long)&b)
{
__CPROVER_assert(0, "unreachable");
}
}
14 changes: 14 additions & 0 deletions regression/cbmc/Pointer_comparison5/test.desc
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
CORE
main.c

^Generated \d+ VCC\(s\), 1 remaining after simplification$
^VERIFICATION SUCCESSFUL$
^EXIT=0$
^SIGNAL=0$
--
^warning: ignoring
--
Simplification and constant propagation make the comparison over (unrelated)
pointers trivially false; the corresponding comparison over pointers cast to
integers is not simplified as the simplifier need not know how pointers convert
to integers (except for NULL).
33 changes: 33 additions & 0 deletions src/util/simplify_expr_int.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ Author: Daniel Kroening, [email protected]
#include "rational_tools.h"
#include "simplify_utils.h"
#include "std_expr.h"
#include "threeval.h"

#include <algorithm>

Expand Down Expand Up @@ -1605,6 +1606,38 @@ simplify_exprt::resultt<> simplify_exprt::simplify_inequality_no_constant(
{
return unchanged(expr);
}
else if(
expr.id() == ID_equal && ptr_op0.id() == ID_address_of &&
ptr_op1.id() == ID_address_of)
{
// comparing pointers: if both are address-of-plus-some-constant such that
// the resulting pointer remains within object bounds then they can never
// be equal
auto in_bounds = [this](const exprt &object_ptr, const exprt &expr_op) {
auto object_size =
size_of_expr(to_address_of_expr(object_ptr).object().type(), ns);

if(object_size.has_value())
{
pointer_offset_exprt offset{expr_op, object_size->type()};
exprt in_object_bounds =
simplify_rec(binary_relation_exprt{
std::move(offset), ID_lt, std::move(*object_size)})
.expr;
if(in_object_bounds.is_constant())
return tvt{in_object_bounds.is_true()};
}

return tvt::unknown();
};

if(
in_bounds(ptr_op0, expr.op0()).is_true() &&
in_bounds(ptr_op1, expr.op1()).is_true())
{
return false_exprt{};
}
}
}

// eliminate strict inequalities
Expand Down