source: Deliverables/D1.2/CompilerProofOutline/outline.tex @ 1758

Last change on this file since 1758 was 1758, checked in by campbell, 9 years ago

Minor improvements to front-end; add an overall statement.

File size: 39.3 KB
Line 
1\documentclass[a4paper, 10pt]{article}
2
3\usepackage{a4wide}
4\usepackage{amsfonts}
5\usepackage{amsmath}
6\usepackage{amssymb}
7\usepackage[english]{babel}
8\usepackage{color}
9\usepackage{diagrams}
10\usepackage{graphicx}
11\usepackage[colorlinks]{hyperref}
12\usepackage[utf8x]{inputenc}
13\usepackage{listings}
14\usepackage{microtype}
15\usepackage{skull}
16\usepackage{stmaryrd}
17\usepackage{array}
18\newcolumntype{b}{@{}>{{}}}
19\newcolumntype{B}{@{}>{{}}c<{{}}@{}}
20\newcolumntype{h}[1]{@{\hspace{#1}}}
21\newcolumntype{L}{>{$}l<{$}}
22\newcolumntype{C}{>{$}c<{$}}
23\newcolumntype{R}{>{$}r<{$}}
24\newcolumntype{S}{>{$(}r<{)$}}
25\newcolumntype{n}{@{}}
26\usepackage{wasysym}
27
28
29\lstdefinelanguage{matita-ocaml} {
30  mathescape=true
31}
32\lstset{
33  language=matita-ocaml,basicstyle=\tt,columns=flexible,breaklines=false,
34  showspaces=false, showstringspaces=false, extendedchars=false,
35  inputencoding=utf8x, tabsize=2
36}
37
38\title{Proof outline for the correctness of the CerCo compiler}
39\date{\today}
40\author{The CerCo team}
41
42\begin{document}
43
44\maketitle
45
46\section{Introduction}
47\label{sect.introduction}
48
49In the last project review of the CerCo project, the project reviewers
50recommended us to quickly outline a paper-and-pencil correctness proof
51for each of the stages of the CerCo compiler in order to allow for an
52estimation of the complexity and time required to complete the formalization
53of the proof. This has been possible starting from month 18 when we have
54completed the formalization in Matita of the datastructures and code of
55the compiler.
56
57In this document we provide a very high-level, pen-and-paper
58sketch of what we view as the best path to completing the correctness proof
59for 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
60been completed at the end of the First Period.
61
62In the last section we finally present an estimation of the effort required
63for the certification in Matita of the compiler and we draw conclusions.
64
65\section{Front-end: Clight to RTLabs}
66
67The front-end of the CerCo compiler consists of several stages:
68
69\begin{center}
70\begin{minipage}{.8\linewidth}
71\begin{tabbing}
72\quad \= $\downarrow$ \quad \= \kill
73\textsf{Clight}\\
74\> $\downarrow$ \> cast removal\\
75\> $\downarrow$ \> add runtime functions\footnote{Following the last project
76meeting we intend to move this transformation to the back-end}\\
77\> $\downarrow$ \> cost labelling\\
78\> $\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)\\
79\> $\downarrow$ \> partial redundancy elimination$^{\mbox{\scriptsize \ref{lab:opt2}}}$ (an endo-transformation)\\
80\> $\downarrow$ \> stack variable allocation and control structure
81 simplification\\
82\textsf{Cminor}\\
83\> $\downarrow$ \> generate global variable initialisation code\\
84\> $\downarrow$ \> transform to RTL graph\\
85\textsf{RTLabs}\\
86\> $\downarrow$ \> \\
87\>\,\vdots
88\end{tabbing}
89\end{minipage}
90\end{center}
91
92Here, by `endo-transformation', we mean a mapping from language back to itself:
93the loop optimization step maps the Clight language to itself.
94
95%Our overall statements of correctness with respect to costs will
96%require a correctly labelled program
97There are three layers in most of the proofs proposed:
98\begin{enumerate}
99\item invariants closely tied to the syntax and transformations using
100  dependent types (such as the presence of variable names in environments),
101\item a forward simulation proof relating each small-step of the
102  source to zero or more steps of the target, and
103\item proofs about syntactic properties of the cost labelling.
104\end{enumerate}
105The first will support both functional correctness and allow us to
106show the totality of some of the compiler stages (that is, those
107stages of the compiler cannot fail).  The second provides the main
108functional correctness result, including the preservation of cost
109labels in the traces, and the last will be crucial for applying
110correctness results about the costings from the back-end by showing
111that they appear in enough places so that we can assign all of the
112execution costs to them.
113
114We will also prove that a suitably labelled RTLabs trace can be turned
115into a \emph{structured trace} which splits the execution trace into
116cost-label to cost-label chunks with nested function calls.  This
117structure was identified during work on the correctness of the
118back-end cost analysis as retaining important information about the
119structure of the execution that is difficult to reconstruct later in
120the compiler.
121
122\subsection{Clight cast removal}
123
124This transformation removes some casts inserted by the parser to make
125arithmetic promotion explicit but which are superfluous (such as
126\lstinline[language=C]'c = (short)((int)a + (int)b);' where
127\lstinline'a' and \lstinline'b' are \lstinline[language=C]'short').
128This is necessary for producing good code for our target architecture.
129
130It only affects Clight expressions, recursively detecting casts that
131can be safely eliminated.  The semantics provides a big-step
132definition for expression, so we should be able to show a lock-step
133forward simulation between otherwise identical states using a lemma
134showing that cast elimination does not change the evaluation of
135expressions.  This lemma will follow from a structural induction on
136the source expression.  We have already proved a few of the underlying
137arithmetic results necessary to validate the approach.
138
139\subsection{Clight cost labelling}
140
141This adds cost labels before and after selected statements and
142expressions, and the execution traces ought to be equivalent modulo
143the new cost labels.  Hence it requires a simple forward simulation
144with a limited amount of stuttering whereever a new cost label is
145introduced.  A bound can be given for the amount of stuttering allowed
146based on the statement or continuation to be evaluated next.
147
148We also intend to show three syntactic properties about the cost
149labelling:
150\begin{enumerate}
151\item every function starts with a cost label,
152\item every branching instruction is followed by a cost label (note that
153  exiting a loop is treated as a branch), and
154\item the head of every loop (and any \lstinline'goto' destination) is
155  a cost label.
156\end{enumerate}
157These can be shown by structural induction on the source term.
158
159\subsection{Clight to Cminor translation}
160
161This translation is the first to introduce some invariants, with the
162proofs closely tied to the implementation by dependent typing.  These
163are largely complete and show that the generated code enjoys:
164\begin{itemize}
165\item some minimal type safety shown by explicit checks on the
166  Cminor types during the transformation (a little more work remains
167  to be done here, but follows the same form);
168\item that variables named in the parameter and local variable
169  environments are distinct from one another, again by an explicit
170  check;
171\item that variables used in the generated code are present in the
172  resulting environment (either by checking their presence in the
173  source environment, or from a list of freshly generated temporary variables);
174  and
175\item that all \lstinline[language=C]'goto' labels are present (by
176  checking them against a list of source labels and proving that all
177  source labels are preserved).
178\end{itemize}
179
180The simulation will be similar to the relevant stages of CompCert
181(Clight to Csharpminor and Csharpminor to Cminor --- in the event that
182the direct proof is unwieldy we could introduce an intermediate
183language corresponding to Csharpminor).  During early experimentation
184with porting CompCert definitions to the Matita proof assistant we
185found little difficulty reproving the results for the memory model, so
186we plan to port the memory injection properties and use them to relate
187Clight in-memory variables with either the value of the local variable or a
188stack slot, depending on how it was classified.
189
190This should be sufficient to show the equivalence of (big-step)
191expression evaluation.  The simulation can then be shown by relating
192corresponding blocks of statement and continuations with their Cminor
193counterparts and proving that a few steps reaches the next matching
194state.
195
196The syntactic properties required for cost labels remain similar and a
197structural induction on the function bodies should be sufficient to
198show that they are preserved.
199
200\subsection{Cminor global initialisation code}
201
202This short phase replaces the global variable initialisation data with
203code that executes when the program starts.  Each piece of
204initialisation data in the source is matched by a new statement
205storing that data.  As each global variable is allocated a distinct
206memory block, the program state after the initialisation statements
207will be the same as the original program's state at the start of
208execution, and will proceed in the same manner afterwards.
209
210% Actually, the above is wrong...
211% ... this ought to be in a fresh main function with a fresh cost label
212
213\subsection{Cminor to RTLabs translation}
214
215In this part of the compiler we transform the program's functions into
216control flow graphs.  It is closely related to CompCert's Cminorsel to
217RTL transformation, albeit with target-independent operations.
218
219We already enforce several invariants with dependent types: some type
220safety, mostly shown using the type information from Cminor; and
221that the graph is closed (by showing that each successor was recently
222added, or corresponds to a \lstinline[language=C]'goto' label which
223are all added before the end).  Note that this relies on a
224monotonicity property; CompCert maintains a similar property in a
225similar way while building RTL graphs.  We will also add a result
226showing that all of the pseudo-register names are distinct for use by
227later stages using the same method as Cminor.
228
229The simulation will relate Cminor states to RTLabs states which are about to
230execute the code corresponding to the Cminor statement or continuation.
231Each Cminor statement becomes zero or more RTLabs statements, with a
232decreasing measure based on the statement and continuations similar to
233CompCert's.  We may also follow CompCert in using a relational
234specification of this stage so as to abstract away from the functional
235(and highly dependently typed) definition.
236
237The first two labelling properties remain as before; we will show that
238cost labels are preserved, so the function entry point will be a cost
239label, and successors to any statement that are cost labels map still
240map to cost labels, preserving the condition on branches.  We replace
241the property for loops with the notion that we will always reach a
242cost label or the end of the function after following a bounded number of
243successors.  This can be easily seen in Cminor using the requirement
244for cost labels at the head of loops and after gotos.  It remains to
245show that this is preserved by the translation to RTLabs.  % how?
246
247\subsection{RTLabs structured trace generation}
248
249This proof-only step incorporates the function call structure and cost
250labelling properties into the execution trace.  As the function calls
251are nested within the trace, we need to distinguish between
252terminating and non-terminating function calls.  Thus we use the
253excluded middle (specialised to a function termination property) to do
254this.
255
256Structured traces for terminating functions are built by following the
257flat trace, breaking it into chunks between cost labels and
258recursively processing function calls.  The main difficulties here are
259the non-structurally recursive nature of the function (instead we use
260the size of the termination proof as a measure) and using the RTLabs
261cost labelling properties to show that the constraints of the
262structured traces are observed.  We also show that the lower stack
263frames are preserved during function calls in order to prove that
264after returning from a function call we resume execution of the
265correct code.  This part of the work has already been constructed, but
266still requires a simple proof to show that flattening the structured
267trace recreates the original flat trace.
268
269The non-terminating case follows the trace like the terminating
270version to build up chunks of trace from cost-label to cost-label
271(which, by the finite distance to a cost label property shown before,
272can be represented by an inductive type).  These chunks are chained
273together in a coinductive data structure that can represent
274non-terminating traces.  The excluded middle is used to decide whether
275function calls terminate, in which case the function described above
276constructs an inductive terminating structured trace which is nested
277in the caller's trace.  Otherwise, another coinductive constructor is
278used to embed the non-terminating trace of the callee, generated by
279corecursion.  This part of the trace transformation is currently under
280construction, and will also need a flattening result to show that it
281is correct.
282
283
284\section{Backend: RTLabs to machine code}
285\label{sect.backend.rtlabs.machine.code}
286
287The compiler backend consists of the following intermediate languages, and stages of translation:
288
289\begin{center}
290\begin{minipage}{.8\linewidth}
291\begin{tabbing}
292\quad \=\,\vdots\= \\
293\> $\downarrow$ \>\\
294\> $\downarrow$ \quad \= \kill
295\textsf{RTLabs}\\
296\> $\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) \\
297\> $\downarrow$ \> instruction selection\\
298\> $\downarrow$ \> change of memory models in compiler\\
299\textsf{RTL}\\
300\> $\downarrow$ \> constant propagation$^{\mbox{\scriptsize \ref{lab:opt}}}$ (an endo-transformation) \\
301\> $\downarrow$ \> calling convention made explicit \\
302\> $\downarrow$ \> layout of activation records \\
303\textsf{ERTL}\\
304\> $\downarrow$ \> register allocation and spilling\\
305\> $\downarrow$ \> dead code elimination\\
306\textsf{LTL}\\
307\> $\downarrow$ \> function linearisation\\
308\> $\downarrow$ \> branch compression (an endo-transformation) \\
309\textsf{LIN}\\
310\> $\downarrow$ \> relabeling\\
311\textsf{ASM}\\
312\> $\downarrow$ \> pseudoinstruction expansion\\
313\textsf{MCS-51 machine code}\\
314\end{tabbing}
315\end{minipage}
316\end{center}
317
318\subsection{The RTLabs to RTL translation}
319\label{subsect.rtlabs.rtl.translation}
320
321The RTLabs to RTL translation pass marks the frontier between the two memory models used in the CerCo project.
322As a result, we require some method of translating between the values that the two memory models permit.
323Suppose we have such a translation, $\sigma$.
324Then the translation between values of the two memory models may be pictured with:
325
326\begin{displaymath}
327\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
328\end{displaymath}
329
330In 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
331representables in a byte, but some others require more bits.
332
333In the back-end model all values are meant to be represented in a single byte.
334Values can thefore be undefined, be one byte long integers or be indexed
335fragments of a pointer, null or not. Floats values are no longer present, as floating point arithmetic is not supported by the CerCo compiler.
336
337The $\sigma$ map implements a one-to-many relation: a single front-end value
338is mapped to a sequence of back-end values when its size is more then one byte.
339
340We 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
341thought as an instance of a generic \texttt{Mem} data type parameterized over
342the kind of values stored in memory.
343
344\begin{displaymath}
345\mathtt{Mem}\ \alpha = \mathtt{Block} \rightarrow (\mathbb{Z} \rightarrow \alpha)
346\end{displaymath}
347
348Here, \texttt{Block} consists of a \texttt{Region} paired with an identifier.
349
350\begin{displaymath}
351\mathtt{Block} ::= \mathtt{Region} \times \mathtt{ID}
352\end{displaymath}
353
354We now have what we need for defining what is meant by the `memory' in the backend memory model.
355Namely, we instantiate the previously defined \texttt{Mem} type with the type of back-end memory values.
356
357\begin{displaymath}
358\mathtt{BEMem} = \mathtt{Mem} \mathtt{BEValue}
359\end{displaymath}
360
361Memory addresses consist of a pair of back-end memory values:
362
363\begin{displaymath}
364\mathtt{Address} = \mathtt{BEValue} \times  \mathtt{BEValue} \\
365\end{displaymath}
366
367The back- and front-end memory models differ in how they represent sized integeer values in memory.
368In 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.
369In contrast, the layout of sized integer values in the back-end memory model consists of a series of byte-sized `chunks':
370
371\begin{center}
372\begin{picture}(0, 25)
373\put(-125,0){\framebox(25,25)[c]{\texttt{v,4}}}
374\put(-100,0){\framebox(25,25)[c]{\texttt{cont}}}
375\put(-75,0){\framebox(25,25)[c]{\texttt{cont}}}
376\put(-50,0){\framebox(25,25)[c]{\texttt{cont}}}
377\put(-15,10){\vector(1, 0){30}}
378\put(25,0){\framebox(25,25)[c]{\texttt{\texttt{v$_1$}}}}
379\put(50,0){\framebox(25,25)[c]{\texttt{\texttt{v$_2$}}}}
380\put(75,0){\framebox(25,25)[c]{\texttt{\texttt{v$_3$}}}}
381\put(100,0){\framebox(25,25)[c]{\texttt{\texttt{v$_4$}}}}
382\end{picture}
383\end{center}
384
385Chunks for pointers are pairs made of the original pointer and the index of
386the chunk. Therefore, when assembling the chunks together, we can always
387recognize if all chunks refer to the same value or if the operation is
388meaningless.
389
390The 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.
391The first lemma required has the following statement:
392\begin{displaymath}
393\mathtt{load}\ s\ a\ M = \mathtt{Some}\ v \rightarrow \forall i \leq s.\ \mathtt{load}\ s\ (a + i)\ \sigma(M) = \mathtt{Some}\ v_i
394\end{displaymath}
395That 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 a value from memory in the back-end memory at \emph{any} address from address $a$ up to and including address $a + i$, where $i \leq s$.
396
397\begin{displaymath}
398\sigma(\mathtt{store}\ v\ M) = \mathtt{store}\ \sigma(v)\ \sigma(M)
399\end{displaymath}
400
401\begin{displaymath}
402\texttt{load}^* (\mathtt{store}\ \sigma(v)\ \sigma(M))\ \sigma(a)\ \sigma(M) = \mathtt{load}^*\ \sigma(s)\ \sigma(a)\ \sigma(M)
403\end{displaymath}
404
405\begin{displaymath}
406\begin{array}{rll}
407\mathtt{State} & ::=  & (\mathtt{State} : \mathtt{Frame}^* \times \mathtt{Frame} \\
408               & \mid & \mathtt{Call} : \mathtt{Frame}^* \times \mathtt{Args} \times \mathtt{Return} \times \mathtt{Fun} \\
409               & \mid & \mathtt{Return} : \mathtt{Frame}^* \times \mathtt{Value} \times \mathtt{Return}) \times \mathtt{Mem}
410\end{array}
411\end{displaymath}
412
413\begin{displaymath}
414\mathtt{State} ::= \mathtt{Frame}^* \times \mathtt{PC} \times \mathtt{SP} \times \mathtt{ISP} \times \mathtt{CARRY} \times \mathtt{REGS}
415\end{displaymath}
416
417\begin{displaymath}
418\mathtt{State} \stackrel{\sigma}{\longrightarrow} \mathtt{State}
419\end{displaymath}
420
421\begin{displaymath}
422\sigma(\mathtt{State} (\mathtt{Frame}^* \times \mathtt{Frame})) \longrightarrow ((\sigma(\mathtt{Frame}^*), \sigma(\mathtt{PC}), \sigma(\mathtt{SP}), 0, 0, \sigma(\mathtt{REGS})), \sigma(\mathtt{Mem}))
423\end{displaymath}
424
425\begin{displaymath}
426\sigma(\mathtt{Return}(-)) \longrightarrow \sigma \circ \text{return one step}
427\end{displaymath}
428
429\begin{displaymath}
430\sigma(\mathtt{Call}(-)) \longrightarrow \sigma \circ \text{call one step}
431\end{displaymath}
432
433Return one step commuting diagram:
434
435\begin{displaymath}
436\begin{diagram}
437s & \rTo^{\text{one step of execution}} & s'   \\
438  & \rdTo                             & \dTo \\
439  &                                   & \llbracket s'' \rrbracket
440\end{diagram}
441\end{displaymath}
442
443Call one step commuting diagram:
444
445\begin{displaymath}
446\begin{diagram}
447s & \rTo^{\text{one step of execution}} & s'   \\
448  & \rdTo                             & \dTo \\
449  &                                   & \llbracket s'' \rrbracket
450\end{diagram}
451\end{displaymath}
452
453\begin{displaymath}
454\begin{array}{rcl}
455\mathtt{Call(id,\ args,\ dst,\ pc),\ State(FRAME, FRAMES)} & \longrightarrow & \mathtt{Call(M(args), dst)}, \\
456                                                           &                 & \mathtt{PUSH(current\_frame[PC := after\_return])}
457\end{array}
458\end{displaymath}
459
460In the case where the call is to an external function, we have:
461
462\begin{displaymath}
463\begin{array}{rcl}
464\mathtt{Call(M(args), dst)},                       & \stackrel{\mathtt{ret\_val = f(M(args))}}{\longrightarrow} & \mathtt{Return(ret\_val,\ dst,\ PUSH(...))} \\
465\mathtt{PUSH(current\_frame[PC := after\_return])} &                                                            & 
466\end{array}
467\end{displaymath}
468
469then:
470
471\begin{displaymath}
472\begin{array}{rcl}
473\mathtt{Return(ret\_val,\ dst,\ PUSH(...))} & \longrightarrow & \mathtt{pc = POP\_STACK(regs[dst := M(ret\_val)],\ pc)}
474\end{array}
475\end{displaymath}
476
477In the case where the call is to an internal function, we have:
478
479\begin{displaymath}
480\begin{array}{rcl}
481\mathtt{CALL}(\mathtt{id}, \mathtt{args}, \mathtt{dst}, \mathtt{pc}) & \longrightarrow & \mathtt{CALL\_ID}(\mathtt{id}, \sigma'(\mathtt{args}), \sigma(\mathtt{dst}), \mathtt{pc}) \\
482\mathtt{RETURN}                                                      & \longrightarrow & \mathtt{RETURN} \\
483\end{array} 
484\end{displaymath}
485
486\begin{displaymath}
487\begin{array}{rcl}
488\mathtt{Call(M(args), dst)}                        & \longrightarrow & \mathtt{sp = alloc}, regs = \emptyset[- := PARAMS] \\
489\mathtt{PUSH(current\_frame[PC := after\_return])} &                 & \mathtt{State}(regs,\ sp,\ pc_\emptyset,\ dst)
490\end{array}
491\end{displaymath}
492
493then:
494
495\begin{displaymath}
496\begin{array}{rcl}
497\mathtt{sp = alloc}, regs = \emptyset[- := PARAMS] & \longrightarrow & \mathtt{free(sp)} \\
498\mathtt{State}(regs,\ sp,\ pc_\emptyset,\ dst)     &                 & \mathtt{Return(M(ret\_val), dst, frames)}
499\end{array}
500\end{displaymath}
501
502and finally:
503
504\begin{displaymath}
505\begin{array}{rcl}
506\mathtt{free(sp)}                         & \longrightarrow & \mathtt{pc = POP\_STACK(regs[dst := M(ret\_val)],\ pc)} \\
507\mathtt{Return(M(ret\_val), dst, frames)} &                 & 
508\end{array}
509\end{displaymath}
510
511\begin{displaymath}
512\begin{array}{rcl}
513\sigma & : & \mathtt{register} \rightarrow \mathtt{list\ register} \\
514\sigma' & : & \mathtt{list\ register} \rightarrow \mathtt{list\ register}
515\end{array}
516\end{displaymath}
517
518\subsection{The RTL to ERTL translation}
519\label{subsect.rtl.ertl.translation}
520
521\begin{displaymath}
522\begin{diagram}
523& & \llbracket \mathtt{CALL\_ID}(\mathtt{id}, \mathtt{args}, \mathtt{dst}, \mathtt{pc})\rrbracket & & \\
524& \ldTo^{\text{external}} & & \rdTo^{\text{internal}} & \\
525\skull & & & & \mathtt{regs} = [\mathtt{params}/-] \\
526& & & & \mathtt{sp} = \mathtt{ALLOC} \\
527& & & & \mathtt{PUSH}(\mathtt{carry}, \mathtt{regs}, \mathtt{dst}, \mathtt{return\_addr}), \mathtt{pc}_{0}, \mathtt{regs}, \mathtt{sp} \\
528\end{diagram}
529\end{displaymath}
530
531\begin{align*}
532\llbracket \mathtt{RETURN} \rrbracket \\
533\mathtt{return\_addr} & := \mathtt{top}(\mathtt{stack}) \\
534v*                    & := m(\mathtt{rv\_regs}) \\
535\mathtt{dst}, \mathtt{sp}, \mathtt{carry}, \mathtt{regs} & := \mathtt{pop} \\
536\mathtt{regs}[v* / \mathtt{dst}] \\
537\end{align*}
538
539\begin{displaymath}
540\begin{diagram}
541s    & \rTo^1 & s' & \rTo^1 & s'' \\
542\dTo &        &    & \rdTo  & \dTo \\
543\llbracket s \rrbracket & \rTo(1,3)^1 & & & \llbracket s'' \rrbracket \\ 
544\mathtt{CALL} \\
545\end{diagram}
546\end{displaymath}
547
548\begin{displaymath}
549\begin{diagram}
550s    & \rTo^1 & s' & \rTo^1 & s'' \\
551\dTo &        &    & \rdTo  & \dTo \\
552\  & \rTo(1,3) & & & \ \\
553\mathtt{RETURN} \\
554\end{diagram}
555\end{displaymath}
556
557\begin{displaymath}
558\mathtt{b\_graph\_translate}: (\mathtt{label} \rightarrow \mathtt{blist'})
559\rightarrow \mathtt{graph} \rightarrow \mathtt{graph}
560\end{displaymath}
561
562\begin{align*}
563\mathtt{theorem} &\ \mathtt{b\_graph\_translate\_ok}: \\
564& \forall  f.\forall G_{i}.\mathtt{let}\ G_{\sigma} := \mathtt{b\_graph\_translate}\ f\ G_{i}\ \mathtt{in} \\
565&       \forall l \in G_{i}.\mathtt{subgraph}\ (f\ l)\ l\ (\mathtt{next}\ l\ G_{i})\ G_{\sigma}
566\end{align*}
567
568\begin{align*}
569\mathtt{lemma} &\ \mathtt{execute\_1\_step\_ok}: \\
570&       \forall s.  \mathtt{let}\ s' := s\ \sigma\ \mathtt{in} \\
571&       \mathtt{let}\ l := pc\ s\ \mathtt{in} \\
572&       s \stackrel{1}{\rightarrow} s^{*} \Rightarrow \exists n. s' \stackrel{n}{\rightarrow} s'^{*} \wedge s'^{*} = s'\ \sigma
573\end{align*}
574
575\begin{align*}
576\mathrm{RTL\ status} & \ \ \mathrm{ERTL\ status} \\
577\mathtt{sp} & = \mathtt{spl} / \mathtt{sph} \\
578\mathtt{graph} &  \mathtt{graph} + \mathtt{prologue}(s) + \mathtt{epilogue}(s) \\
579& \mathrm{where}\ s = \mathrm{callee\ saved} + \nu \mathrm{RA} \\
580\end{align*}
581
582\begin{displaymath}
583\begin{diagram}
584\mathtt{CALL} & \rTo^1 & \mathtt{inside\ function} \\
585\dTo & & \dTo \\
586\underbrace{\ldots}_{\llbracket \mathtt{CALL} \rrbracket} & \rTo &
587\underbrace{\ldots}_{\mathtt{prologue}} \\
588\end{diagram}
589\end{displaymath}
590
591\begin{displaymath}
592\begin{diagram}
593\mathtt{RETURN} & \rTo^1 & \mathtt{.} \\
594\dTo & & \dTo \\
595\underbrace{\ldots}_{\mathtt{epilogue}} & \rTo &
596\underbrace{\ldots} \\
597\end{diagram}
598\end{displaymath}
599
600\begin{align*}
601\mathtt{prologue}(s) = & \mathtt{create\_new\_frame}; \\
602                       & \mathtt{pop\ ra}; \\
603                       & \mathtt{save\ callee\_saved}; \\
604                                                                                         & \mathtt{get\_params} \\
605                                                                                         & \ \ \mathtt{reg\_params}: \mathtt{move} \\
606                                                                                         & \ \ \mathtt{stack\_params}: \mathtt{push}/\mathtt{pop}/\mathtt{move} \\
607\end{align*}
608
609\begin{align*}
610\mathtt{epilogue}(s) = & \mathtt{save\ return\ to\ tmp\ real\ regs}; \\
611                                                                                         & \mathtt{restore\_registers}; \\
612                       & \mathtt{push\ ra}; \\
613                       & \mathtt{delete\_frame}; \\
614                       & \mathtt{save return} \\
615\end{align*}
616
617\begin{displaymath}
618\mathtt{CALL}\ id \mapsto \mathtt{set\_params};\ \mathtt{CALL}\ id;\ \mathtt{fetch\_result}
619\end{displaymath}
620
621\subsection{The ERTL to LTL translation}
622\label{subsect.ertl.ltl.translation}
623\newcommand{\declsf}[1]{\expandafter\newcommand\expandafter{\csname #1\endcsname}{\mathop{\mathsf{#1}}\nolimits}}
624\declsf{Livebefore}
625\declsf{Liveafter}
626\declsf{Defined}
627\declsf{Used}
628\declsf{Eliminable}
629\declsf{StatementSem}
630For the liveness analysis, we aim at a map
631$\ell \in \mathtt{label} \mapsto $ live registers at $\ell$.
632We define the following operators on ERTL statements.
633$$
634\begin{array}{lL>{(ex. $}L<{)$}}
635\Defined(s) & registers defined at $s$ & r_1\leftarrow r_2+r_3 \mapsto \{r_1,C\}, \mathtt{CALL}~id\mapsto \text{caller-save}
636\\
637\Used(s) & registers used at $s$ & r_1\leftarrow r_2+r_3 \mapsto \{r_2,r_3\}, \mathtt{CALL}~id\mapsto \text{parameters}
638\end{array}
639$$
640Given $LA:\mathtt{label}\to\mathtt{lattice}$ (where $\mathtt{lattice}$
641is the type of sets of registers\footnote{More precisely, it is thethe lattice
642of pairs of sets of pseudo-registers and sets of hardware registers,
643with pointwise operations.}, we also have have the following
644predicates:
645$$
646\begin{array}{lL}
647\Eliminable_{LA}(\ell) & iff $s(\ell)$ has side-effects only on $r\notin LA(\ell)$
648\\&
649(ex.\ $\ell : r_1\leftarrow r_2+r_3 \mapsto (\{r_1,C\}\cap LA(\ell)\neq\emptyset,
650  \mathtt{CALL}id\mapsto \text{never}$)
651\\
652\Livebefore_{LA}(\ell) &$:=
653  \begin{cases}
654    LA(\ell) &\text{if $\Eliminable_{LA}(\ell)$,}\\
655    (LA(\ell)\setminus \Defined(s(\ell)))\cup \Used(s(\ell) &\text{otherwise}.
656  \end{cases}$
657\end{array}
658$$
659In particular, $\Livebefore$ has type $(\mathtt{label}\to\mathtt{lattice})\to
660\mathtt{label}\to\mathtt{lattice}$.
661
662The equation on which we build the fixpoint is then
663$$\Liveafter(\ell) \doteq \bigcup_{\ell' >_1 \ell} \Livebefore_{\Liveafter}(\ell')$$
664where $\ell' >_1 \ell$ denotes that $\ell'$ is an immediate successor of $\ell$
665in the graph. We do not require the fixpoint to be the least one, so the hypothesis
666on $\Liveafter$ that we require is
667$$\Liveafter(\ell) \supseteq \bigcup_{\ell' >_1 \ell} \Livebefore(\ell')$$
668(for shortness we drop the subscript from $\Livebefore$).
669\subsection{The LTL to LIN translation}
670\label{subsect.ltl.lin.translation}
671
672We 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:
673\begin{displaymath}
674\mathtt{pc : label} \stackrel{\sigma}{\longrightarrow} \mathbb{N}
675\end{displaymath}
676
677The LTL to LIN translation pass also linearises the graph data structure into a list of instructions.
678Pseudocode for the linearisation process is as follows:
679
680\begin{lstlisting}
681let rec linearise graph visited required generated todo :=
682  match todo with
683  | l::todo ->
684    if l $\in$ visited then
685      let generated := generated $\cup\ \{$ Goto l $\}$ in
686      let required := required $\cup$ l in
687        linearise graph visited required generated todo
688    else
689      -- Get the instruction at label `l' in the graph
690      let lookup := graph(l) in
691      let generated := generated $\cup\ \{$ lookup $\}$ in
692      -- Find the successor of the instruction at label `l' in the graph
693      let successor := succ(l, graph) in
694      let todo := successor::todo in
695        linearise graph visited required generated todo
696  | []      -> (required, generated)
697\end{lstlisting}
698
699It is easy to see that this linearisation process eventually terminates.
700In 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.
701
702The 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.
703We envisage needing to prove the following invariants on the linearisation function above:
704
705\begin{enumerate}
706\item
707$\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,
708\item
709$\forall \mathtt{l} \in \mathtt{generated}.\ \mathtt{succ(l,\ graph)} \subseteq \mathtt{required} \cup \mathtt{todo}$,
710\item
711$\mathtt{required} \subseteq \mathtt{visited}$,
712\item
713$\mathtt{visited} \cap \mathtt{todo} = \emptyset$.
714\end{enumerate}
715
716The invariants collectively imply the following properties, crucial to correctness, about the linearisation process:
717
718\begin{enumerate}
719\item
720Every graph node is visited at most once,
721\item
722Every instruction that is generated is generated due to some graph node being visited,
723\item
724The successor instruction of every instruction that has been visited already will eventually be visited too.
725\end{enumerate}
726
727Note, because the LTL to LIN transformation is the first time the program is linearised, we must discover a notion of `well formed program' suitable for linearised forms.
728In particular, we see the notion of well formedness (yet to be formally defined) resting on the following conditions:
729
730\begin{enumerate}
731\item
732For every jump to a label in a linearised program, the target label exists at some point in the program,
733\item
734Each label is unique, appearing only once in the program,
735\item
736The final instruction of a program must be a return.
737\end{enumerate}
738
739We assume that these properties will be easy consequences of the invariants on the linearisation function defined above.
740
741The final condition above is potentially a little opaque, so we explain further.
742First, the only instructions that can reasonably appear in final position at the end of a program 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).
743However, in LIN, though each function's graph has been linearised, the entire program is not yet fully linearised into a list of instructions, but rather, a list of `functions', each consisting of a linearised body along with other data.
744Each well-formed function must end with a call to \texttt{RET}, and therefore the only correct instruction that can terminate a LIN program is a \texttt{RET} instruction.
745
746\subsection{The LIN to ASM and ASM to MCS-51 machine code translations}
747\label{subsect.lin.asm.translation}
748
749The LIN to ASM translation step is trivial, being almost the identity function.
750The 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.
751
752The ASM to MCS-51 machine code translation step, and the required statements of correctness, are found in an unpublished manuscript attached to this document.
753This is the most complex translation because of the huge number of cases
754to be addressed and because of the complexity of the two semantics.
755Moreover, in the assembly code we have conditional and unconditional jumps
756to arbitrary locations in the code, which are not supported by the MCS-51
757instruction set. The latter has several kind of jumps characterized by a
758different instruction size and execution time, but limited in range. For
759instance, conditional jumps to locations whose destination is more than
760$2^7$ bytes away from the jump instruction location are not supported at
761all and need to be emulated with a code transformation. The problem, which
762is known in the litterature as branch displacement and that applies also
763to modern architectures, is known to be hard and is often NP. As far as we
764know, we will provide the first formally verified proof of correctness for
765an assembler that implements branch displacement. We are also providing
766the first verified proof of correctness of a mildly optimizing branch
767displacement algorithm that, at the moment, is almost finished, but not
768described in the companion paper. This proof by itself took about 6 men
769months.
770
771\section{Correctness of cost prediction}
772Roughly speaking,
773the proof of correctness of cost prediction shows that the cost of executing
774a labelled object code program is the same as the sum over all labels in the
775program execution trace of the cost statically associated to the label on
776computed on the object code itself.
777
778The previous statement is too weak to be proved that way.
779
780T O D O ! ! !
781
782\section{Overall results}
783
784Functional correctness of the compiled code can be shown by composing
785the simulations to show that the target behaviour matches the
786behaviour of the source program, if the source program does not `go
787wrong'.  More precisely, we show that there is a forward simulation
788between the source trace and a (flattened structured) trace of the
789output, and conclude equivalence because the target's semantics are
790in the form of an executable function, and hence
791deterministic.
792
793Combining this with the correctness of the assignment of costs to cost
794labels at the ASM level for a structured trace, we can show that the
795cost of executing any compiled function (including the main function)
796is equal to the sum of all the values for cost labels encountered in
797the \emph{source code's} trace of the function.
798
799\section{Estimated effort}
800Based on the rough analysis performed so far we can estimate the total
801effort for the certification of the compiler. We obtain this estimation by
802combining, for each pass: 1) the number of lines of code to be certified;
8032) the ratio of number of lines of proof to number of lines of code from
804the CompCert project~\cite{compcert} for the CompCert pass that is closest to
805ours; 3) an estimation of the complexity of the pass according to the
806analysis above.
807
808\begin{tabular}{lrlrr}
809Pass origin & Code lines & CompCert ratio & Estimated effort & Estimated effort \\
810            &            &                & (based on CompCert) & \\
811\hline
812Common &  4864 & 4.25 \permil & 20.67 & 17.0 \\
813Cminor &  1057 & 5.23 \permil & 5.53  &  6.0 \\
814Clight &  1856 & 5.23 \permil & 9.71  & 10.0 \\ 
815RTLabs &  1252 & 1.17 \permil & 1.48  &  5.0 \\
816RTL    &   469 & 4.17 \permil & 1.95  &  2.0 \\
817ERTL   &   789 & 3.01 \permil & 2.38  & 2.5 \\
818LTL    &    92 & 5.94 \permil & 0.55  & 0.5 \\
819LIN    &   354 & 6.54 \permil & 2.31  &   1.0 \\
820ASM    &   984 & 4.80 \permil & 4.72  &  10.0 \\
821\hline
822Total common    &  4864 & 4.25 \permil & 20.67 & 17.0 \\
823Total front-end &  2913 & 5.23 \permil & 15.24 & 16.0 \\
824Total back-end  &  6853 & 4.17 \permil & 13.39 & 21.0 \\
825\hline
826Total           & 14630 & 3.75 \permil & 49.30 & 54.0 \\
827\end{tabular}
828
829We provide now some additional informations on the methodology used in the
830computation. The passes in Cerco and CompCert front-end closely match each
831other. However, there is no clear correspondence between the two back-ends.
832For instance, we enforce the calling convention immediately after instruction
833selection, whereas in CompCert this is performed in a later phase. Or we
834linearize the code at the very end, whereas CompCert performs linearization
835as soon as possible. Therefore, the first part of the exercise has consisted
836in shuffling and partitioning the CompCert code in order to assign to each
837CerCo pass the CompCert code that performs the same transformation.
838
839After this preliminary step, using the data given in~\cite{compcert} (which
840are relative to an early version of CompCert) we computed the ratio between
841men months and lines of code in CompCert for each CerCo pass. This is shown
842in the third column of Table~\ref{wildguess}. For those CerCo passes that
843have no correspondence in CompCert (like the optimizing assembler) or where
844we have insufficient data, we have used the average of the ratios computed
845above.
846
847The first column of the table shows the number of lines of code for each
848pass in CerCo. The third column is obtained multiplying the first with the
849CompCert ratio. It provides an estimate of the effort required (in men months)
850if the complexity of the proofs for CerCo and Compcert would be the same.
851
852The two proof styles, however, are on purpose completely different. Where
853CompCert uses non executable semantics, describing the various semantics with
854inductive types, we have preferred executable semantics. Therefore, CompCert
855proofs by induction and inversion become proof by functional inversion,
856performed using the Russel methodology (now called Program in Coq, but whose
857behaviour differs from Matita's one). Moreover, CompCert code is written using
858only types that belong to the Hindley-Milner fragment, whereas we have
859heavily exploited dependent types all over the code. The dependent type
860discipline offers many advantages from the point of view of clarity of the
861invariants involved and early detection of errors and it naturally combines
862well with the Russel approach which is based on dependent types. However, it
863is also well known to introduce technical problems all over the code, like
864the need to explicitly prove type equalities to be able to manipulate
865expressions in certain ways. In many situations, the difficulties encountered
866with manipulating dependent types are better addressed by improving the Matita
867system, according to the formalization driven system development. For this
868reason, and assuming a pessimistic point of view on our performance, the
869fourth columns presents the final estimation of the effort required, that also
870takes in account the complexity of the proof suggested by the informal proofs
871sketched in the previous section.
872
873\end{document}
Note: See TracBrowser for help on using the repository browser.