CBMC
|
Back to Code Contracts User Documentation
A decreases clause specifies a measure that must strictly decrease at every iteration of a loop. By demonstrating that the measure
we can prove termination of loops. This is because the measure must eventually hit the lower bound at which point the loop must terminate, since the measure cannot strictly decrease further. This technique for proving termination was proposed by Robert Floyd, and interested readers may refer to his seminal paper "[_Assigning Meaning to Programs_](https://people.eecs.berkeley.edu/~necula/Papers/FloydMeaning.pdf)".
A one-dimensional (1D) decreases clause for a loop is an arithmetic expression e
over the variables visible at the same scope as the loop, specified as __CPROVER_decreases(e)
.
Like invariant clauses, decreases clauses may be specified just after the loop guard. An example of a 1D decreases clause is shown below.
Please see the loop invariant clauses page for more examples on for
and do...while
loops.
To help prove termination of more complex loops, CBMC also supports multi-dimensional decreases clauses. A multi-dimensional decreases clause is an ordered tuple of arithmetic expressions, specified as __CPROVER_decreases(e_1, e_2, ..., e_n)
. An example of a multi-dimensional decreases clause is given below.
We extend the strict arithmetic comparison for 1D decreases clauses to a strict lexicographic comparison for multi-dimensional decreases clauses.
Important. Like invariant clauses, decreases clauses must be free of side effects, for example, mutation of local or global variables. Otherwise, CBMC raises an error message during compilation:
A decreases clause extends the loop abstraction introduced in the loop invariant clause documentation. In addition to the inductiveness check asserted at the end of a single arbitrary iteration, CBMC would also assert the strict decrement of the measure specified in the decreases clause. At a high level, in addition to the assumptions and assertions introduced by the invariant clause, a decreases clause expands to three key steps:
For a 1D decreases clause, we use the strict arithmetic comparison (i.e., <
). For a multi-dimensional decreases clause, say (e_1, ..., e_n)
, we extend the strict arithmetic comparison to a strict lexicographic comparison.
As an example, consider our binary search implementation again, this time with a decreases clause annotation to prove its termination:
The instrumented GOTO program is conceptually similar to the following high-level C program:
The instrumented code points (5), (6), (8), and (9) are specific to the decreases clause.
Important. Decreases clauses work in conjunction with loop invariant clauses, which model an arbitrary loop iteration at which the decreases clause is checked. If a decreases clause is annotated on a loop without an invariant clause, then the weakest possible invariant (i.e, true
) is used to model an arbitrary iteration.