Ranking Templates for Linear Loops

We present a new method for the constraint-based synthesis of termination arguments for linear loop programs based on linear ranking templates. Linear ranking templates are parametrized, well-founded relations such that an assignment to the parameters gives rise to a ranking function. This approach generalizes existing methods and enables us to use templates for many different ranking functions with affine-linear components. We discuss templates for multiphase, piecewise, and lexicographic ranking functions. Because these ranking templates require both strict and non-strict inequalities, we use Motzkin's Transposition Theorem instead of Farkas Lemma to transform the generated $\exists\forall$-constraint into an $\exists$-constraint.


Introduction
The scope of this work is the constraint-based synthesis of termination arguments.In our setting, we consider linear loop programs, which are specified by a boolean combination of affine-linear inequalities over the program variables.This allows for both, deterministic and non-deterministic updates of the program variables.An example of a linear loop program is given in Figure 1.
We introduce the notion of linear ranking templates (Section 3).These are parameterized relations specified by linear inequalities such that any assignment to the parameters yields a well-founded relation.This notion is general enough to encompass all existing methods for linear loop programs that use constraint-based synthesis of ranking functions of various kinds (see Section 8 for an assessment).Moreover, ours is the first method for synthesis of lexicographic ranking functions that does not require a mapping between loop disjuncts and lexicographic components.
In this paper we present the following linear ranking templates.• The multiphase ranking template specifies a ranking function that proceeds through a fixed number of phases in the program execution.Each phase is ranked by an affinelinear function; when this function becomes non-positive, we move on to the next phase (Subsection 4.1).We call such a ranking function a multiphase ranking function.• The nested ranking template specifies a ranking function that is a special case of a multiphase ranking function (Subsection 4.2).In contrast to the multiphase ranking template, the nested ranking template requires only linear constraint solving.• The piecewise ranking template specifies a ranking function that is a piecewise affine-linear function with affine-linear predicates to discriminate between the pieces (Subsection 4.3).• The lexicographic ranking template specifies a lexicographic ranking function that corresponds to a tuple of affine-linear functions together with a lexicographic ordering on the tuple (Subsection 4.4).• The parallel ranking template targets programs that have to complete a finite number of independent tasks with no predetermined order (Subsection 4.5).Furthermore, our linear ranking templates can be used as a 'construction kit' for composing linear ranking templates that enable more complex ranking functions (Section 5).Thus, variations on the linear ranking templates presented here can be used and completely different templates could be conceived.
Our method is described in Section 6 and can be summarized as follows.The input is a linear loop program as well as a linear ranking template.From these we construct a constraint on the parameters of the template.This constraint is a quantified nonlinear SMT formula.With Motzkin's theorem [Sch99] we transform the constraint into a purely existentially quantified constraint.This ∃-constraint is then passed to an SMT solver which checks its satisfiability.A positive result implies that the program terminates.Furthermore, a satisfying assignment yields a ranking function, which constitutes a termination argument for the given linear loop program.
Related approaches invoke Farkas' lemma for the transformation into ∃-constraints [ADFG10, BMS05a, BMS05b, CSS03, HHLP13, PR04a, Ryb10, SSM04].Several of our ranking templates contain both strict and non-strict inequalities, yet only non-strict inequalities can be transformed using Farkas' lemma.We solve this problem by introducing the use of Motzkin's Transposition Theorem, a generalization of Farkas' lemma.As a side effect, this also enables both strict and non-strict inequalities in the program syntax.To our knowledge, all of the aforementioned methods can be extended to programs with strict inequalities if Motzkin's theorem is applied instead of Farkas' lemma.
Our method is complete in the following sense.If there is a ranking function of the form specified by the given linear ranking template, then our method will discover this ranking function.In other words, the existence of a solution is never lost in the process of transforming the constraint.
In contrast to some related methods [HHLP13,PR04a] the constraint we generate is not linear, but rather a nonlinear algebraic constraint.Theoretically, this constraint can be decided in exponential time [GV88].Much progress on nonlinear SMT solvers has been made and present-day implementations routinely solve nonlinear constraints of various sizes [JM12].
A related setting to linear loop programs are linear lasso programs (see Figure 3).These consist of a linear loop program and a program stem, both of which are specified by boolean combinations of affine-linear inequalities over the program variables.Our method can be extended to linear lasso programs through the addition of affine-linear inductive invariants, analogously to related approaches [BMS05a, CSS03, HHLP13, SSM04] (Section 7).
In this work, we consider variables with values in the rational or real numbers.Our method can be applied directly to integer programs, but in this case our completeness result does not hold.However, if we compute the integral hull of transition relations analogously to [CKRW13,HHLP13], we obtain the same completeness result for integer-valued linear loop programs as for rational-and real-valued linear loop programs.
This journal article is an extension of a conference paper [LH14].In the conference paper, we introduced the notion of ranking templates and showed how to solve them using Motzkin's theorem (Section 4 and Section 6).We discussed the multiphase, the piecewise, and the lexicographic ranking template.The main additions in this article are the nested and parallel ranking template, the composition of ranking templates, and the extension of our method to linear lasso programs, as well as additional examples.

Preliminaries
In this paper we use K to denote a field that is either the rational numbers Q or the real numbers R.
2.1.Set Theory.We use the the following notions from set theory [Jec06].A set X is transitive iff every element of X is a subset of X.A relation R ⊆ X × X is well-founded iff every non-empty subset of X has an R-minimal element.
The ordinal numbers are a method of counting 'beyond infinity'.The smallest ordinal is the empty set, and for every ordinal α there is a unique successor ordinal α ∪ {α}.The finite ordinals coincide with the natural numbers, therefore we use them interchangeably.The smallest infinite ordinal is denoted by ω.Ordinals can be added, multiplied and exponentiated, but in general these operations are not commutative.
We use the following theorem which allows us to define functions recursively.
Theorem 2.2 (Recursion Theorem [Jec06,Thm. 6.11]).Let R be a well-founded relation on the set X and let G be a function on sets.Then there is a unique function F with domain X such that for every x ∈ X, where F | Y is the restriction of the function F to the domain Y .
2.2.Linear Loop Programs.In this work, we consider programs that consist of a single loop.We use binary relations over the program's states to define its transition relation.We denote by x the vector of n variables (x 1 , . . ., x n ) T ∈ K n corresponding to program states, and by for some finite index set I, some matrices Geometrically the relation LOOP corresponds to a union of convex polyhedra.
In general, the termination of linear loop programs is undecidable because linear loop programs can be used to simulate counter machines.An undecidability proof for the termination of linear lasso programs is given in [Lei13,Thm. 3.18].
Example 2.5.Consider the following program code.while ( q > 0 ) : i f ( y > 0 ) : q := q − y − 1 ; e l s e : q := q + y − 1 ; We represent this code using the following linear loop program: This linear loop program is not conjunctive.Furthermore, there is no infinite sequence of states x 0 , x 1 , . . .such that for all i ≥ 0, the two successive states (x i , x i+1 ) are contained in the relation LOOP.Hence the relation LOOP(x, x ′ ) is well-founded and the linear loop program terminates.We note that this linear loop program does not have a linear ranking function.However, termination of this program can be proven using ranking functions that we present in Subsection 4.1 and in Subsection 4.2.♦

Ranking Templates
A ranking template is a template for a well-founded relation.More specifically, it is a parameterized formula defining a relation that is well-founded for all assignments to the parameters.If we show that a given program's transition relation LOOP is a subset of an instance of this well-founded relation, it must be well-founded itself and thus we have a proof for the program's termination.Moreover, an assignment to the parameters of the template gives rise to a ranking function.In this work, we consider ranking templates that can be encoded with linear arithmetic.We call a formula whose free variables contain x and x ′ a relation template.Each free variable other than x and x ′ in a relation template is called parameter.Given an assignment ν to all parameter variables of a relation template T(x, x ′ ), the evaluation ν(T) is called an instantiation of the relation template T. We note that each instantiation of a relation template T(x, x ′ ) defines a binary relation.
When specifying templates, we use parameter variables to define affine-linear functions.For notational convenience, we write f (x) instead of the term s T f x + t f , where s f ∈ K n and t f ∈ K are parameters.We call f an affine-linear function symbol.Definition 3.1 (Linear Ranking Template).Let T(x, x ′ ) be a relation template with parameters D and affine-linear function symbols F that can be written as a boolean combination of atoms of the form where α f , β f , γ δ ∈ K are constants and ⊲ ∈ {≥, >}.We call T a linear ranking template over D and F iff every instantiation of T defines a well-founded relation.
Example 3.2.We call the following template with parameters D = {δ} and affine-linear function symbols F = {f } the PR ranking template [PR04a].
In the remainder of this section, we introduce a formalism that allows us to show that every instantiation of the PR ranking template defines a well-founded relation.Let us now check the additional syntactic requirements for (3.1) to be a linear ranking template: The next lemma states that we can prove termination of a given linear loop program by checking that this program's transition relation is included in an instantiation of a linear ranking template.Lemma 3.3 (Termination).Let LOOP be a linear loop program and let T be a linear ranking template with parameters D and affine-linear function symbols F .If there is an assignment ν to D and F such that the formula is valid, then the program LOOP terminates.
Proof.By definition, ν(T) is a well-founded relation and (3.2) is valid iff the relation LOOP is a subset of ν(T).Thus LOOP must be well-founded.
In order to establish that a relation template which is conforming to the syntactic requirements is indeed a ranking template, we have to show that each instantiation of the relation template is well-founded.According to the following lemma, we can do this by showing that each assignment to D and F gives rise to a ranking function.A similar argument was given in [BA09]; we provide a significantly shortened proof by use of the Recursion Theorem, along the lines of [Jec06, Ex. 6.12].Definition 3.4 (Ranking Function).Given a binary relation R over a set Σ, a function ρ from Σ to some ordinal α is a ranking function for R iff for all x, x ′ ∈ Σ the following implication holds.
Lemma 3.5 (Existence of Ranking Functions).A binary relation R is well-founded if and only if there exists a ranking function for R.
Proof.Let ρ be a ranking function for R. The image of a sequence decreasing with respect to R under ρ is a strictly decreasing ordinal sequence.Because the ordinals are well-ordered, this sequence cannot be infinite.
Conversely, the graph G = (Σ, R) with vertices Σ and edges R is acyclic by assumption.Hence the function ρ that assigns to every element of Σ an ordinal number such that ρ(x) = sup {ρ(x ′ )+ 1 | (x, x ′ ) ∈ R} is well-defined and exists due to the Recursion Theorem.
Example 3.6.Consider the terminating linear loop program LOOP from Example 2.5.A ranking function for LOOP is ρ : R 2 → ω, defined as follows.
ρ(q, y) = ⌈q⌉, if q > 0, and 0 otherwise, where ⌈•⌉ denotes the ceiling function that assigns to every real number r the smallest natural number that is larger or equal to r.Since we consider the natural numbers to be a subset of the ordinals, the ranking function ρ is well-defined.♦ We use assignments to a template's parameters and affine-linear function symbols to construct a ranking function.These functions are real-valued and we transform them into ordinal-valued functions as follows.
Definition 3.7 (Ordinal Ranking Equivalent).Given an affine-linear function f and a real number δ > 0 called the step size, we define the ordinal ranking equivalent of f as , if f (x) > 0, and 0 otherwise.
Our notation does not explicitly refer to δ to increase readability.In our presentation the step size δ is always clear from the context in which an ordinal ranking equivalent f is used.

♦
The assignment from Example 3.8 to δ and f makes the implication (3.2) valid.In order to invoke Lemma 3.3 to show that the linear loop program given in Example 2.5 terminates, we need to prove that the PR ranking template is a linear ranking template.We use the following technical lemma.Lemma 3.9 (Well-Foundedness of Ordinal Ranking Equivalents).Let f be an affine-linear function of step size δ > 0 and let x and x ′ be two states.
Corollary 3.10.The PR ranking template is a linear ranking template.
Proof.Any assignment ν to δ and f satisfies the requirements of Lemma 3.9.Consequently, f is a ranking function for ν(T), and by Lemma 3.5 this implies that ν(T) is well-founded.
The goal of this paper is to use linear ranking templates to prove the termination of linear lasso programs, as exposed in Lemma 3.3.We defer the explanation how the ∃∀formula (3.2) can be transformed so that it is easier to solve to Section 6.The next two sections focus on additional examples for linear ranking templates.

Examples of Ranking Templates
4.1.The Multiphase Ranking Template.The multiphase ranking template targets programs that go through a finite number of phases in their execution.Each phase is ranked with an affine-linear function and the phase is considered to be completed once this function becomes non-positive.
Example 4.1.Consider the linear loop program from Figure 1 on page 2. Every execution can be partitioned into two phases: first y increases until it is positive and then q decreases until the loop condition q > 0 is violated.Depending on the initial values of y and q, one or more phases might be skipped altogether.♦ Definition 4.2 (Multiphase Ranking Template).We define the k-phase ranking template with parameters D = {δ 1 , . . ., δ k } and affine-linear function symbols We say that the multiphase ranking function given by an assignment to f 1 , . . ., f k and δ 1 , . . ., δ k is in phase i iff f i (x) > 0 and f j (x) ≤ 0 for all j < i.The condition (4.2) states that there is always some i such that the multiphase ranking function is in phase i. Conditions (4.3) and (4.4) state that if we are in a phase ≥ i, then f i has to be decreasing by at least δ i > 0. Thus we start in phase 1 and transition through the phases 2, . . ., k, possibly skipping some or all of them.
Two special cases of the multiphase ranking template have been discussed previously in the literature: the 1-phase ranking template, because it coincides with the PR ranking template, and the 2-phase ranking template [BM13].
Moreover, multiphase ranking functions are related to eventually negative expressions introduced by Bradley, Manna, and Sipma [BMS05b].However, in contrast to our approach, they require a template tree that specifies in detail how each loop disjunct interacts with each phase.
Example 4.3.Consider the program from Figure 1 on page 2. The assignment yields a 2-phase ranking function for this program.This program is in phase 1 iff y < 1 and it is in phase 2 iff y ≥ 1 and q > −1.♦ Theorem 4.4.The k-phase ranking template is a linear ranking template.
Proof.The k-phase ranking template conforms to the linear ranking template's syntactic requirements.Let ν be an assignment to the parameters D and the affine-linear function symbols F of the k-phase ranking template T k-phase .Consider the following ranking function with codomain ω • k.
. By Lemma 3.5, we need to show that ρ(x ′ ) < ρ(x).From (4.2) follows that ρ(x) > 0.Moreover, there is an i such that f i (x) > 0 and f j (x) ≤ 0 for all j < i.By (4.3) and (4.4), we obtain f j (x ′ ) ≤ 0 for all j < i, because Therefore Lemma 3.5 implies that ν(T k-phase ) is well-founded.Does each terminating linear loop program have a multiphase ranking function if we restrict ourselves to conjunctive linear loop programs?The following theorem gives a negative answer to this question.
Theorem 4.5.The following terminating conjunctive linear loop program does not have a multiphase ranking function.
Proof.The variables a and b are positive and grow exponentially, but b grows faster than a.
For any input, b eventually becomes larger than a and then the loop program terminates.Assume the loop program (4.6) has a multiphase ranking function.Then there are As maxima over a finite nonempty set, a, b ∈ R exist uniquely and we have a > b > 1 by construction.By setting a ′ = 2a and b ′ = 3b, we get (a, b, 2a, 3b) ∈ LOOP.Let j be the smallest index such that f j (a, b) > 0, which exists due to (4.2).According to (4.1) we obtain δ j > 0 and since j is minimal, we get (4.7) We do an exhaustive case analysis over α j and β j , and show that all cases yield contradictions.Thus our assumption that there is a multiphase ranking function must be false.(i) α j > 0: From (4.7) and a ≥ −2β j b we get Example 4.6.Recall that we allowed our linear loop programs to have nondeterministic variable assignments.Because of this, the existence of a multiphase ranking function does not imply an upper bound on the execution time of the program.Consider the following linear loop program.
For a given input with y > 0, we cannot give an upper bound on the execution time: after the first loop execution, y is set to 0 and q is set to some arbitrary value, as no restriction to q ′ applies in the first disjunct.In particular, this value does not depend on the input.The remainder of the loop execution then takes ⌈q⌉ iterations to terminate.
However, we can prove the program's termination with the 2-phase ranking function constructed from f 1 (q, y) = y and f 2 (q, y) = q.♦ 4.2.The Nested Ranking Template.Like the multiphase ranking template, the nested ranking template targets programs that go through a fixed number of phases in their execution.Again, each phase has an affine-linear ranking function, but this affine-linear function cannot increase by more than the value of the previous phase's affine-linear function.Thus once the previous phase is finished, its value starts decreasing.
δ > 0 (4.8) Example 4.8.Consider the program from Figure 1.In Example 4.3 we gave an assignment for the 2-phase ranking template.We can use almost the same assignment to get a 2-nested ranking function for this program.♦ The following lemma states that nested ranking functions are a special case of multiphase ranking functions.Lemma 4.9 (Nested Ranking Template ⊆ Multiphase Ranking Template).For every assignment ν to the k-phase ranking template T k-phase there is an assignment ν ′ to the k-nested Proof.For a given ν, we choose We show ν ′ (T k-nested ) ⊆ ν(T k-phase ) by showing that each of (4.8), (4.9), (4.10), and (4.11) with assignment ν ′ implies (4.1), (4.2), (4.3), and (4.4) with assignment ν, respectively.This is immediate for the first three lines.For (4.11) → (4.4) let (x, x ′ ) and i > 1 be given and assume ν(f i−1 )(x) ≤ 0. We get with ν(δ k+1 ) := 0 for notational convenience.
Theorem 4.10.The k-nested ranking template is a linear ranking template.
Proof.Follows from Theorem 4.4 and Lemma 4.9.
If a nested ranking function is just a special case of a multiphase ranking function, why are we considering it separately?The advantage of the nested template is that it does not contain any disjunctions.Thus, the generated constraint can be solved using only linear constraint solving [Lei13,Ch. 6].In our experiments, many programs that have a multiphase ranking function also have a nested ranking function.Hence it is a viable and faster alternative to the multiphase template in practice.
Example 4.11.The multiphase template is strictly more powerful than the nested template; consider the following loop program LOOP.
This program has the 2-phase ranking function constructed from f 1 (q, y) = y and f 2 (q, y) = q.Since there are no upper or lower bounds on q and y, only the constant function f i (q, y) = γ i can be positive for all q, y.By (4.11) if f i is constant, then f i−1 is positive.By induction we get that f 1 must be constant, a contradiction to (4.10).♦ Despite their simplicity, nested ranking templates are already quite powerful.We give two nontrivial examples below that each have a nested ranking function.These ranking functions were found automatically.
During the execution of this loop, the vector (a, b) is rotated around 0 by the irrational angle arccos(3/5) ≈ 53.13 degrees.In the long run, the contribution of a to q cancels out, and q decreases on average, hence the program terminates.This program has a 3-nested ranking function constructed from the affine-linear functions f 2 (q, a, b) = 4q + 5a, and f 3 (q, a, b) = 5q.♦ Example 4.13 (Crazy Spirals).We can also take the previous example to more extremes; consider the following conjunctive linear loop program.
During program execution, the vector (c, d) moves on an outward spiral centered at 0; the vector (a, b) does the same except that it is offset by c.On average, the contribution from these spirals to q cancel out, so q decreases on average.This program has a 7-nested ranking function.♦ 4.3.The Piecewise Ranking Template.The piecewise ranking template formalizes a ranking function that is defined piecewise using affine-linear predicates to discriminate the pieces.
The disjunction (4.15) states that the discriminators cover all states; in other words, the piecewise defined ranking function is a total function.Given the k different pieces f 1 , . . ., f k and a state x, we use f i as a ranking function only if g i (x) ≥ 0 holds.This choice need not be unambiguous; the discriminators may overlap.If they do, we can use any one of their ranking pieces.According to (4.14), all ranking pieces are positive-valued and by (4.13), ranking piece transitions are well-defined: the rank of the new state is always less than the rank of any of the ranking pieces assigned to the old state.(q > 0 ∧ p > 0 ∧ q < p ∧ q ′ = q − 1) In every loop iteration, the minimum of p and q is decreased by 1 until it becomes negative.Thus, this program is ranked by the 2-piece ranking function constructed from the ranking pieces f 1 (p, q) = p and f 2 (p, q) = q with step size δ = 1/2 and discriminators g 1 (p, q) = q − p and g 2 (p, q) = p − q.Moreover, this program does not have a multiphase or lexicographic ranking function: both p and q may increase without bound during program execution due to non-determinism and the number of switches between p and q being the minimum value is also unbounded.♦ Theorem 4.16.The k-piece ranking template is a linear ranking template.
Proof.The k-piece ranking template conforms to the linear ranking template's syntactic requirements.Let ν be an assignment to the parameter δ and the affine-linear function symbols F of the k-piece template T k-piece be given.Consider the following ranking function with codomain ω. ρ(x) The function ρ is well-defined, because the set { f i (x) | g i (x) ≥ 0} is not empty according to (4.15).Let (x, x ′ ) ∈ ν(T k-piece ) and let i and j be indices such that ρ(x) = f i (x) and ρ(x ′ ) = f j (x ′ ).By the definition of ρ, we have that g i (x) ≥ 0 and g j (x ′ ) ≥ 0, and (4.13) thus implies f j (x ′ ) < f i (x) − δ.Using (4.14), we prove analogously to Lemma 3.9, that this entails f j (x ′ ) < f i (x) and therefore ρ(x ′ ) < ρ(x).Lemma 3.5 now implies that ν(T k-piece ) is well-founded.
4.4.The Lexicographic Ranking Template.Lexicographic ranking functions consist of lexicographically ordered components of affine-linear functions.A state is mapped to a tuple of values such that the loop transition leads to a decrease with respect to the lexicographic ordering for this tuple.Therefore no function may increase unless a function of a lower index decreases.Additionally, at every step, there must be at least one function that decreases.
There are different definitions of lexicographic ranking functions in circulation [ADFG10, BAG13, BMS05a]; a comparison can be found in [BAG13, Sec.2.4].Each of these definitions for lexicographic linear ranking functions can be formalized using linear ranking templates.
Here we are following the definition of [ADFG10].This definition is the weakest, but for the other definitions the ranking template has an exponentially larger CNF, and hence our method performs comparatively poorly on them.Definition 4.17 (Lexicographic Ranking Template).We define the k-lexicographic ranking template with parameters D = {δ 1 , . . ., δ k } and affine-linear function symbols F = {f 1 , . . ., f k } as follows.
The conjunction (4.18) establishes that all lexicographic components f 1 , . . ., f k have positive values.In every step, at least one component must decrease according to (4.20).From (4.19) follows that all functions corresponding to components of larger index than the decreasing function may increase.
Example 4.18.Consider the following linear loop program.
When taking the first disjunct, b decreases until it becomes ≤ 5. Hence we take the second disjunct eventually, decreasing a.Because a does not increase when taking the first disjunct, we can only take the second disjunct finitely many times.Since the second disjunct is always taken eventually, the program terminates.This is proved by the 2-lexicographic ranking function constructed from the components f 1  Proof.The k-lexicographic ranking template conforms to the linear ranking template's syntactic requirements.Let ν be an assignment to the parameters D and the affine-linear function symbols F of the k-lexicographic template T k-lex .Consider the following ranking function with codomain ω k .
Therefore Lemma 3.5 implies that ν(T k-lex ) is well-founded.
4.5.The Parallel Ranking Template.The parallel ranking template targets programs that do multiple tasks in parallel where progress on each task can be nondeterministic.These tasks have no predetermined order of execution.We assume that each task can be ranked by an affine-linear ranking function.
The ranking functions f 1 , . . ., f k correspond to k different tasks.The conjunction (4.23) states that none of the ranking functions may increase at any point.Moreover, (4.24) states that with every transition, at least one task has to make progress and end in a finite number of steps.Note that (4.24) is not given in conjunctive normal form (CNF).When transformed in CNF, the number of conjuncts blows up exponentially.
Example 4.21.Consider the following linear loop program.
This programs performs two tasks nondeterministically in parallel: the first task takes a iterations and the second task takes b iterations; the program terminates once both tasks have been completed.
By (4.24), there is a j such that f j (x) > 0 and f j (x ′ ) < f j (x) − δ j .Therefore we have f j (x ′ ) < f j (x) by Lemma 3.9.Hence Now Lemma 3.5 implies that ν(T k-parallel ) is well-founded.

Composition of Templates
In this section we discuss how more powerful linear ranking templates can be constructed based on the linear ranking templates from Section 4. First, we consider a program that is terminating, but whose termination cannot be proven using one of the ranking templates presented so far.
Example 5.1.Consider the following linear loop program.
When executing the first disjunct, y decreases until it becomes negative.Then we execute the second disjunct: we increment x, set y to some arbitrary value, and decrement q if x is positive.If y was reset to some positive value, the first disjunct is executed again, but the values of q and x do not change until the second disjunct is executed.Eventually, x is positive and from then on q is decremented until it is nonpositive; thus the program terminates.♦ The program's behavior resembles a lexicographic ranking function with q as the first component and y as the second.However, q is decremented only after x becomes positive: the first component needs 2 phases.We want a ranking template for a lexicographic ranking function that has multiphase ranking functions instead of affine-linear functions in every component.How can we construct a linear ranking template for such a ranking function?
Observe that all of our linear ranking templates share the following subformulas.
In the context of ranking templates, these formulas have the following meaning.
(i) The function f is non-increasing.
(ii) The function f is decreasing.
(iii) The codomain of the function f is well-founded.Here f is always an affine-linear function.The idea of template composition is to replace the subformulas (i-iii) with subformulas of the same meaning for more powerful functions.We next define triples of formulas that are suitable substituents for (i-iii), called composed template recipes.Afterwards, we will use composed template recipes to build new linear ranking templates.
Definition 5.2 (Composed Template Recipe).A composed template recipe is defined recursively according to the following rules.(C1) The PR template recipe (T ≤ PR , T < PR , T >0 PR ) is a composed template recipe with k ) which do not share any parameters or affine-linear function symbols, we can construct a composed template recipe (T ≤ , T < , T >0 ) according to one of the following three composition rules.

Composition rule
The intuition behind Definition 5.2 is that we build composed templates recursively using PR template recipes (C1) or k-piece template recipes (C2) as the base case and plugging them into composition rules given in (C3).
There is a composition rule for each linear ranking template presented in Section 4 but the k-piece ranking template and the k-nested ranking template.We cannot define a kpiece or a k-nested composition rule analogously, because not all of these ranking templates' atoms are of the form (i-iii) above: they also have atoms containing multiple affine-linear function symbols (f i (x ′ ) < f i (x) + f i−1 (x) in (4.11) and f j (x ′ ) < f i (x) − δ in (4.13)).
Given a composed template recipe (T ≤ , T < , T >0 ), we call the conjunction T < ∧ T >0 a composed template.The following theorem states that composed templates are linear ranking templates.
Theorem 5.3.If (T ≤ , T < , T >0 ) is a composed template recipe, then the composed template T < ∧ T >0 is a linear ranking template.
The proof of Theorem 5.3 is deferred to the end of this section.
Example 5.4 (The k-Phase Composition Rule).We apply the k-phase composition rule to k PR template recipes.Let D := {δ i | 1 ≤ i ≤ k} be parameters and let = {f i | 1 ≤ i ≤ k} be affine-linear function symbols.For each i, we have three formulas T ≤ PR,i , T < PR,i , and T >0 PR,i .Using the k-phase composition rule from Definition 5.2 (C3), we get the composed template recipe (T ≤ k-phase , T < k-phase , T >0 k-phase ) where By Theorem 5.3, T < k−phase ∧ T >0 k−phase is a linear ranking template.In fact, we already know this from Theorem 4.4, because the formula T < k-phase ∧ T >0 k-phase is equivalent to the k-phase ranking template.♦ Remark 5.5.(i) Let (T ≤ , T < , T >0 ) be the k-phase composition rule applied to k PR template recipes.
Then the composed template T >0 ∧ T < is equivalent to the k-phase ranking template.(ii) Let (T ≤ , T < , T >0 ) be the k-lexicographic composition rule applied to k PR template recipes.Then the composed template T >0 ∧ T < is equivalent to the k-lexicographic ranking template.(iii) Let (T ≤ , T < , T >0 ) be the k-parallel composition rule applied to k PR template recipes.
Then the composed template T >0 ∧T < is equivalent to the k-parallel ranking template.
Next, we construct a composed template to prove termination of Example 5.1.
Example 5.6.We apply the ℓ-lexicographic composition rule to ℓ copies of the composed template recipe from Example 5.4.Let D := {δ i,j | 1 ≤ i ≤ k, 1 ≤ j ≤ ℓ} be parameters and let F = {f i,j | 1 ≤ i ≤ k, 1 ≤ j ≤ ℓ} be affine-linear function symbols.For each j, we apply the k-phase composition rule to k PR template recipes as in Example 5.4, using the parameters D j := {δ i,j | 1 ≤ i ≤ k} and the affine-linear function symbols F j := {f i,j | 1 ≤ i ≤ k}.Let the resulting composed template recipe be denoted (T ≤ k-phase,j , T < k-phase,j , T >0 k-phase,j ).Next, we apply the ℓ-lexicographic composition rule to the ℓ composed template recipes (T ≤ k-phase,j , T < k-phase,j , T >0 k-phase,j ) resulting in the composed template recipe (T ≤ lm , T < lm , T >0 lm ) where By Theorem 5.3, T < lm ∧ T >0 lm is a linear ranking template.♦ Example 5.7.Using the composed template recipe from Example 5.6, we can find a ranking function for Example 5.1: Proof of Theorem 5.3.First, we need to check the syntactic requirements.This was already shown for the PR ranking template and the k-piece ranking template.Any substitution is a boolean combination of parts of simpler templates, and the syntactic requirements for linear ranking templates allow for arbitrary boolean combinations of atoms.
To show well-foundedness, we prove the following statement by induction over the recursive construction of the composed template recipes.We show that for all assignments ν to the parameters and affine-linear function symbols, we find a function ρ : Σ → α from the program states Σ to some ordinal α such that For the base case, we have a PR template recipe or a k-piece template recipe, and we get a ranking function ρ : Σ → ω.Claims (ii) and (iii) follow from Lemma 3.9 and Theorem 4.16.For the PR template recipe, claim (i) holds because f (x ′ ) ≤ f (x) implies f (x ′ ) ≤ f (x).For the k-piece template recipe, we prove this analogously to the proof of Theorem 4.16, using For the induction step, assume that claims (i-iii) hold for the composed template recipes Thus for every i = 1 . . .k, we have a ranking function ρ i : Σ → α i with ordinal α i as codomain.We consider the three inductive cases in turn.
• k-parallel: We define the ranking function For (x, x ′ ) ∈ ν(T ≤ ), we have that ρ i (x ′ ) ≤ ρ i (x) for all i by the induction hypothesis, and hence ρ(x ′ ) ≤ ρ(x).For (x, x ′ ) ∈ ν(T < ), we again have by the induction hypothesis that ρ i (x ′ ) ≤ ρ i (x) for all i, and that there is an i such that ρ i (x ′ ) < ρ i (x).Therefore we obtain ρ(x ′ ) < ρ(x).For (x, x ′ ) ∈ ν(T >0 ), we have that there is an i such that ρ i (x) > 0 by the induction hypothesis, therefore ρ(x) > 0. This completes the induction.To finish the proof, we note that according to claim (ii) and (iii), ρ is a ranking function for ν(T < ∧T >0 ), and by Lemma 3.5 this implies that ν(T < ∧T >0 ) is well-founded.
Although the procedure introduced in this section allows for an infinite number of different ranking templates, it is not exhaustive.We expect that there are many more types of ranking functions that can be formalized using linear ranking templates, and possibly also composed with other templates.

Synthesizing Ranking Functions
Following related approaches [ADFG10, BMS05a, BMS05b, CSS03, HHLP13, PR04a, Ryb10, SSM04], we transform the ∃∀-constraint (3.2) into an ∃-constraint.This transformation makes the constraint more easily solvable not only because we remove universal quantification, but also because it reduces the number of nonlinear operations in the constraint.Every application of an affine-linear function symbol f corresponds to a nonlinear term s T f x + t f where s f is a vector of real-valued parameters and t f is a real-valued parameter.For this step, we need the following theorem.
6.1.Motzkin's Transposition Theorem.Intuitively, Motzkin's transposition theorem states that a given system of linear inequalities has no solution if and only if a contradiction can be derived via a positive linear combination of the inequalities.
If ℓ is set to 1 in Theorem 6.1, we obtain the affine version of Farkas' lemma [Sch99, Cor.7.1h].Therefore Motzkin's theorem is strictly superior to Farkas' lemma, as it allows for a combination of both strict and non-strict inequalities.Moreover, it is logically optimal in the sense that it enables the transformation of any purely universally quantified (Π 0 1 ) formula from the theory of linear arithmetic.6.2.Constraint Transformation.We fix a linear loop program LOOP and a linear ranking template T with parameters D and affine-linear function symbols F .For simplicity of presentation, we assume the loop program LOOP does not contain any strict inequalities, and the ranking template T does not contain any non-strict inequalities; however, recall that we are using Motzkin's theorem instead of Farkas' lemma precisely to lift this restriction.For the fully general constraints, see [Lei13,Ch. 5].We write LOOP in disjunctive normal form and T in conjunctive normal form: We prove the termination of LOOP by solving the constraint (3.2).This constraint is implicitly existentially quantified over the parameters D and the parameters corresponding to the affine-linear function symbols F .
First, we transform the constraint (6.1) into an equivalent constraint of the form required by Motzkin's theorem.
Now, Motzkin's Transposition theorem transforms the constraint (6.2) into an equivalent existentially quantified constraint:  The ∃-constraint (6.3) is then checked for satisfiability.If an assignment is found, it gives rise to a ranking function.Conversely, if no assignment exists, then there cannot be an instantiation of the linear ranking template and thus no ranking function of the kind formalized by the linear ranking template exists.In this sense our method is sound and complete.Theorem 6.2 (Soundness).If the transformed ∃-constraint (6.3) is satisfiable, then the linear loop program terminates.Theorem 6.3 (Completeness).If the ∃∀-constraint (3.2) is satisfiable, then so is the transformed ∃-constraint (6.3).6.3.Ranking Template Pools.Our method for ranking function synthesis can be applied as follows.We fix a finite pool of linear ranking templates T , consisting of multiphase, nested, piecewise, lexicographic, and parallel ranking templates as well as composed templates in various sizes.The input is a linear loop program LOOP that we want to check for termination.We start by picking a linear ranking template T from the pool T .From the ranking template T we build the constraint (3.2) to the parameters and affine-linear function symbols of T. This constraint is transformed using Motzkin's theorem to an ∃-constraint (6.3).If this constraint is satisfiable, this gives rise to a ranking function according to Lemma 3.5, and thus we proved that the loop program LOOP terminates.Otherwise, we try again using the next linear ranking template from the pool T until the pool has been exhausted.If the pool has been exhausted, the proof of the loop program LOOP's termination failed.However, due to the completeness of our method, we know that the loop program LOOP does not have a ranking function of the form specified by any of the linear ranking templates in the pool.Figure 2 is a description of our method in pseudocode.

STEM LOOP
Figure 3: A lasso program.
Our method extends to the more general setting of linear lasso programs.These are linear loop programs that have a program stem in addition to the loop (see Figure 3).We use affine-linear inductive invariants to extract the information that is crucial for the termination proof from the stem.This is in line with related approaches [CSS03, SSM04, BMS05a for some finite index set I, some matrices A i ∈ K n×m i , C i ∈ K n×k i , and some vectors b i ∈ K m i and d i ∈ K k i .The linear lasso program P is called conjunctive iff there is only one disjunct in both transitions STEM and LOOP.Definition 7.2 (Affine-Linear Supporting Invariant).A formula ψ is an affine-linear supporting invariant for the linear lasso program P iff there is an affine-linear function f such that ψ(x) ≡ f (x) ⊲ 0 with ⊲ ∈ {≥, >}, and the following two formulas hold.
The affine-linear supporting invariant ψ is strict iff ⊲ is > and non-strict otherwise.
Given a linear lasso program, we do the same transformation steps as in Subsection 6.2, adding a finite number of supporting invariants: In fact, every conjunct in (6.2) gets m supporting invariants: To insure that the ψ i,j,ℓ (x) are indeed supporting invariants, we add the constraints (II) and (IC) for each (i, j, ℓ) ∈ I ×J ×{1, . . ., m}.Each of these constraints is then transformed using Motzkin's theorem.analogously to Subsection 6.2.Not all invariants are inductive and we only consider invariants that are affine-linear inequalities.We do not retain completeness of our method in the sense of Theorem 6.3.
The invariant initiating (II) is a linear constraint, but the invariant consecution (IC) is nonlinear.We could make (IC) linear by restricting ourselves to non-decreasing invariants [HHLP13].However, the overall constraints are generally still nonlinear because the constraints that come from the linear ranking template are generally nonlinear.

Related Work
Synthesis of linear ranking functions for linear loop programs was first discussed by Colón and Sipma [CS01].This was extended to a complete template-based method by Podelski and Rybalchenko [PR04a,Ryb10], using the PR ranking template as discussed in Example 3.2.Their method is not complete over the integers.Cook et al. [CKRW13] compute the integral hull of transition relations in order obtain the same completeness for integers and bitvectors.Bagnara and Mesnard generalize the PR ranking template to the 2-phase ranking template, relying on nonlinear constraint solving [BM13].
Bradley, Manna, and Sipma propose a constraint-based approach for linear lasso programs [BMS05a].Their termination argument is a lexicographic ranking function with each lexicographic component corresponding to one loop disjunct.This requires nonlinear constraint solving and an ordering on the loop disjuncts.The authors extend this approach in [BMS05b] by the use of template trees.These trees allow each lexicographic component to have a ranking function that decreases not necessarily in every step, but eventually.
Ben-Amram and Genaim discuss the synthesis of affine-linear and lexicographic ranking functions for linear loop programs over the integers [BAG13].They prove that this problem is generally co-NP-complete and show that several special cases admit a polynomial time complexity.
In [CFM12] the authors also address the problem of finding termination arguments for (not necessarily conjunctive) linear loop programs.In contrast to our work, the authors do not synthesize the termination argument directly.Instead, they iteratively synthesize linear ranking functions and obtain a disjunctively well-founded relation [PR04b] as a termination argument.
Approaches for computing lexicographic linear ranking functions for a more general class of programs, namely programs that can consist of several (potentially nested) loops are presented in [ADFG10] and [CSZ13].On linear loop programs, both algorithms involve choosing an ordering on the loop disjuncts.Hence, both approaches are either incomplete or have to use backtracking to iteratively consider all possible orderings of loop disjuncts.
Our method is not able to prove termination for all terminating linear loop programs.Termination is decidable for the subclass of deterministic conjunctive linear loop programs of the form while(B s x > b s ∧ B w x ≥ b w ) x := Ax + c; where the matrices B s , B w , A and vectors b s , b w , c are rational, and variables can take on rational or real values [Tiw04].This class also admits decidable termination analysis over the integers for the homogeneous case where b s , b w , c = 0 [Bra06].However, their method is not targeted at the synthesis of ranking functions.
Ranking functions can also be computed via abstract interpretation [CC12].Urban and Miné [Urb13, UM14a, UM14b] introduced the domain of piecewise defined ordinalvalued functions for this approach.In contrast to our work, their approach is applicable to programs with arbitrary structure and not restricted to linear lasso programs.However, the authors do not provide completeness results that state that a ranking function of a certain form can always be found.

Conclusion
We presented a sound and complete method for constraint-based synthesis of ranking functions for linear loop programs.For this method, we introduced the notion of linear ranking templates, which are parameterized formulas for well-founded relations.In Section 3 we established how they can be applied to prove termination (Lemma 3.3) and that an instantiation of a linear ranking template gives rise to a ranking function (Lemma 3.5).Our method can be applied to different kinds of ranking functions that previously have been considered independently (affine-linear and lexicographic ranking functions), in addition to enabling new kinds (multiphase, piecewise, and parallel ranking functions).The ranking templates can also be composed into more powerful templates, allowing for more general ranking functions.See Table 1 for statistics on the size of our ranking templates.
Our method can be applied to linear loop programs and linear lasso programs with variables that are rational numbers, real numbers, or integers.In general, it requires solving nonlinear algebraic constraints, but some linear ranking templates such as the PR ranking template or the nested ranking template only require linear constraint solving.

Example 4. 15 .
Consider the following linear loop program.
(a, b) = a and f 2 (a, b) = b.♦ Note that the program from Example 4.18 does not have a multiphase ranking function and the program from Figure 1 on page 2 does not have a lexicographic ranking function.Thus the multiphase ranking template and the lexicographic ranking template are incomparable in expressive power.

Theorem 4. 19 .
The k-lexicographic ranking template is a linear ranking template.
The 2-parallel ranking function constructed from f 1 (a, b) = a and f 2 (a, b) = b proves this program terminating.♦ Theorem 4.22.The k-parallel ranking template is a linear ranking template.Proof.The k-parallel ranking template conforms to the linear ranking template's syntactic requirements.Let ν be an assignment to the parameters D and the affine-linear function symbols F of the k-parallel template T k-parallel .Consider the following ranking function with codomain ω. ρ(x) := k i=1

Figure 2 :
Figure 2: Our ranking function synthesis algorithm described in pseudocode.The function transformWithMotzkin transforms the ∃∀-constraint ϕ into an ∃-constraint ψ as described in Subsection 6.2.The ranking function is extracted from an assignment of the template with the function extractRankingFunction.This function returns a description of the ranking function depending on the template; for example the ordinal-based representation from the proofs.
variables of the next state.Definition 2.3 (Linear Loop Program).A linear loop program LOOP(x, x ′ ) is a binary relation defined by a formula with the free variables x and x ′ of the form Input: linear loop program LOOP and a list of linear ranking templates T Output: a ranking function for LOOP or null if none is found foreach T ∈ T do : l e t ϕ = ∀x, x ′ .LOOP(x, x ′ ) → T(x, x ′ ) For every inequality in (M1), a new existentially quantified variable is added in (M2).These new existentially quantified variables are called Motzkin coefficients.
Definition 7.1 (Linear Lasso Program).A linear lasso program P = (STEM, LOOP) consists of • a linear loop program LOOP, and • a predicate STEM, defined by a formula with the free variables x of the form

Table 1 :
Statistics of our linear ranking templates in CNF; the integer k specifies their size.Every affine-linear function symbol constributes n + 1 parameters to the template, where n is the number of program variables.