\documentclass[11pt,a4paper]{article}
\usepackage{a4wide}
\usepackage{amsfonts}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{array}
\usepackage[english]{babel}
\usepackage{../../style/cerco}
\usepackage{color}
\usepackage{diagrams}
\usepackage{graphicx}
\usepackage[utf8x]{inputenc}
\usepackage{listings}
\usepackage{microtype}
\usepackage{skull}
\usepackage{stmaryrd}
\usepackage{wasysym}
\newcolumntype{b}{\at{}>{{}}}
\newcolumntype{B}{\at{}>{{}}c<{{}}\at{}}
\newcolumntype{h}[1]{\at{\hspace{#1}}}
\newcolumntype{L}{>{$}l<{$}}
\newcolumntype{C}{>{$}c<{$}}
\newcolumntype{R}{>{$}r<{$}}
\newcolumntype{S}{>{$(}r<{)$}}
\newcolumntype{n}{\at{}}
\lstdefinelanguage{matita-ocaml}
{keywords={definition,coercion,lemma,theorem,remark,inductive,record,qed,let,in,rec,match,return,with,Type,try,on,to},
morekeywords={[2]whd,normalize,elim,cases,destruct},
morekeywords={[3]type,of,val,assert,let,function},
mathescape=true,
}
\lstset{language=matita-ocaml,basicstyle=\tt,columns=flexible,breaklines=false,
keywordstyle=\bfseries, %\color{red}\bfseries,
keywordstyle=[2]\bfseries, %\color{blue},
keywordstyle=[3]\bfseries, %\color{blue}\bfseries,
% commentstyle=\color{green},
% stringstyle=\color{blue},
showspaces=false,showstringspaces=false}
\DeclareUnicodeCharacter{8797}{:=}
\DeclareUnicodeCharacter{10746}{++}
\DeclareUnicodeCharacter{9001}{\ensuremath{\langle}}
\DeclareUnicodeCharacter{9002}{\ensuremath{\rangle}}
\lstset{
extendedchars=false,
inputencoding=utf8x,
tabsize=1
}
\hypersetup{bookmarksopenlevel=2}
\title{
INFORMATION AND COMMUNICATION TECHNOLOGIES\\
(ICT)\\
PROGRAMME\\
\vspace*{1cm}Project FP7-ICT-2009-C-243881 {\cerco}}
\date{ }
\author{}
\begin{document}
\thispagestyle{empty}
\vspace*{-1cm}
\begin{center}
\includegraphics[width=0.6\textwidth]{../../style/cerco_logo.png}
\end{center}
\begin{minipage}{\textwidth}
\maketitle
\end{minipage}
\vspace*{0.5cm}
\begin{center}
\begin{LARGE}
\bf
Proof outline for the correctness of the CerCo compiler
\end{LARGE}
\end{center}
\vspace*{2cm}
\begin{center}
\begin{large}
Version 1.0
\end{large}
\end{center}
\vspace*{0.5cm}
\begin{center}
\begin{large}
Main Authors:\\
B. Campbell, D. Mulligan, P. Tranquilli, C. Sacerdoti Coen
\end{large}
\end{center}
\vspace*{\fill}
\noindent
Project Acronym: {\cerco}\\
Project full title: Certified Complexity\\
Proposal/Contract no.: FP7-ICT-2009-C-243881 {\cerco}\\
\clearpage \pagestyle{myheadings} \markright{{\cerco}, FP7-ICT-2009-C-243881}
\tableofcontents
\section{Introduction}
\label{sect.introduction}
In the last project review of the CerCo project, the project reviewers
recommended us to quickly outline a paper-and-pencil correctness proof
for each of the stages of the CerCo compiler in order to allow for an
estimation of the complexity and time required to complete the formalization
of the proof. This has been possible starting from month 18 when we have
completed the formalization in Matita of the datastructures and code of
the compiler.
In this document we provide a very high-level, pen-and-paper
sketch of what we view as the best path to completing the correctness proof
for the compiler. In particular, for every translation between two intermediate languages, in both the front- and back-ends, we identify the key translation steps, and identify some invariants that we view as being important for the correctness proof. We sketch the overall correctness results, and also briefly describe the parts of the proof that have already
been completed at the end of the First Period.
In the last section we finally present an estimation of the effort required
for the certification in Matita of the compiler and we draw conclusions.
\section{Front-end: Clight to RTLabs}
The front-end of the CerCo compiler consists of several stages:
\begin{center}
\begin{minipage}{.8\linewidth}
\begin{tabbing}
\quad \= $\downarrow$ \quad \= \kill
\textsf{Clight}\\
\> $\downarrow$ \> cast removal\\
\> $\downarrow$ \> add runtime functions\footnote{Following the last project
meeting we intend to move this transformation to the back-end}\\
\> $\downarrow$ \> cost labelling\\
\> $\downarrow$ \> loop optimizations\footnote{\label{lab:opt2}To be ported from the untrusted compiler and certified only in case of early completion of the certification of the other passes.} (an endo-transformation)\\
\> $\downarrow$ \> partial redundancy elimination$^{\mbox{\scriptsize \ref{lab:opt2}}}$ (an endo-transformation)\\
\> $\downarrow$ \> stack variable allocation and control structure
simplification\\
\textsf{Cminor}\\
\> $\downarrow$ \> generate global variable initialisation code\\
\> $\downarrow$ \> transform to RTL graph\\
\textsf{RTLabs}\\
\> $\downarrow$ \> \\
\>\,\vdots
\end{tabbing}
\end{minipage}
\end{center}
Here, by `endo-transformation', we mean a mapping from language back to itself:
the loop optimization step maps the Clight language to itself.
%Our overall statements of correctness with respect to costs will
%require a correctly labelled program
There are three layers in most of the proofs proposed:
\begin{enumerate}
\item invariants closely tied to the syntax and transformations using
dependent types (such as the presence of variable names in environments),
\item a forward simulation proof relating each small-step of the
source to zero or more steps of the target, and
\item proofs about syntactic properties of the cost labelling.
\end{enumerate}
The first will support both functional correctness and allow us to
show the totality of some of the compiler stages (that is, those
stages of the compiler cannot fail). The second provides the main
functional correctness result, including the preservation of cost
labels in the traces, and the last will be crucial for applying
correctness results about the costings from the back-end by showing
that they appear in enough places so that we can assign all of the
execution costs to them.
We will also prove that a suitably labelled RTLabs trace can be turned
into a \emph{structured trace} which splits the execution trace into
cost-label to cost-label chunks with nested function calls. This
structure was identified during work on the correctness of the
back-end cost analysis as retaining important information about the
structure of the execution that is difficult to reconstruct later in
the compiler.
\subsection{Clight cast removal}
This transformation removes some casts inserted by the parser to make
arithmetic promotion explicit but which are superfluous (such as
\lstinline[language=C]'c = (short)((int)a + (int)b);' where
\lstinline'a' and \lstinline'b' are \lstinline[language=C]'short').
This is necessary for producing good code for our target architecture.
It only affects Clight expressions, recursively detecting casts that
can be safely eliminated. The semantics provides a big-step
definition for expression, so we should be able to show a lock-step
forward simulation between otherwise identical states using a lemma
showing that cast elimination does not change the evaluation of
expressions. This lemma will follow from a structural induction on
the source expression. We have already proved a few of the underlying
arithmetic results necessary to validate the approach.
\subsection{Clight cost labelling}
This adds cost labels before and after selected statements and
expressions, and the execution traces ought to be equivalent modulo
the new cost labels. Hence it requires a simple forward simulation
with a limited amount of stuttering whereever a new cost label is
introduced. A bound can be given for the amount of stuttering allowed
based on the statement or continuation to be evaluated next.
We also intend to show three syntactic properties about the cost
labelling:
\begin{enumerate}
\item every function starts with a cost label,
\item every branching instruction is followed by a cost label (note that
exiting a loop is treated as a branch), and
\item the head of every loop (and any \lstinline'goto' destination) is
a cost label.
\end{enumerate}
These can be shown by structural induction on the source term.
\subsection{Clight to Cminor translation}
This translation is the first to introduce some invariants, with the
proofs closely tied to the implementation by dependent typing. These
are largely complete and show that the generated code enjoys:
\begin{itemize}
\item some minimal type safety shown by explicit checks on the
Cminor types during the transformation (a little more work remains
to be done here, but follows the same form);
\item that variables named in the parameter and local variable
environments are distinct from one another, again by an explicit
check;
\item that variables used in the generated code are present in the
resulting environment (either by checking their presence in the
source environment, or from a list of freshly generated temporary variables);
and
\item that all \lstinline[language=C]'goto' labels are present (by
checking them against a list of source labels and proving that all
source labels are preserved).
\end{itemize}
The simulation will be similar to the relevant stages of CompCert
(Clight to Csharpminor and Csharpminor to Cminor --- in the event that
the direct proof is unwieldy we could introduce an intermediate
language corresponding to Csharpminor). During early experimentation
with porting CompCert definitions to the Matita proof assistant we
found little difficulty reproving the results for the memory model, so
we plan to port the memory injection properties and use them to relate
Clight in-memory variables with either the value of the local variable or a
stack slot, depending on how it was classified.
This should be sufficient to show the equivalence of (big-step)
expression evaluation. The simulation can then be shown by relating
corresponding blocks of statement and continuations with their Cminor
counterparts and proving that a few steps reaches the next matching
state.
The syntactic properties required for cost labels remain similar and a
structural induction on the function bodies should be sufficient to
show that they are preserved.
\subsection{Cminor global initialisation code}
This short phase replaces the global variable initialisation data with
code that executes when the program starts. Each piece of
initialisation data in the source is matched by a new statement
storing that data. As each global variable is allocated a distinct
memory block, the program state after the initialisation statements
will be the same as the original program's state at the start of
execution, and will proceed in the same manner afterwards.
% Actually, the above is wrong...
% ... this ought to be in a fresh main function with a fresh cost label
\subsection{Cminor to RTLabs translation}
In this part of the compiler we transform the program's functions into
control flow graphs. It is closely related to CompCert's Cminorsel to
RTL transformation, albeit with target-independent operations.
We already enforce several invariants with dependent types: some type
safety, mostly shown using the type information from Cminor; and
that the graph is closed (by showing that each successor was recently
added, or corresponds to a \lstinline[language=C]'goto' label which
are all added before the end). Note that this relies on a
monotonicity property; CompCert maintains a similar property in a
similar way while building RTL graphs. We will also add a result
showing that all of the pseudo-register names are distinct for use by
later stages using the same method as Cminor.
The simulation will relate Cminor states to RTLabs states which are about to
execute the code corresponding to the Cminor statement or continuation.
Each Cminor statement becomes zero or more RTLabs statements, with a
decreasing measure based on the statement and continuations similar to
CompCert's. We may also follow CompCert in using a relational
specification of this stage so as to abstract away from the functional
(and highly dependently typed) definition.
The first two labelling properties remain as before; we will show that
cost labels are preserved, so the function entry point will be a cost
label, and successors to any statement that are cost labels map still
map to cost labels, preserving the condition on branches. We replace
the property for loops with the notion that we will always reach a
cost label or the end of the function after following a bounded number of
successors. This can be easily seen in Cminor using the requirement
for cost labels at the head of loops and after gotos. It remains to
show that this is preserved by the translation to RTLabs. % how?
\subsection{RTLabs structured trace generation}
This proof-only step incorporates the function call structure and cost
labelling properties into the execution trace. As the function calls
are nested within the trace, we need to distinguish between
terminating and non-terminating function calls. Thus we use the
excluded middle (specialised to a function termination property) to do
this.
Structured traces for terminating functions are built by following the
flat trace, breaking it into chunks between cost labels and
recursively processing function calls. The main difficulties here are
the non-structurally recursive nature of the function (instead we use
the size of the termination proof as a measure) and using the RTLabs
cost labelling properties to show that the constraints of the
structured traces are observed. We also show that the lower stack
frames are preserved during function calls in order to prove that
after returning from a function call we resume execution of the
correct code. This part of the work has already been constructed, but
still requires a simple proof to show that flattening the structured
trace recreates the original flat trace.
The non-terminating case follows the trace like the terminating
version to build up chunks of trace from cost-label to cost-label
(which, by the finite distance to a cost label property shown before,
can be represented by an inductive type). These chunks are chained
together in a coinductive data structure that can represent
non-terminating traces. The excluded middle is used to decide whether
function calls terminate, in which case the function described above
constructs an inductive terminating structured trace which is nested
in the caller's trace. Otherwise, another coinductive constructor is
used to embed the non-terminating trace of the callee, generated by
corecursion. This part of the trace transformation is currently under
construction, and will also need a flattening result to show that it
is correct.
\section{Backend: RTLabs to machine code}
\label{sect.backend.rtlabs.machine.code}
The compiler backend consists of the following intermediate languages, and stages of translation:
\begin{center}
\begin{minipage}{.8\linewidth}
\begin{tabbing}
\quad \=\,\vdots\= \\
\> $\downarrow$ \>\\
\> $\downarrow$ \quad \= \kill
\textsf{RTLabs}\\
\> $\downarrow$ \> copy propagation\footnote{\label{lab:opt}To be ported from the untrusted compiler and certified only in case of early completion of the certification of the other passes.} (an endo-transformation) \\
\> $\downarrow$ \> instruction selection\\
\> $\downarrow$ \> change of memory models in compiler\\
\textsf{RTL}\\
\> $\downarrow$ \> constant propagation$^{\mbox{\scriptsize \ref{lab:opt}}}$ (an endo-transformation) \\
\> $\downarrow$ \> calling convention made explicit \\
\> $\downarrow$ \> layout of activation records \\
\textsf{ERTL}\\
\> $\downarrow$ \> register allocation and spilling\\
\> $\downarrow$ \> dead code elimination\\
\textsf{LTL}\\
\> $\downarrow$ \> function linearisation\\
\> $\downarrow$ \> branch compression (an endo-transformation) \\
\textsf{LIN}\\
\> $\downarrow$ \> relabeling\\
\textsf{ASM}\\
\> $\downarrow$ \> pseudoinstruction expansion\\
\textsf{MCS-51 machine code}\\
\end{tabbing}
\end{minipage}
\end{center}
\subsection{Graph translations}
RTLabs and most intermediate languages in the back-end have a graph
representation:
the code of each function is represented by a graph of instructions.
The graph maps a set of labels (the names of the nodes) to the instruction
stored at that label (the nodes of the graph).
Instructions reference zero or more additional labels that are the immediate
successors of the instruction: zero for return from functions; more than one
for conditional jumps and calls; one in all other cases. The references
from one instruction to its immediates are the arcs of the graph.
Status of graph languages always have a program counter that holds a
representation of a reference to the current instruction.
A translation between two consecutive graph languages maps each instruction
stored at location $l$ in the first graph and with immediate successors
$\{l_1,\ldots,l_n\}$ to a subgraph of the output graph that has a single
entry point at location $l$ and exit arcs to $\{l_1,\ldots,l_n\}$. Moreover,
the labels of all non entry nodes in the subgraph are distinct from all the
labels in the source graph.
In order to simplify the translations and the relative proofs of forward
simulation, after the release of D4.2 and D4.3, we have provided:
\begin{itemize}
\item a new data type (called \texttt{blist}) that represents a
sequence of instructions to be added to the output graph.
The ``b'' in the name stands for binder, since a \texttt{blist} is
either empty, an extension of a \texttt{blist} with an instruction
at the front, or the generation of a fresh quantity followed by a
\texttt{blist}. The latter feature is used, for instance, to generate
fresh register names. The instructions in the list are unlabelled and
all of them but the last one are also sequential, like in a linear program.
\item a new iterator (called \texttt{b\_graph\_translate}) of type
\begin{displaymath}
\mathtt{b\_graph\_translate}: (\mathtt{label} \rightarrow \mathtt{blist})
\rightarrow \mathtt{graph} \rightarrow \mathtt{graph}
\end{displaymath}
The iterator transform the input graph in the output graph by replacing
each node with the graph that corresponds to the linear \texttt{blist}
obtained by applying the function in input to the node label.
\end{itemize}
Using the iterator above, the code can be written in such a way that
the programmer does not see any distinction between writing a transformation
on linear or graph languages.
In order to prove simulations for translations obtained using the iterator,
we will prove the following theorem:
\begin{align*}
\mathtt{theorem} &\ \mathtt{b\_graph\_translate\_ok}: \\
& \forall f.\forall G_{i}.\mathtt{let}\ G_{\sigma} := \mathtt{b\_graph\_translate}\ f\ G_{i}\ \mathtt{in} \\
& \forall l \in G_{i}.\mathtt{subgraph}\ (f\ l)\ l\ (next \ l \ G_i)\ G_{\sigma}
\end{align*}
Here \texttt{subgraph} is a computational predicate that given a \texttt{blist}
$[i_1, \ldots, i_n]$, an entry label $l$, an exit label $l'$ and a graph $G$
expands to the fact that fetching from $G$ at address $l$ one retrieves a node
$i_1$ with a successor $l_1$ that, when fetched, yields a node $i_2$ with a
successor $l_2$ such that \ldots. The successor of $i_n$ is $l'$.
Proving a forward simulation diagram of the following kind using the theorem
above is now as simple as doing the same using standard small step operational
semantics over linear languages.
\begin{align*}
\mathtt{lemma} &\ \mathtt{execute\_1\_step\_ok}: \\
& \forall s. \mathtt{let}\ s' := s\ \sigma\ \mathtt{in} \\
& \mathtt{let}\ l := pc\ s\ \mathtt{in} \\
& s \stackrel{1}{\rightarrow} s^{*} \Rightarrow \exists n. s' \stackrel{n}{\rightarrow} s'^{*} \wedge s'^{*} = s'\ \sigma
\end{align*}
Because of the fact that graph translation preserves entry and exit labels of
translated statements, the state translation function $\sigma$ will simply
preserve the value of the program counter. The program code, which is
part of the state, is translated using the iterator.
The proof is then roughly the following. Let $l$ be the program counter of the
input state $s$. We proceed by cases on the current instruction of $s$.
Let $[i_1, \ldots, i_n]$ be the \texttt{blist} associated to $l$ and $s$
by the translation function. The witness required for the existential
statement is simply $n$. By applying the theorem above we know that the
next $n$ instructions that will be fetched from $s\ \sigma$ will be
$[i_1, \ldots, i_n]$ and it is now sufficient to prove that they simulate
the original instruction.
\subsection{The RTLabs to RTL translation}
\label{subsect.rtlabs.rtl.translation}
\subsubsection*{Translation of values and memory}
The RTLabs to RTL translation pass marks the frontier between the two memory models used in the CerCo project.
As a result, we require some method of translating between the values that the two memory models permit.
Suppose we have such a translation, $\sigma$.
Then the translation between values of the two memory models may be pictured with:
\begin{displaymath}
\mathtt{Value} ::= \bot \mid \mathtt{int(size)} \mid \mathtt{float} \mid \mathtt{null} \mid \mathtt{ptr} \quad\stackrel{\sigma}{\longrightarrow}\quad \mathtt{BEValue} ::= \bot \mid \mathtt{byte} \mid \mathtt{null}_i \mid \mathtt{ptr}_i
\end{displaymath}
In the front-end, we have both integer and float values, where integer values are `sized', along with null values and pointers. Some frontenv values are
representables in a byte, but some others require more bits.
In the back-end model all values are meant to be represented in a single byte.
Values can thefore be undefined, be one byte long integers or be indexed
fragments of a pointer, null or not. Floats values are no longer present, as floating point arithmetic is not supported by the CerCo compiler.
The $\sigma$ map implements a one-to-many relation: a single front-end value
is mapped to a sequence of back-end values when its size is more then one byte.
We further require a map, $\sigma$, which maps the front-end \texttt{Memory} and the back-end's notion of \texttt{BEMemory}. Both kinds of memory can be
thought as an instance of a generic \texttt{Mem} data type parameterized over
the kind of values stored in memory.
\begin{displaymath}
\mathtt{Mem}\ \alpha = \mathtt{Block} \rightarrow (\mathbb{Z} \rightarrow \alpha)
\end{displaymath}
Here, \texttt{Block} consists of a \texttt{Region} paired with an identifier.
\begin{displaymath}
\mathtt{Block} ::= \mathtt{Region} \times \mathtt{ID}
\end{displaymath}
We now have what we need for defining what is meant by the `memory' in the backend memory model.
Namely, we instantiate the previously defined \texttt{Mem} type with the type of back-end memory values.
\begin{displaymath}
\mathtt{BEMem} = \mathtt{Mem}~\mathtt{BEValue}
\end{displaymath}
Memory addresses consist of a pair of back-end memory values:
\begin{displaymath}
\mathtt{Address} = \mathtt{BEValue} \times \mathtt{BEValue} \\
\end{displaymath}
The back- and front-end memory models differ in how they represent sized integeer values in memory.
In particular, the front-end stores integer values as a header, with size information, followed by a string of `continuation' blocks, marking out the full representation of the value in memory.
In contrast, the layout of sized integer values in the back-end memory model consists of a series of byte-sized `chunks':
\begin{center}
\begin{picture}(0, 25)
\put(-125,0){\framebox(25,25)[c]{\texttt{v,4}}}
\put(-100,0){\framebox(25,25)[c]{\texttt{cont}}}
\put(-75,0){\framebox(25,25)[c]{\texttt{cont}}}
\put(-50,0){\framebox(25,25)[c]{\texttt{cont}}}
\put(-15,10){\vector(1, 0){30}}
\put(25,0){\framebox(25,25)[c]{\texttt{\texttt{v$_1$}}}}
\put(50,0){\framebox(25,25)[c]{\texttt{\texttt{v$_2$}}}}
\put(75,0){\framebox(25,25)[c]{\texttt{\texttt{v$_3$}}}}
\put(100,0){\framebox(25,25)[c]{\texttt{\texttt{v$_4$}}}}
\end{picture}
\end{center}
Chunks for pointers are pairs made of the original pointer and the index of the chunk.
Therefore, when assembling the chunks together, we can always recognize if all chunks refer to the same value or if the operation is meaningless.
The differing memory representations of values in the two memory models imply the need for a series of lemmas on the actions of \texttt{load} and \texttt{store} to ensure correctness.
The first lemma required has the following statement:
\begin{displaymath}
\mathtt{load}\ s\ a\ M = \mathtt{Some}\ v \rightarrow \forall i \leq s.\ \mathtt{load}\ s\ (a + i)\ \sigma(M) = \mathtt{Some}\ v_i
\end{displaymath}
That is, if we are successful in reading a value of size $s$ from memory at address $a$ in front-end memory, then we should successfully be able to read all of its chunks from memory in the back-end memory at appropriate address (from address $a$ up to and including address $a + i$, where $i \leq s$).
Next, we must show that \texttt{store} properly commutes with the $\sigma$-map between memory spaces:
\begin{displaymath}
\sigma(\mathtt{store}\ a\ v\ M) = \mathtt{store}\ \sigma(v)\ \sigma(a)\ \sigma(M)
\end{displaymath}
That is, if we store a value \texttt{v} in the front-end memory \texttt{M} at address \texttt{a} and transform the resulting memory with $\sigma$, then this is equivalent to storing a transformed value $\mathtt{\sigma(v)}$ at address $\mathtt{\sigma(a)}$ into the back-end memory $\mathtt{\sigma(M)}$.
Finally, the commutation properties between \texttt{load} and \texttt{store} are weakened in the $\sigma$-image of the memory.
Writing \texttt{load}$^*$ for the multiple consecutive iterations of \texttt{load} used to fetch all chunks of a value, we must prove that, when $a \neq a'$:
\begin{displaymath}
\texttt{load}^* \sigma(a)\ (\mathtt{store}\ \sigma(a')\ \sigma(v)\ \sigma(M)) = \mathtt{load}^*\ \sigma(s)\ \sigma(a)\ \sigma(M)
\end{displaymath}
That is, suppose we store a transformed value $\mathtt{\sigma(v)}$ into a back-end memory $\mathtt{\sigma(M)}$ at address $\mathtt{\sigma(a')}$, using \texttt{store}, and then load from the address $\sigma(a)$. Even if $a$ and $a'$ are
distinct by hypothesis, there is a priori no guarantee that the consecutive
bytes for the value stored at $\sigma(a)$ are disjoint from those for the
values stored at $\sigma(a')$. The fact that this holds is a non-trivial
property of $\sigma$ to be proved.
\subsubsection*{Translation of RTLabs states}
RTLabs states come in three flavours:
\begin{displaymath}
\begin{array}{rll}
\mathtt{State} & ::= & (\mathtt{State} : \mathtt{Frame}^* \times \mathtt{Frame} \\
& \mid & \mathtt{Call} : \mathtt{Frame}^* \times \mathtt{Args} \times \mathtt{Return} \times \mathtt{Fun} \\
& \mid & \mathtt{Return} : \mathtt{Frame}^* \times \mathtt{Value} \times \mathtt{Return}) \times \mathtt{Mem}
\end{array}
\end{displaymath}
\texttt{State} is the default state in which RTLabs programs are almost always in.
The \texttt{Call} state is only entered when a call instruction is being executed, and then we immediately return to being in \texttt{State}.
Similarly, \texttt{Return} is only entered when a return instruction is being executed, before returning immediately to \texttt{State}.
All RTLabs states are accompanied by a memory, \texttt{Mem}, with \texttt{Call} and \texttt{Return} keeping track of arguments, return addresses and the results of functions.
\texttt{State} keeps track of a list of stack frames.
RTL states differ from their RTLabs counterparts, in including a program counter \texttt{PC}, stack-pointer \texttt{SP}, internal stack pointer \texttt{ISP}, a carry flag \texttt{CARRY} and a set of registers \texttt{REGS}:
\begin{displaymath}
\mathtt{State} ::= \mathtt{Frame}^* \times \mathtt{PC} \times \mathtt{SP} \times \mathtt{ISP} \times \mathtt{CARRY} \times \mathtt{REGS}
\end{displaymath}
The internal stack pointer \texttt{ISP}, and its relationship with the stack pointer \texttt{SP}, needs some comment.
Due to the design of the MCS-51, and its minuscule stack, it was decided that the compiler would implement an emulated stack in external memory.
As a result, we have two stack pointers in our state: \texttt{ISP}, which is the real, hardware stack, and \texttt{SP}, which is the stack pointer of the emulated stack in memory.
The emulated stack is used for pushing and popping stack frames when calling or returning from function calls, however this is done using the hardware stack, indexed by \texttt{ISP} as an intermediary.
Instructions like \texttt{LCALL} and \texttt{ACALL} are hardwired by the processor's design to push the return address on to the hardware stack. Therefore after a call has been made, and before a call returns, the compiler emits code to move the return address back and forth the two stacks. Parameters, return values
and local variables are only present in the external stack.
As a result, for most of the execution of the processor, the hardware stack is empty, or contains a single item ready to be moved into external memory.
Once more, we require a relation $\sigma$ between RTLabs states and RTL states.
Because $\sigma$ is one-to-many and, morally, a multi-function,
we use in the following the functional notation for $\sigma$, using $\star$
in the output of $\sigma$ to mean that any value is accepted.
\begin{displaymath}
\mathtt{State} \stackrel{\sigma}{\longrightarrow} \mathtt{State}
\end{displaymath}
Translating an RTLabs state to an RTL state proceeds by cases on the particular type of state we are trying to translate, either a \texttt{State}, \texttt{Call} or a \texttt{Return}.
For \texttt{State} we perform a further case analysis of the top stack frame, which decomposes into a tuple holding the current program counter value, the current stack pointer and the value of the registers:
\begin{displaymath}
\sigma(\mathtt{State} (\mathtt{Frame}^* \times \mathtt{\langle PC, REGS, SP \rangle})) \longrightarrow ((\sigma(\mathtt{Frame}^*), \sigma(\mathtt{PC}), \sigma(\mathtt{SP}), \star, \star, \sigma(\mathtt{REGS})), \sigma(\mathtt{Mem}))
\end{displaymath}
Translation then proceeds by translating the remaining stack frames, as well as the contents of the top stack frame. Any value for the internal stack pointer
and the carry bit is admitted.
Translating \texttt{Call} and \texttt{Return} states is more involved, as a commutation between a single step of execution and the translation process must hold:
\begin{displaymath}
\sigma(\mathtt{Return}(-)) \longrightarrow \sigma \circ \text{return one step}
\end{displaymath}
\begin{displaymath}
\sigma(\mathtt{Call}(-)) \longrightarrow \sigma \circ \text{call one step}
\end{displaymath}
Here \emph{return one step} and \emph{call one step} refer to a pair of commuting diagrams relating the one-step execution of a call and return state and translation of both.
We provide the one step commuting diagrams in Figure~\ref{fig.commuting.diagrams}. The fact that one execution step in the source language is not performed
in the target language is not problematic for preservation of divergence
because it is easy to show that every step from a \texttt{Call} or
\texttt{Return} state is always preceeded/followed by one step that is always
simulated.
\begin{figure}
\begin{displaymath}
\begin{diagram}
s & \rTo^{\text{one step of execution}} & s' \\
& \rdTo & \dTo \\
& & \llbracket s'' \rrbracket
\end{diagram}
\end{displaymath}
\begin{displaymath}
\begin{diagram}
s & \rTo^{\text{one step of execution}} & s' \\
& \rdTo & \dTo \\
& & \llbracket s'' \rrbracket
\end{diagram}
\end{displaymath}
\caption{The one-step commuting diagrams for \texttt{Call} and \texttt{Return} state translations}
\label{fig.commuting.diagrams}
\end{figure}
\subsubsection*{The forward simulation proof}
The forward simulation proof for all steps that do not involve function calls are lengthy, but routine.
They consist of simulating a front-end operation on front-end pseudo-registers and the front-end memory with sequences of back-end operations on the back-end pseudo-registers and back-end memory.
The properties of $\sigma$ presented before that relate values and memories will need to be heavily exploited.
The simulation of invocation of functions and returns from functions is less obvious.
We sketch here what happens on the source code and on its translation.
\subparagraph{Function call/return in RTLabs}
\begin{displaymath}
\begin{array}{rcl}
\mathtt{Call(id,\ args,\ dst,\ pc) \in State(Frame^*, Frame)} & \longrightarrow & \mathtt{Call(M(args), dst)}, \\
& & \mathtt{PUSH(Frame[pc := after\_return])}
\end{array}
\end{displaymath}
Suppose we are given a \texttt{State} with a list of stack frames, with the top frame being \texttt{Frame}.
Suppose also that the program counter in \texttt{Frame} points to a \texttt{Call} instruction, complete with arguments and destination address.
Then this is executed by entering into a \texttt{Call} state where the arguments are loaded from memory, and the address pointing to the instruction immediately following the \texttt{Call} instruction is filled in, with the current stack frame being pushed on top of the stack with the return address substituted for the program counter.
Now, what happens next depends on whether we are executing an internal or an external function.
In the case where the call is to an external function, we have:
\begin{displaymath}
\begin{array}{rcl}
\mathtt{Call(M(args), dst)}, & \stackrel{\mathtt{ret\_val = f(M(args))}}{\longrightarrow} & \mathtt{Return(ret\_val,\ dst,\ PUSH(...))} \\
\mathtt{PUSH(current\_frame[pc := after\_return])} & &
\end{array}
\end{displaymath}
That is, the call to the external function enters a return state after first computing the return value by executing the external function on the arguments.
Then the return state restores the program counter by popping the stack, and execution proceeds in a new \texttt{State}:
\begin{displaymath}
\begin{array}{rcl}
\mathtt{Return(ret\_val,\ dst,\ PUSH(...))} & \longrightarrow & \mathtt{pc = POP\_STACK(regs[dst := M(ret\_val)],\ pc)} \\
& & \mathtt{State(regs[dst := M(ret\_val),\ pc)}
\end{array}
\end{displaymath}
Suppose we are executing an internal function, however:
\begin{displaymath}
\begin{array}{rcl}
\mathtt{Call(M(args), dst)} & \longrightarrow & \mathtt{sp = alloc,\ regs = \emptyset[- := params]} \\
\mathtt{PUSH(current\_frame[pc := after\_return])} & & \mathtt{State(regs,\ sp,\ pc_\emptyset,\ dst)}
\end{array}
\end{displaymath}
A new stack frame is allocated and its address is stored in the stack pointer.
The register map is initialized first to the empty map, assigning an undefined value to all register, before the value of the parameters is inserted into the map into the argument registers, and a new \texttt{State} follows.
Eventually, a Return instruction is faced,
the return value is fetched from the registers map,
the stack frame is deallocated
and a Return state is entered:
\begin{displaymath}
\begin{array}{rcl}
\mathtt{Return(id,\ args,\ dst,\ pc) \in State(Frame^*, Frame)} & \longrightarrow & \mathtt{free(sp)} \\
& & \mathtt{Return(M(ret\_val), dst, Frames)}
\end{array}
\end{displaymath}
Then the return state restores the program counter by popping the stack, and execution proceeds in a new \texttt{State}, like the case for external functions:
\begin{displaymath}
\begin{array}{rcl}
\mathtt{free(sp)} & \longrightarrow & \mathtt{pc = POP\_STACK(regs[dst := M(ret\_val)],\ pc)} \\
\mathtt{Return(M(ret\_val), dst, frames)} & & \mathtt{State(regs[dst := M(ret\_val),\ pc)}
\end{array}
\end{displaymath}
\subparagraph{The RTLabs to RTL translation for function calls}
Return instructions are translated to return instructions:
\begin{displaymath}
\mathtt{Return} \longrightarrow \mathtt{Return}
\end{displaymath}
\texttt{Call} instructions are translated to \texttt{Call\_ID} instructions:
\begin{displaymath}
\mathtt{Call(id,\ args,\ dst,\ pc)} \longrightarrow \mathtt{CALL\_ID(id,\ \Sigma'(args),\ \Sigma(dst),\ pc)}
\end{displaymath}
Here $\Sigma$ is the map, computed by the compiler,
that translate pseudo-registers holding front-end values to list of
pseudo-registers holding the chunks for the front-end values.
The specification for $\Sigma$ is that for every state $s$,
$$\sigma(s(r)) = (\sigma(s))(\Sigma(r))$$
\subparagraph{Function call/return in RTL}
In the case of RTL, execution proceeds as follows.
Suppose we are executing a \texttt{CALL\_ID} instruction.
Then a case split occurs depending on whether we are executing an internal or an external function, as in the RTLabs case:
\begin{displaymath}
\hspace{-3.5cm}
\begin{diagram}
& & \llbracket \mathtt{CALL\_ID}(\mathtt{id}, \mathtt{args}, \mathtt{dst}, \mathtt{pc})\rrbracket & & \\
& \ldTo^{\text{external}} & & \rdTo^{\text{internal}} & \\
\skull & & & &
\begin{array}{l}
\mathtt{sp = alloc,\ regs = \emptyset[- := params]} \\
\mathtt{PUSH}(\mathtt{carry}, \mathtt{regs}, \mathtt{dst}, \mathtt{return\_addr}), \mathtt{pc}_{0}, \mathtt{regs}, \mathtt{sp}
\end{array}
\end{diagram}
\end{displaymath}
Here, however, we differ from RTLabs when we attempt to execute an external function, in that we use a daemon (i.e. an axiom that can close any goal) to artificially close the case, as we have not yet implemented external functions in the backend.
The reason for this lack of implementation is as follows.
Though we have implemented an optimising assembler as the target of the compiler's backend, we have not yet implemented a linker for that assembler, so external functions can not yet be called.
Whilst external functions are carried forth throughout the entirety of the compiler's frontend, we choose not to do the same for the backend, instead eliminating them in RTL.
However, it is plausible that we could have carried external functions forth, in order to eliminate them at a later stage (i.e. when translating from LIN to assembly).
In the case of an internal function being executed, we proceed as follows.
The register map is initialized to the empty map, where all registers are assigned the undefined value, and then the registers corresponding to the function parameters are assigned the value of the parameters.
Further, the stack pointer is reallocated to make room for an extra stack frame, then a frame is pushed onto the stack with the correct address to jump back to in place of the program counter.
Note, in particular, that this final act of pushing a frame on the stack leaves us in an identical state to the RTLabs case, where the instruction
\begin{displaymath}
\mathtt{PUSH(current\_frame[pc := after\_return])}
\end{displaymath}
was executed. To summarize, up to the different numer of transitions required
to do the job, the RTL code for internal function calls closely simulates
the RTLabs code.
The execution of \texttt{Return} in RTL is similarly straightforward, with the return address, stack pointer, and so on, being computed by popping off the top of the stack, and the return value computed by the function being retrieved from memory:
\begin{align*}
\mathtt{return\_addr} & := \mathtt{top}(\mathtt{stack}) \\
v^* & := M(\mathtt{rv\_regs}) \\
\mathtt{dst}, \mathtt{sp}, \mathtt{carry}, \mathtt{regs} & := \mathtt{pop} \\
\mathtt{regs}[v^* / \mathtt{dst}] \\
\end{align*}
To summarize, the forward simulation diagrams for function call/return
XXX
Translation and execution must satisfy a pair of commutation properties for the \texttt{Return} and \texttt{Call} cases.
Starting from any \texttt{Return} or \texttt{Call} state, translating and then executing a single step must be the same as executing exactly two steps and then translating, with the intermediate state obtained by executing once also being translatable to the final state.
This is exemplified by the following diagram:
\begin{displaymath}
\begin{diagram}
s & \rTo^1 & s' & \rTo^1 & s'' \\
\dTo & & & \rdTo & \dTo \\
\llbracket s \rrbracket & \rTo(1,3)^1 & & & \llbracket s'' \rrbracket \\
\end{diagram}
\end{displaymath}
\subsection{The RTL to ERTL translation}
\label{subsect.rtl.ertl.translation}
We map RTL statuses to ERTL statuses as follows:
\begin{align*}
\mathtt{sp} & = \mathtt{RegisterSPH} / \mathtt{RegisterSPL} \\
\mathtt{graph} & \mathtt{graph} + \mathtt{prologue}(s) + \mathtt{epilogue}(s) \\
& \mathrm{where}\ s = \mathrm{callee\ saved} + \nu \mathrm{RA} \\
\end{align*}
The 16-bit RTL stack pointer \texttt{SP} is mapped to a pair of 8-bit hardware registers \texttt{RegisterSPH} and \texttt{RegisterSPL}.
The internal function graphs of RTL are augmented with an epilogue and a prologue, indexed by a set of registers, consisting of a fresh pair of registers \texttt{RA} and the set of registers that must be saved by the callee of a function.
The prologue and epilogue that are added to the function graph do the following:
\begin{align*}
\mathtt{prologue}(s) = & \mathtt{create\_new\_frame}; \\
& \mathtt{pop\ ra}; \\
& \mathtt{save\ callee\_saved}; \\
& \mathtt{get\_params} \\
& \ \ \mathtt{reg\_params}: \mathtt{move} \\
& \ \ \mathtt{stack\_params}: \mathtt{push}/\mathtt{pop}/\mathtt{move} \\
\end{align*}
That is, the prologue first creates a new stack frame, pops the return address from the stack, saves all the callee saved registers (i.e. the set \texttt{s}), fetches the parameters that are passed via registers and the stack and moves them into the correct registers.
In other words, the prologue of a function correctly sets up the calling convention used in the compiler when calling a function.
On the other hand, the epilogue undoes the action of the prologue:
\begin{align*}
\mathtt{epilogue}(s) = & \mathtt{save\ return\ to\ tmp\ real\ regs}; \\
& \mathtt{restore\_registers}; \\
& \mathtt{push\ ra}; \\
& \mathtt{delete\_frame}; \\
& \mathtt{save return} \\
\end{align*}
That is, the epilogue first saves the return value to a temporary register, restores all the registers, pushes the return address on to the stack, deletes the stack frame that the prologue created, and saves the return value.
The \texttt{CALL} instruction is translated as follows:
\begin{displaymath}
\mathtt{CALL}\ id \mapsto \mathtt{set\_params};\ \mathtt{CALL}\ id;\ \mathtt{fetch\_result}
\end{displaymath}
Here, \texttt{set\_params} and \texttt{fetch\_result} are functions that implement what the caller of the function needs to do when calling a function, as opposed to the epilogue and prologue which implement what the callee must do.
The translation from RTL to ERTL and execution functions must satisfy the following properties for \texttt{CALL} and \texttt{RETURN} instructions appropriately:
\begin{displaymath}
\begin{diagram}
\mathtt{CALL} & \rTo^1 & \mathtt{inside\ function} \\
\dTo & & \dTo \\
\underbrace{\ldots}_{\llbracket \mathtt{CALL} \rrbracket} & \rTo &
\underbrace{\ldots}_{\mathtt{prologue}} \\
\end{diagram}
\end{displaymath}
That is, if we start in a RTL \texttt{CALL} instruction, and translate this to an ERTL \texttt{CALL} instruction, then executing the RTL \texttt{CALL} instruction for one step and translating should land us in the prologue of the translated function.
A similar property for \texttt{RETURN} should also hold, substituting the prologue for the epilogue of the function being translated:
\begin{displaymath}
\begin{diagram}
\mathtt{RETURN} & \rTo^1 & \mathtt{.} \\
\dTo & & \dTo \\
\underbrace{\ldots}_{\mathtt{epilogue}} & \rTo &
\underbrace{\ldots} \\
\end{diagram}
\end{displaymath}
\subsection{The ERTL to LTL translation}
\label{subsect.ertl.ltl.translation}
During the ERTL to LTL translation pseudo-registers are stored in hardware
registers or spilled on to the stack frame. The decision is based on liveness
analysis of the ERTL code to determine what pair of pseudoregisters are live
at the same time at a given location. A coloring algorithm is then used to
choose where to store the pseudo-registers, allowing pseudo-registers that
are never live at the same time to share the same location.
We will not certify any coloring algorithm or control flow analysis.
Instead, we axiomatically assume the existence of solutions to the
coloring and liveness problems. In a later phase we plan to validate the
solutions by writing and certifying the code of a validator.
We describe the liveness analysis and colouring analysis first and then
the ERTL to LTL translation.
Throughout this section, we denote pseudoregisters with the type $\mathtt{register}$ and hardware ones with $\mathtt{hdwregister}$.
\subsubsection{Liveness analysis}
\newcommand{\declsf}[1]{\expandafter\newcommand\expandafter{\csname #1\endcsname}{\mathop{\mathsf{#1}}\nolimits}}
\declsf{Livebefore}
\declsf{Liveafter}
\declsf{Defined}
\declsf{Used}
\declsf{Eliminable}
\declsf{StatementSem}
For the liveness analysis, we aim at a map
$\ell \in \mathtt{label} \mapsto $ live registers at $\ell$.
We define the following operators on ERTL statements.
$$
\begin{array}{lL>{(ex. $}L<{)$}}
\Defined(\ell) & registers defined at $\ell$ & \ell:r_1\leftarrow r_2+r_3 \mapsto \{r_1,C\}, \ell:\mathtt{CALL}~id\mapsto \text{caller-save}
\\
\Used(\ell) & registers used at $\ell$ & \ell:r_1\leftarrow r_2+r_3 \mapsto \{r_2,r_3\}, \ell:\mathtt{CALL}~id\mapsto \text{parameters}
\end{array}
$$
Given $LA:\mathtt{label}\to\mathtt{lattice}$ (where $\mathtt{lattice}$
is the type of sets of registers\footnote{More precisely, it is the lattice
of pairs of sets of pseudo-registers and sets of hardware registers,
with pointwise operations.}), we also have have the following
predicates:
$$
\begin{array}{lL}
\Eliminable_{LA}(\ell) & iff executing $\ell$ has side-effects only on $r\notin LA(\ell)$
\\&
(ex.\ $\ell : r_1\leftarrow r_2+r_3 \mapsto (\{r_1,C\}\cap LA(\ell)\neq\emptyset),
\mathtt{CALL}id\mapsto \text{never}$)
\\
\Livebefore_{LA}(\ell) &$:=
\begin{cases}
LA(\ell) &\text{if $\Eliminable_{LA}(\ell)$,}\\
(LA(\ell)\setminus \Defined(\ell))\cup \Used(\ell) &\text{otherwise}.
\end{cases}$
\end{array}
$$
In particular, $\Livebefore$ has type $(\mathtt{label}\to\mathtt{lattice})\to
\mathtt{label}\to\mathtt{lattice}$.
The equation on which we build the fixpoint is then
$$\Liveafter(\ell) \doteq \bigcup_{\ell <_1 \ell'} \Livebefore_{\Liveafter}(\ell')$$
where $\ell <_1 \ell'$ denotes that $\ell'$ is an immediate successor of $\ell$
in the graph. We do not require the fixpoint to be the least one, so the hypothesis
on $\Liveafter$ that we require is
\begin{equation}
\label{eq:livefixpoint}
\Liveafter(\ell) \supseteq \bigcup_{\ell <_1 \ell'} \Livebefore(\ell')
\end{equation}
(for shortness we drop the subscript from $\Livebefore$).
\subsubsection{Colouring}
\declsf{Colour}
\newcommand{\at}{\mathrel{@}}
The aim of the liveness analysis is to define what properties we need
of the colouring function, which is a map (computed separately for each
internal function)
$$\Colour:\mathtt{register}\to\mathtt{hdwregister}+\mathtt{nat}$$
which identifies pseudoregisters with hardware ones if it is able to, otherwise
it spills them to the stack. We will just state what property we need from such
a map. First, we extend the definition to all types of registers by:
$$\begin{aligned}
\Colour^+:\mathtt{hdwregister}+\mathtt{register} &\to \mathtt{hdwregister}+\mathtt{nat}\\
r & \mapsto
\begin{cases}
\Colour(r) &\text{if $r\in\mathtt{register}$,}\\
r &\text{if $r\in\mathtt{hdwregister}$,}.
\end{cases}
\end{aligned}$$
The other piece of information we compute for each function is a \emph{similarity}
relation, which is an equivalence relation on all kinds of registers which depends
on the point of the program. We write
$$x\sim y \at \ell$$
to state that registers $x$ and $y$ are similar at $\ell$. The formal definition
will be given next, but intuitively it means that those two registers \emph{must}
have the same value at $\ell$. The analysis that produces this information can be
coarse: in our case, we just set two different registers to be similar at $\ell$
if at $\ell$ itself there is a move instruction between the two.
The property required of colouring is the following:
\begin{equation}
\label{eq:colourprop}
\forall \ell.\forall x,y. x,y\in \Liveafter(\ell)\Rightarrow
\Colour^+(x)=\Colour^+(y) \Rightarrow x\sim y \at\ell.
\end{equation}
\subsubsection{The translation}
For example:
$$\ell : r_1\leftarrow r_2+r_3 \mapsto \begin{cases}
\varepsilon & \text{if $\Eliminable(\ell)$},\\
\Colour(r_1) \leftarrow \Colour(r_2) + \Colour(r_3) & \text{otherwise}.
\end{cases}$$
where $\varepsilon$ is the empty block of instructions (i.e.\ a \texttt{GOTO}),
and $\Colour(r_1) \leftarrow \Colour(r_2) + \Colour(r_3)$ is a notation for a
block of instructions that take into account:
\begin{itemize}
\item load and store ops on the stack if any colouring is in fact a spilling;
\item using the accumulator to store intermediate values.
\end{itemize}
The overall effect is that if $T$ is an LTL state with $\ell(T)=\ell$
then we will have $T\to^+T'$ where $T'(\Colour(r_1))=T(\Colour(r_2))+T(\Colour(r_2))$.
We skip over the details of correctly dealing with the stack and its size.
\subsubsection{The relation between ERTL and LTL states}
Given a state $S$ in ERTL, we abuse the notation by using $S$ as the underlying map
$$S : \mathtt{hdwregister}+\mathtt{register} \to \mathtt{Value}.$$
The program counter in $S$ is written as $\ell(S)$. At this point we can state
the property asked from similarity:
\begin{equation}
\label{eq:similprop}
\forall S,S'.S\to S' \Rightarrow \forall x,y.x\sim y \at \ell(S) \Rightarrow S'(x) = S'(y).
\end{equation}
Next, we relate ERTL states with LTL ones. For a state $T$ in LTL we again
abuse the notation using $T$ as a map
$$T: \mathtt{hdwregister}+\mathtt{nat} \to \mathtt{Value}$$
which maps hardware registers and \emph{local stack offsets} to values (in particular,
$T$ as a map depends on the saved frames for computing the correct absolute
stack values).
The relation existing between the states at the two sides of this translation step,
which depends on liveness and colouring, is
then defined as
$$S\mathrel\sigma T \iff \ldots \wedge \forall x. x\in \Livebefore(\ell(S))\Rightarrow T(\Colour^+(x)) = S(x).$$
The ellipsis stands for other straightforward preservation, among which the properties
$\ell(T) = \ell(S)$ and, inductively, the preservation of frames.
\subsubsection{Proof of preservation}
We will prove the following proposition:
$$\forall S, T. S \mathrel\sigma T \Rightarrow S \to S' \Rightarrow \exists T'.T\to^+ T' \wedge S'\mathrel\sigma T'$$
(with appropriate cost-labelled trace preservation which we omit). We will call $S\mathrel \sigma T$
the inductive hypothsis, as it will be such in the complete proof by induction on the trace of the program.
As usual, this step is done by cases
on the statement at $\ell(S)$ and how it is translated. We carry out in some detail a single case, the one of
a binary operation on registers.
Suppose that $\ell(S):r_1 \leftarrow r_2+r_3$, so that
$$S'(x)=\begin{cases}S(r_1)+S(r_2) &\text{if $x=r_1$,}\\S(x) &\text{otherwise.}\end{cases}$$
\paragraph*{Case $\Eliminable(\ell(S))$.}
By definition we have $r_1\notin \Liveafter(\ell(S))$, and the translation
of the operation yields a \texttt{GOTO}. We take $T'$ the immediate successor
of $T$.
Now in order to prove $S'\mathrel\sigma T'$, take any
$$x\in\Livebefore(\ell(S'))\subseteq \Liveafter(\ell(S)) = \Livebefore(\ell(S))$$
where we have used property~\eqref{eq:livefixpoint} and the definition
of $\Livebefore$ when $\Eliminable(\ell(S))$. We get the following chain of equalities:
$$T'(\Colour^+(x))\stackrel 1=T(\Colour^+(x))\stackrel 2=S(x) \stackrel 3= S'(x)$$
where
\begin{enumerate}
\item is because $T'$ has the same store as $T$,
\item is by inductive hypothesis as $x\in\Livebefore(\ell(S))$,
\item is because $x\neq r_1$, as $r_1\notin \Liveafter(\ell(S))\ni x$.
\end{enumerate}
\paragraph*{Case $\neg\Eliminable(\ell(S))$.}
We then have $r_1\in\Liveafter(\ell(S))$, and
$$\Livebefore(\ell(S))=(\Liveafter(\ell(S))\setminus\{r_1\})\cup\{r_2,r_3\}.$$
Moreover the statement is translated to $\Colour(r_1)\leftarrow\Colour(r_2)+\Colour(r_3)$,
and we take the $T'\leftarrow^+T$ such that $T'(\Colour(r_1))=T(\Colour(r_2))+T(\Colour(r_3))$ and
$T'(\Colour^+(x))=T(\Colour^+(x))$ for all $x$ with $\Colour^+(x)\neq\Colour(r_1)$.
Take any $x\in\Livebefore(\ell(S'))\subseteq \Liveafter(\ell(S))$ (by property~\eqref{eq:livefixpoint}).
If $\Colour^+(x)=\Colour(r_1)$, we have by property~\eqref{eq:colourprop}
that $x\sim r_1\at \ell(S)$ (as both $r_1,x\in\Liveafter(\ell(S))$, so that
$$T'(\Colour^+(x))=T(\Colour(r_2))+T(\Colour(r_3))\stackrel 1=S(r_2)+S(r_3)=S'(r_1)\stackrel 2=S(x)$$
where
\begin{enumerate}
\item is by two uses of inductive hypothesis, as $r_2,r_3\in\Livebefore(\ell(S))$,
\item is by property~\eqref{eq:similprop}\footnote{Notice that in our particular implementation
for this case of binary op $x\sim r_1\at\ell(S)$ implies $x=r_1$. But nothing prevents us from
employing more fine euristics for similarity.}.
\end{enumerate}
If $\Colour^+(x)\neq\Colour(r_1)$ (so in particular $x\neq r_1$), then $x\in\Livebefore(\ell(S))$,
so by inductive hypothesis we have
$$T'(\Colour^+(x))=T(\Colour^+(x))=S(x)=S'(x).$$
\subsection{The LTL to LIN translation}
\label{subsect.ltl.lin.translation}
Ad detailed elsewhere in the reports, due to the parameterized representation of
the back-end languages, the pass described here is actually much more generic
than the translation from LTL to LIN. It consists in a linearization pass
that maps any graph-based back-end language to its corresponding linear form,
preserving its semantics. In the rest of the section, however, we will keep
the names LTL and LIN for the two partial instantiations of the parameterized
language.
We require a map, $\sigma$, from LTL statuses, where program counters are represented as labels in a graph data structure, to LIN statuses, where program counters are natural numbers:
\begin{displaymath}
\mathtt{pc : label} \stackrel{\sigma}{\longrightarrow} \mathbb{N}
\end{displaymath}
The LTL to LIN translation pass also linearises the graph data structure into a list of instructions.
Pseudocode for the linearisation process is as follows:
\begin{lstlisting}
let rec linearise graph visited required generated todo :=
match todo with
| l::todo ->
if l $\in$ visited then
let generated := generated $\cup\ \{$ Goto l $\}$ in
let required := required $\cup$ l in
linearise graph visited required generated todo
else
-- Get the instruction at label `l' in the graph
let lookup := graph(l) in
let generated := generated $\cup\ \{$ lookup $\}$ in
-- Find the successor of the instruction at label `l' in the graph
let successor := succ(l, graph) in
let todo := successor::todo in
linearise graph visited required generated todo
| [] -> (required, generated)
\end{lstlisting}
It is easy to see that this linearisation process eventually terminates.
In particular, the size of the visited label set is monotonically increasing, and is bounded above by the size of the graph that we are linearising.
The initial call to \texttt{linearise} sees the \texttt{visited}, \texttt{required} and \texttt{generated} sets set to the empty set, and \texttt{todo} initialized with the singleton list consisting of the entry point of the graph.
We envisage needing to prove the following invariants on the linearisation function above:
\begin{enumerate}
\item
$\mathtt{visited} \approx \mathtt{generated}$, where $\approx$ is \emph{multiset} equality, as \texttt{generated} is a set of instructions where instructions may mention labels multiple times, and \texttt{visited} is a set of labels,
\item
$\forall \mathtt{l} \in \mathtt{generated}.\ \mathtt{succ(l,\ graph)} \subseteq \mathtt{required} \cup \mathtt{todo}$,
\item
$\mathtt{required} \subseteq \mathtt{visited}$,
\item
$\mathtt{visited} \cap \mathtt{todo} = \emptyset$.
\end{enumerate}
The invariants collectively imply the following properties, crucial to correctness, about the linearisation process:
\begin{enumerate}
\item
Every graph node is visited at most once,
\item
Every instruction that is generated is generated due to some graph node being visited,
\item
The successor instruction of every instruction that has been visited already will eventually be visited too.
\end{enumerate}
Note, because the LTL to LIN transformation is the first time the code of
a function is linearised in the back-end, we must discover a notion of `well formed function code' suitable for linearised forms.
In particular, we see the notion of well formedness (yet to be formally defined) resting on the following conditions:
\begin{enumerate}
\item
For every jump to a label in a linearised function code, the target label exists at some point in the function code,
\item
Each label is unique, appearing only once in the function code,
\item
The final instruction of a function code must be a return or an unconditional
jump.
\end{enumerate}
We assume that these properties will be easy consequences of the invariants on the linearisation function defined above.
The final condition above is potentially a little opaque, so we explain further.
The only instructions that can reasonably appear in final position at the end of a function code are returns or backward jumps, as any other instruction would cause execution to `fall out' of the end of the program (for example, when a function invoked with \texttt{CALL} returns, it returns to the next instruction past the \texttt{CALL} that invoked it).
\subsection{The LIN to ASM and ASM to MCS-51 machine code translations}
\label{subsect.lin.asm.translation}
The LIN to ASM translation step is trivial, being almost the identity function.
The only non-trivial feature of the LIN to ASM translation is that all labels are `named apart' so that there is no chance of freshly generated labels from different namespaces clashing with labels from another namespace.
The ASM to MCS-51 machine code translation step, and the required statements of correctness, are found in an unpublished manuscript attached to this document.
This is the most complex translation because of the huge number of cases
to be addressed and because of the complexity of the two semantics.
Moreover, in the assembly code we have conditional and unconditional jumps
to arbitrary locations in the code, which are not supported by the MCS-51
instruction set. The latter has several kind of jumps characterized by a
different instruction size and execution time, but limited in range. For
instance, conditional jumps to locations whose destination is more than
$2^7$ bytes away from the jump instruction location are not supported at
all and need to be emulated with a code transformation. The problem, which
is known in the litterature as branch displacement and that applies also
to modern architectures, is known to be hard and is often NP. As far as we
know, we will provide the first formally verified proof of correctness for
an assembler that implements branch displacement. We are also providing
the first verified proof of correctness of a mildly optimizing branch
displacement algorithm that, at the moment, is almost finished, but not
described in the companion paper. This proof by itself took about 6 men
months.
\section{Correctness of cost prediction}
Roughly speaking,
the proof of correctness of cost prediction shows that the cost of executing
a labelled object code program is the same as the sum over all labels in the
program execution trace of the cost statically associated to the label and
computed on the object code itself.
In presence of object level function calls, the previous statement is, however,
incorrect. The reason is twofold. First of all, a function call may diverge.
To the last labels that comes before the call, however, we also associate
the cost of the instructions that follow the call. Therefore, in the
sum over all labels, when we meet a label we pre-pay for the instructions
after function calls, assuming all calls to be terminating. This choice is
driven by considerations on the source code. Functions can be called also
inside expressions and it would be too disruptive to put labels inside
expressions to capture the cost of instructions that follow a call. Moreover,
adding a label after each call would produce a much higher number of proof
obligations in the certification of source programs using Frama-C. The
proof obligations, moreover, would be guarded by termination of all functions
involved, that also generates lots of additional complex proof obligations
that have little to do with execution costs. With our approach, instead, we
put less burden on the user, at the price of proving a weaker statement:
the estimated and actual costs will be the same if and only if the high level
program is converging. For prefixes of diverging programs we can provide
a similar result where the equality is replaced by an inequality (loss of
precision).
Assuming totality of functions is however not sufficient yet at the object
level. Even if a function returns, there is no guarantee that it will transfer
control back to the calling point. For instance, the function could have
manipulated the return address from its stack frame. Moreover, an object level
program can forge any address and transfer control to it, with no guarantee
on the execution behaviour and labelling properties of the called program.
To solve the problem, we introduced the notion of \emph{structured trace}
that come in two flavours: structured traces for total programs (an inductive
type) and structured traces for diverging programs (a co-inductive type based
on the previous one). Roughly speaking, a structured trace represents the
execution of a well behaved program that is subject to several constraints
like
\begin{enumerate}
\item All function calls return control just after the calling point
\item The execution of all function bodies start with a label and end with
a RET (even the ones reached by invoking a function pointer)
\item All instructions are covered by a label (required by correctness of
the labelling approach)
\item The target of all conditional jumps must be labelled (a sufficient
but not necessary condition for precision of the labelling approach)
\item \label{prop5} Two structured traces with the same structure yield the same
cost traces.
\end{enumerate}
Correctness of cost predictions is proved only for structured execution traces,
i.e. well behaved programs. The forward simulation proof for all back-end
passes will actually be a proof of preservation of the structure of
the structured traces that, because of property \ref{prop5}, will imply
correctness of the cost prediction for the back-end. The Clight to RTLabs
will also include a proof that associates to each converging execution its
converging structured trace and to each diverging execution its diverging
structured trace.
There are also other two issues that invalidate the naive statement of
correctness of cost prediciton given above. The algorithm that statically
computes the cost of blocks is correct only when the object code is \emph{well
formed} and the program counter is \emph{reachable}.
A well formed object code is such that
the program counter will never overflow after the execution step of
the processor. An overflow that occurs during fetching but is overwritten
during execution is, however, correct and necessary to accept correct
programs that are as large as the program memory. Temporary overflows add
complications to the proof. A reachable address is an address that can be
obtained by fetching (not executing!) a finite number of times from the
beginning of the code memory without ever overflowing. The complication is that
the static prediction traverses the code memory assuming that the memory will
be read sequentially from the beginning and that all jumps jump only to
reachable addresses. When this property is violated, the way the code memory
is interpreted is uncorrect and the cost computed is totally meaningless.
The reachability relation is closed by fetching for well formed programs.
The property that calls to function pointers only target reachable and
well labelled locations, however, is not statically predictable and it is
enforced in the structured trace.
The proof of correctness of cost predictions has been quite complex. Setting
up the good invariants (structured traces, well formed programs, reachability)
and completing the proof has required more than 3 men months while the initally
estimated effort was much lower. In the paper-and-pencil proof for IMP, the
corresponding proof was obvious and only took two lines.
The proof itself is quite involved. We
basically need to show as an important lemma that the sum of the execution
costs over a structured trace, where the costs are summed in execution order,
is equivalent to the sum of the execution costs in the order of pre-payment.
The two orders are quite different and the proof is by mutual recursion over
the definition of the converging structured traces, which is a family of three
mutual inductive types. The fact that this property only holds for converging
function calls in hidden in the definition of the structured traces.
Then we need to show that the order of pre-payment
corresponds to the order induced by the cost traces extracted from the
structured trace. Finally, we need to show that the statically computed cost
for one block corresponds to the cost dinamically computed in pre-payment
order.
\section{Overall results}
Functional correctness of the compiled code can be shown by composing
the simulations to show that the target behaviour matches the
behaviour of the source program, if the source program does not `go
wrong'. More precisely, we show that there is a forward simulation
between the source trace and a (flattened structured) trace of the
output, and conclude equivalence because the target's semantics are
in the form of an executable function, and hence
deterministic.
Combining this with the correctness of the assignment of costs to cost
labels at the ASM level for a structured trace, we can show that the
cost of executing any compiled function (including the main function)
is equal to the sum of all the values for cost labels encountered in
the \emph{source code's} trace of the function.
\section{Estimated effort}
Based on the rough analysis performed so far we can estimate the total
effort for the certification of the compiler. We obtain this estimation by
combining, for each pass: 1) the number of lines of code to be certified;
2) the ratio of number of lines of proof to number of lines of code from
the CompCert project~\cite{compcert} for the CompCert pass that is closest to
ours; 3) an estimation of the complexity of the pass according to the
analysis above. The result is shown in Table~\ref{table}.
\begin{table}{h}
\begin{tabular}{lrlrr}
Pass origin & Code lines & CompCert ratio & Estimated effort & Estimated effort \\
& & & (based on CompCert) & \\
\hline
Common & 4864 & 4.25 \permil & 20.67 & 17.0 \\
Cminor & 1057 & 5.23 \permil & 5.53 & 6.0 \\
Clight & 1856 & 5.23 \permil & 9.71 & 10.0 \\
RTLabs & 1252 & 1.17 \permil & 1.48 & 5.0 \\
RTL & 469 & 4.17 \permil & 1.95 & 2.0 \\
ERTL & 789 & 3.01 \permil & 2.38 & 2.5 \\
LTL & 92 & 5.94 \permil & 0.55 & 0.5 \\
LIN & 354 & 6.54 \permil & 2.31 & 1.0 \\
ASM & 984 & 4.80 \permil & 4.72 & 10.0 \\
\hline
Total common & 4864 & 4.25 \permil & 20.67 & 17.0 \\
Total front-end & 2913 & 5.23 \permil & 15.24 & 16.0 \\
Total back-end & 6853 & 4.17 \permil & 13.39 & 21.0 \\
\hline
Total & 14630 & 3.75 \permil & 49.30 & 54.0 \\
\end{tabular}
\caption{\label{table} Estimated effort}
\end{table}
We provide now some additional informations on the methodology used in the
computation. The passes in Cerco and CompCert front-end closely match each
other. However, there is no clear correspondence between the two back-ends.
For instance, we enforce the calling convention immediately after instruction
selection, whereas in CompCert this is performed in a later phase. Or we
linearize the code at the very end, whereas CompCert performs linearization
as soon as possible. Therefore, the first part of the exercise has consisted
in shuffling and partitioning the CompCert code in order to assign to each
CerCo pass the CompCert code that performs the same transformation.
After this preliminary step, using the data given in~\cite{compcert} (which
are relative to an early version of CompCert) we computed the ratio between
men months and lines of code in CompCert for each CerCo pass. This is shown
in the third column of Table~\ref{table}. For those CerCo passes that
have no correspondence in CompCert (like the optimizing assembler) or where
we have insufficient data, we have used the average of the ratios computed
above.
The first column of the table shows the number of lines of code for each
pass in CerCo. The third column is obtained multiplying the first with the
CompCert ratio. It provides an estimate of the effort required (in men months)
if the complexity of the proofs for CerCo and Compcert would be the same.
The two proof styles, however, are on purpose completely different. Where
CompCert uses non executable semantics, describing the various semantics with
inductive types, we have preferred executable semantics. Therefore, CompCert
proofs by induction and inversion become proof by functional inversion,
performed using the Russel methodology (now called Program in Coq, but whose
behaviour differs from Matita's one). Moreover, CompCert code is written using
only types that belong to the Hindley-Milner fragment, whereas we have
heavily exploited dependent types all over the code. The dependent type
discipline offers many advantages from the point of view of clarity of the
invariants involved and early detection of errors and it naturally combines
well with the Russel approach which is based on dependent types. However, it
is also well known to introduce technical problems all over the code, like
the need to explicitly prove type equalities to be able to manipulate
expressions in certain ways. In many situations, the difficulties encountered
with manipulating dependent types are better addressed by improving the Matita
system, according to the formalization driven system development. For this
reason, and assuming a pessimistic point of view on our performance, the
fourth columns presents the final estimation of the effort required, that also
takes in account the complexity of the proof suggested by the informal proofs
sketched in the previous section.
\subsection{Contingency plan}
On the basis of the proof strategy sketched in this document and the
estimated effort, we can refine our contingency plan. In case we will end
the certification of the basic compiler in advance we will have the choice
of either proving loop optimizations and/or partial redundancy elimination
correct (both tasks that seem difficult to achieve in a short time) or
considering the MCS-51 specific extensions introduced during the first period
and under-used in the formalized prototype. Yet another possibility would be
to better study retargeting of the code and the commutation property between
different compiler passes. The latter study is easily enabled by our
approach where all back-end languages are instances of the same parameterized
language.
In the case of a consistent delay in the certification of some
components, we will address first the passes that are more likely to have
undetected bugs and we will follow a top-down approach, axiomatizing
the properties of the data structured used in the compiler to focus more
on the algorithms. The rational is that data structures are easier then
algorithms to test using well known methodologies.
The effort table clearly shows that commond definitions
and data structures are 1/4th of the size of the code and require slightly
less than 1/3rd of the total effort. At least half of this effort really goes
into simple data structures (vectors, bounded and unbounded integers, tries
and maps) whose certification is not interesting and whose code could be
taken without re-proving it from the library of any other theorem prover.
\section{Conclusions}
The overall exercise, whose details have been only minimally reported here,
has been very useful. It has allowed to spot in an early moment some criticities
of the proof that have required major changes in the proof plan. It has also
shown that the last passes of the compilation (e.g. assembly) and cost
prediction on the object code are much more involved than more high level
passes.
The final estimation for the effort is surely affected by a low degree of
confidence. It is however sufficient to conclude that the effort required
is in line with the man power that was scheduled for the second half of the
second period and for the third period. Compared to the number of men months
declared in Annex I of the contract, we will need more men months. However,
both at UNIBO and UEDIN there have been major differences in hiring with
respect to the Annex. Therefore both sites have now an higher number of men
months available, with the trade-off of a lower level of maturity of the
people employed.
The reviewers suggested that we use this estimation to compare two possible
scenarios: a) proceed as planned, porting all the CompCert proofs to Matita
or b) port D3.1 and D4.1 to Coq and re-use the CompCert proofs.
We remark here again that the back-end of the two compilers, from the
memory model on, are sensibly different: we are not re-proving correctness
of the same piece of code. Moreover, the proof techniques are different for
the front-end too. Switching to the CompCert formalization would imply
the abandon of the untrusted compiler, the abandon of the experiment with
a different proof technique, the abandon of the quest for an open source
proof, and the abandon of the co-development of the formalization and the
Matita proof assistant. In the Commitment Letter~\cite{letter} delivered
to the Officer in May we clarified our personal perspective on the project
goals and objectives. We do not re-describe here the point of view presented
in the letter that we can condense in ``we value diversity''.
Clearly, if the execise would have suggested the infeasability in terms of
effort of concluding the formalization or getting close to that, we would have
abandoned our path and embraced the reviewer's suggestion. However, we
have been comforted in the analysis we did in autumn and further progress done
during the winter does not show yet any major delay with respect to the
proof schedule. We are thus planning to continue the certification according
to the more detailed proof plan that came out from the exercise reported in
this manuscript.
\begin{thebibliography}{2}
\bibitem{compcert} X. Leroy, ``A Formally Verified Compiler back-end'',
Journal of Automated Reasoning 43(4)):363-446, 2009.
\bibitem{letter}The CerCo team, ``Commitment to the Consideration of Reviewer's Reccomendation'', 16/05/2011.
\end{thebibliography}
\end{document}