Fix some more header stuff.
[matthijs/master-project/report.git] / Chapters / Normalization.tex
1 \chapter[chap:normalization]{Normalization}
2   % A helper to print a single example in the half the page width. The example
3   % text should be in a buffer whose name is given in an argument.
4   %
5   % The align=right option really does left-alignment, but without the program
6   % will end up on a single line. The strut=no option prevents a bunch of empty
7   % space at the start of the frame.
8   \define[1]\example{
9     \framed[offset=1mm,align=right,strut=no,background=box,frame=off]{
10       \setuptyping[option=LAM,style=sans,before=,after=,strip=auto]
11       \typebuffer[#1]
12       \setuptyping[option=none,style=\tttf,strip=auto]
13     }
14   }
15
16   \define[4]\transexample{
17     \placeexample[here][ex:trans:#1]{#2}
18     \startcombination[2*1]
19       {\example{#3}}{Original program}
20       {\example{#4}}{Transformed program}
21     \stopcombination
22   }
23
24   The first step in the core to \small{VHDL} translation process, is normalization. We
25   aim to bring the core description into a simpler form, which we can
26   subsequently translate into \small{VHDL} easily. This normal form is needed because
27   the full core language is more expressive than \small{VHDL} in some
28   areas (higher-order expressions, limited polymorphism using type
29   classes, etc.) and because core can describe expressions that do not
30   have a direct hardware interpretation.
31
32   \section{Normal form}
33     The transformations described here have a well-defined goal: to bring the
34     program in a well-defined form that is directly translatable to
35     \VHDL, while fully preserving the semantics of the program. We refer
36     to this form as the \emph{normal form} of the program. The formal
37     definition of this normal form is quite simple:
38
39     \placedefinition[force]{}{\startboxed A program is in \emph{normal form} if none of the
40     transformations from this chapter apply.\stopboxed}
41
42     Of course, this is an \quote{easy} definition of the normal form, since our
43     program will end up in normal form automatically. The more interesting part is
44     to see if this normal form actually has the properties we would like it to
45     have.
46
47     But, before getting into more definitions and details about this normal
48     form, let us try to get a feeling for it first. The easiest way to do this
49     is by describing the things that are unwanted in the intended normal form.
50
51     \startitemize
52       \item Any \emph{polymorphism} must be removed. When laying down hardware, we
53       cannot generate any signals that can have multiple types. All types must be
54       completely known to generate hardware.
55       
56       \item All \emph{higher-order} constructions must be removed. We cannot
57       generate a hardware signal that contains a function, so all values,
58       arguments and return values used must be first order.
59
60       \item All complex \emph{nested scopes} must be removed. In the \small{VHDL}
61       description, every signal is in a single scope. Also, full expressions are
62       not supported everywhere (in particular port maps can only map signal
63       names and constants, not complete expressions). To make the \small{VHDL}
64       generation easy, a separate binder must be bound to ever application or
65       other expression.
66     \stopitemize
67
68     \startbuffer[MulSum]
69     alu :: Bit -> Word -> Word -> Word
70     alu = λa.λb.λc.
71         let
72           mul = (*) a b
73           sum = (+) mul c
74         in
75           sum
76     \stopbuffer
77
78     \startuseMPgraphic{MulSum}
79       save a, b, c, mul, add, sum;
80
81       % I/O ports
82       newCircle.a(btex $a$ etex) "framed(false)";
83       newCircle.b(btex $b$ etex) "framed(false)";
84       newCircle.c(btex $c$ etex) "framed(false)";
85       newCircle.sum(btex $sum$ etex) "framed(false)";
86
87       % Components
88       newCircle.mul(btex * etex);
89       newCircle.add(btex + etex);
90
91       a.c      - b.c   = (0cm, 2cm);
92       b.c      - c.c   = (0cm, 2cm);
93       add.c            = c.c + (2cm, 0cm);
94       mul.c            = midpoint(a.c, b.c) + (2cm, 0cm);
95       sum.c            = add.c + (2cm, 0cm);
96       c.c              = origin;
97
98       % Draw objects and lines
99       drawObj(a, b, c, mul, add, sum);
100
101       ncarc(a)(mul) "arcangle(15)";
102       ncarc(b)(mul) "arcangle(-15)";
103       ncline(c)(add);
104       ncline(mul)(add);
105       ncline(add)(sum);
106     \stopuseMPgraphic
107
108     \placeexample[][ex:MulSum]{Simple architecture consisting of a
109     multiplier and a subtractor.}
110       \startcombination[2*1]
111         {\typebufferlam{MulSum}}{Core description in normal form.}
112         {\boxedgraphic{MulSum}}{The architecture described by the normal form.}
113       \stopcombination
114
115     \todo{Intermezzo: functions vs plain values}
116
117     A very simple example of a program in normal form is given in
118     \in{example}[ex:MulSum]. As you can see, all arguments to the function (which
119     will become input ports in the generated \VHDL) are at the outer level.
120     This means that the body of the inner lambda abstraction is never a
121     function, but always a plain value.
122
123     As the body of the inner lambda abstraction, we see a single (recursive)
124     let expression, that binds two variables (\lam{mul} and \lam{sum}). These
125     variables will be signals in the generated \VHDL, bound to the output port
126     of the \lam{*} and \lam{+} components.
127
128     The final line (the \quote{return value} of the function) selects the
129     \lam{sum} signal to be the output port of the function. This \quote{return
130     value} can always only be a variable reference, never a more complex
131     expression.
132
133     \todo{Add generated VHDL}
134
135     \in{Example}[ex:MulSum] showed a function that just applied two
136     other functions (multiplication and addition), resulting in a simple
137     architecture with two components and some connections.  There is of
138     course also some mechanism for choice in the normal form. In a
139     normal Core program, the \emph{case} expression can be used in a few
140     different ways to describe choice. In normal form, this is limited
141     to a very specific form.
142
143     \in{Example}[ex:AddSubAlu] shows an example describing a
144     simple \small{ALU}, which chooses between two operations based on an opcode
145     bit. The main structure is similar to \in{example}[ex:MulSum], but this
146     time the \lam{res} variable is bound to a case expression. This case
147     expression scrutinizes the variable \lam{opcode} (and scrutinizing more
148     complex expressions is not supported). The case expression can select a
149     different variable based on the constructor of \lam{opcode}.
150     \refdef{case expression}
151
152     \startbuffer[AddSubAlu]
153     alu :: Bit -> Word -> Word -> Word
154     alu = λopcode.λa.λb.
155         let
156           res1 = (+) a b
157           res2 = (-) a b
158           res = case opcode of
159             Low -> res1
160             High -> res2
161         in
162           res
163     \stopbuffer
164
165     \startuseMPgraphic{AddSubAlu}
166       save opcode, a, b, add, sub, mux, res;
167
168       % I/O ports
169       newCircle.opcode(btex $opcode$ etex) "framed(false)";
170       newCircle.a(btex $a$ etex) "framed(false)";
171       newCircle.b(btex $b$ etex) "framed(false)";
172       newCircle.res(btex $res$ etex) "framed(false)";
173       % Components
174       newCircle.add(btex + etex);
175       newCircle.sub(btex - etex);
176       newMux.mux;
177
178       opcode.c - a.c   = (0cm, 2cm);
179       add.c    - a.c   = (4cm, 0cm);
180       sub.c    - b.c   = (4cm, 0cm);
181       a.c      - b.c   = (0cm, 3cm);
182       mux.c            = midpoint(add.c, sub.c) + (1.5cm, 0cm);
183       res.c    - mux.c = (1.5cm, 0cm);
184       b.c              = origin;
185
186       % Draw objects and lines
187       drawObj(opcode, a, b, res, add, sub, mux);
188
189       ncline(a)(add) "posA(e)";
190       ncline(b)(sub) "posA(e)";
191       nccurve(a)(sub) "posA(e)", "angleA(0)";
192       nccurve(b)(add) "posA(e)", "angleA(0)";
193       nccurve(add)(mux) "posB(inpa)", "angleB(0)";
194       nccurve(sub)(mux) "posB(inpb)", "angleB(0)";
195       nccurve(opcode)(mux) "posB(n)", "angleA(0)", "angleB(-90)";
196       ncline(mux)(res) "posA(out)";
197     \stopuseMPgraphic
198
199     \placeexample[][ex:AddSubAlu]{Simple \small{ALU} supporting two operations.}
200       \startcombination[2*1]
201         {\typebufferlam{AddSubAlu}}{Core description in normal form.}
202         {\boxedgraphic{AddSubAlu}}{The architecture described by the normal form.}
203       \stopcombination
204
205     As a more complete example, consider
206     \in{example}[ex:NormalComplete]. This example shows everything that
207     is allowed in normal form, except for built-in higher-order functions
208     (like \lam{map}). The graphical version of the architecture contains
209     a slightly simplified version, since the state tuple packing and
210     unpacking have been left out. Instead, two separate registers are
211     drawn. Most synthesis tools will further optimize this architecture by
212     removing the multiplexers at the register input and instead use the write
213     enable port of the register (when it is available), but we want to show
214     the architecture as close to the description as possible.
215
216     As you can see from the previous examples, the generation of the final
217     architecture from the normal form is straightforward. In each of the
218     examples, there is a direct match between the normal form structure,
219     the generated VHDL and the architecture shown in the images.
220
221     \startbuffer[NormalComplete]
222       regbank :: Bit 
223                  -> Word 
224                  -> State (Word, Word) 
225                  -> (State (Word, Word), Word)
226
227       -- All arguments are an inital lambda (address, data, packed state)
228       regbank = λa.λd.λsp.
229       -- There are nested let expressions at top level
230       let
231         -- Unpack the state by coercion (\eg, cast from
232         -- State (Word, Word) to (Word, Word))
233         s = sp ▶ (Word, Word)
234         -- Extract both registers from the state
235         r1 = case s of (a, b) -> a
236         r2 = case s of (a, b) -> b
237         -- Calling some other user-defined function.
238         d' = foo d
239         -- Conditional connections
240         out = case a of
241           High -> r1
242           Low -> r2
243         r1' = case a of
244           High -> d'
245           Low -> r1
246         r2' = case a of
247           High -> r2
248           Low -> d'
249         -- Packing a tuple
250         s' = (,) r1' r2'
251         -- pack the state by coercion (\eg, cast from
252         -- (Word, Word) to State (Word, Word))
253         sp' = s' ▶ State (Word, Word)
254         -- Pack our return value
255         res = (,) sp' out
256       in
257         -- The actual result
258         res
259     \stopbuffer
260
261     \startuseMPgraphic{NormalComplete}
262       save a, d, r, foo, muxr, muxout, out;
263
264       % I/O ports
265       newCircle.a(btex \lam{a} etex) "framed(false)";
266       newCircle.d(btex \lam{d} etex) "framed(false)";
267       newCircle.out(btex \lam{out} etex) "framed(false)";
268       % Components
269       %newCircle.add(btex + etex);
270       newBox.foo(btex \lam{foo} etex);
271       newReg.r1(btex $\lam{r1}$ etex) "dx(4mm)", "dy(6mm)";
272       newReg.r2(btex $\lam{r2}$ etex) "dx(4mm)", "dy(6mm)", "reflect(true)";
273       newMux.muxr1;
274       % Reflect over the vertical axis
275       reflectObj(muxr1)((0,0), (0,1));
276       newMux.muxr2;
277       newMux.muxout;
278       rotateObj(muxout)(-90);
279
280       d.c               = foo.c + (0cm, 1.5cm); 
281       a.c               = (xpart r2.c + 2cm, ypart d.c - 0.5cm);
282       foo.c             = midpoint(muxr1.c, muxr2.c) + (0cm, 2cm);
283       muxr1.c           = r1.c + (0cm, 2cm);
284       muxr2.c           = r2.c + (0cm, 2cm);
285       r2.c              = r1.c + (4cm, 0cm);
286       r1.c              = origin;
287       muxout.c          = midpoint(r1.c, r2.c) - (0cm, 2cm);
288       out.c             = muxout.c - (0cm, 1.5cm);
289
290     %  % Draw objects and lines
291       drawObj(a, d, foo, r1, r2, muxr1, muxr2, muxout, out);
292       
293       ncline(d)(foo);
294       nccurve(foo)(muxr1) "angleA(-90)", "posB(inpa)", "angleB(180)";
295       nccurve(foo)(muxr2) "angleA(-90)", "posB(inpb)", "angleB(0)";
296       nccurve(muxr1)(r1) "posA(out)", "angleA(180)", "posB(d)", "angleB(0)";
297       nccurve(r1)(muxr1) "posA(out)", "angleA(0)", "posB(inpb)", "angleB(180)";
298       nccurve(muxr2)(r2) "posA(out)", "angleA(0)", "posB(d)", "angleB(180)";
299       nccurve(r2)(muxr2) "posA(out)", "angleA(180)", "posB(inpa)", "angleB(0)";
300       nccurve(r1)(muxout) "posA(out)", "angleA(0)", "posB(inpb)", "angleB(-90)";
301       nccurve(r2)(muxout) "posA(out)", "angleA(180)", "posB(inpa)", "angleB(-90)";
302       % Connect port a
303       nccurve(a)(muxout) "angleA(-90)", "angleB(180)", "posB(sel)";
304       nccurve(a)(muxr1) "angleA(180)", "angleB(-90)", "posB(sel)";
305       nccurve(a)(muxr2) "angleA(180)", "angleB(-90)", "posB(sel)";
306       ncline(muxout)(out) "posA(out)";
307     \stopuseMPgraphic
308
309     \todo{Don't split registers in this image?}
310     \placeexample[][ex:NormalComplete]{Simple architecture consisting of an adder and a
311     subtractor.}
312       \startcombination[2*1]
313         {\typebufferlam{NormalComplete}}{Core description in normal form.}
314         {\boxedgraphic{NormalComplete}}{The architecture described by the normal form.}
315       \stopcombination
316     
317
318
319     \subsection[sec:normalization:intendednormalform]{Intended normal form definition}
320       Now we have some intuition for the normal form, we can describe how we want
321       the normal form to look like in a slightly more formal manner. The
322       EBNF-like description in \in{definition}[def:IntendedNormal] captures
323       most of the intended structure (and generates a subset of \GHC's core
324       format). 
325       
326       There are two things missing from this definition: cast expressions are
327       sometimes allowed by the prototype, but not specified here and the below
328       definition allows uses of state that cannot be translated to \VHDL\
329       properly. These two problems are discussed in
330       \in{section}[sec:normalization:castproblems] and
331       \in{section}[sec:normalization:stateproblems] respectively.
332
333       Some clauses have an expression listed behind them in parentheses.
334       These are conditions that need to apply to the clause. The
335       predicates used there (\lam{lvar()}, \lam{representable()},
336       \lam{gvar()}) will be defined in
337       \in{section}[sec:normalization:predicates].
338
339       An expression is in normal form if it matches the first
340       definition, \emph{normal}.
341
342       \todo{Fix indentation}
343       \startbuffer[IntendedNormal]
344       \italic{normal} := \italic{lambda}
345       \italic{lambda} := λvar.\italic{lambda}                        (representable(var))
346                       | \italic{toplet} 
347       \italic{toplet} := letrec [\italic{binding}...] in var         (representable(var))
348       \italic{binding} := var = \italic{rhs}                         (representable(rhs))
349                        -- State packing and unpacking by coercion
350                        | var0 = var1 ▶ State ty                      (lvar(var1))
351                        | var0 = var1 ▶ ty                            (var1 :: State ty ∧ lvar(var1))
352       \italic{rhs} := \italic{userapp}
353                    | \italic{builtinapp}
354                    -- Extractor case
355                    | case var of C a0 ... an -> ai                   (lvar(var))
356                    -- Selector case
357                    | case var of                                     (lvar(var))
358                       [ DEFAULT -> var ]                             (lvar(var))
359                       C0 w0,0 ... w0,n -> var0
360                       \vdots
361                       Cm wm,0 ... wm,n -> varm                       (\forall{}i \forall{}j, wi,j \neq vari, lvar(vari))
362       \italic{userapp} := \italic{userfunc}
363                        | \italic{userapp} {userarg}
364       \italic{userfunc} := var                                       (gvar(var))
365       \italic{userarg} := var                                        (lvar(var))
366       \italic{builtinapp} := \italic{builtinfunc}
367                           | \italic{builtinapp} \italic{builtinarg}
368       \italic{built-infunc} := var                                    (bvar(var))
369       \italic{built-inarg} := var                                     (representable(var) ∧ lvar(var))
370                           | \italic{partapp}                         (partapp :: a -> b)
371                           | \italic{coreexpr}                        (¬representable(coreexpr) ∧ ¬(coreexpr :: a -> b))
372       \italic{partapp} := \italic{userapp} 
373                        | \italic{builtinapp}
374       \stopbuffer
375
376       \placedefinition[][def:IntendedNormal]{Definition of the intended nnormal form using an \small{EBNF}-like syntax.}
377           {\defref{intended normal form definition}
378            \typebufferlam{IntendedNormal}}
379
380       When looking at such a program from a hardware perspective, the top
381       level lambda abstractions (\italic{lambda}) define the input ports.
382       Lambda abstractions cannot appear anywhere else. The variable reference
383       in the body of the recursive let expression (\italic{toplet}) is the
384       output port.  Most binders bound by the let expression define a
385       component instantiation (\italic{userapp}), where the input and output
386       ports are mapped to local signals (\italic{userarg}). Some of the others
387       use a built-in construction (\eg\ the \lam{case} expression) or call a
388       built-in function (\italic{builtinapp}) such as \lam{+} or \lam{map}.
389       For these, a hardcoded \small{VHDL} translation is available.
390
391   \section[sec:normalization:transformation]{Transformation notation}
392     To be able to concisely present transformations, we use a specific format
393     for them. It is a simple format, similar to one used in logic reasoning.
394
395     Such a transformation description looks like the following.
396
397     \starttrans
398     <context conditions>
399     ~
400     <original expression>
401     --------------------------          <expression conditions>
402     <transformed expression>
403     ~
404     <context additions>
405     \stoptrans
406
407     This format describes a transformation that applies to \lam{<original
408     expression>} and transforms it into \lam{<transformed expression>}, assuming
409     that all conditions are satisfied. In this format, there are a number of placeholders
410     in pointy brackets, most of which should be rather obvious in their meaning.
411     Nevertheless, we will more precisely specify their meaning below:
412
413       \startdesc{<original expression>} The expression pattern that will be matched
414       against (subexpressions of) the expression to be transformed. We call this a
415       pattern, because it can contain \emph{placeholders} (variables), which match
416       any expression or binder. Any such placeholder is said to be \emph{bound} to
417       the expression it matches. It is convention to use an uppercase letter (\eg\
418       \lam{M} or \lam{E}) to refer to any expression (including a simple variable
419       reference) and lowercase letters (\eg\ \lam{v} or \lam{b}) to refer to
420       (references to) binders.
421
422       For example, the pattern \lam{a + B} will match the expression 
423       \lam{v + (2 * w)} (binding \lam{a} to \lam{v} and \lam{B} to 
424       \lam{(2 * w)}), but not \lam{(2 * w) + v}.
425       \stopdesc
426
427       \startdesc{<expression conditions>}
428       These are extra conditions on the expression that is matched. These
429       conditions can be used to further limit the cases in which the
430       transformation applies, commonly to prevent a transformation from
431       causing a loop with itself or another transformation.
432
433       Only if these conditions are \emph{all} satisfied, the transformation
434       applies.
435       \stopdesc
436
437       \startdesc{<context conditions>}
438       These are a number of extra conditions on the context of the function. In
439       particular, these conditions can require some (other) top level function to be
440       present, whose value matches the pattern given here. The format of each of
441       these conditions is: \lam{binder = <pattern>}.
442
443       Typically, the binder is some placeholder bound in the \lam{<original
444       expression>}, while the pattern contains some placeholders that are used in
445       the \lam{transformed expression}.
446       
447       Only if a top level binder exists that matches each binder and pattern,
448       the transformation applies.
449       \stopdesc
450
451       \startdesc{<transformed expression>}
452       This is the expression template that is the result of the transformation. If, looking
453       at the above three items, the transformation applies, the \lam{<original
454       expression>} is completely replaced by the \lam{<transformed expression>}.
455       We call this a template, because it can contain placeholders, referring to
456       any placeholder bound by the \lam{<original expression>} or the
457       \lam{<context conditions>}. The resulting expression will have those
458       placeholders replaced by the values bound to them.
459
460       Any binder (lowercase) placeholder that has no value bound to it yet will be
461       bound to (and replaced with) a fresh binder.
462       \stopdesc
463
464       \startdesc{<context additions>}
465       These are templates for new functions to be added to the context.
466       This is a way to let a transformation create new top level
467       functions.
468
469       Each addition has the form \lam{binder = template}. As above, any
470       placeholder in the addition is replaced with the value bound to it, and any
471       binder placeholder that has no value bound to it yet will be bound to (and
472       replaced with) a fresh binder.
473       \stopdesc
474
475     To understand this notation better, the step by step application of
476     the η-expansion transformation to a simple \small{ALU} will be
477     shown. Consider η-expansion, which is a common transformation from
478     labmda calculus, described using above notation as follows:
479
480     \starttrans
481     E                 \lam{E :: a -> b}
482     --------------    \lam{E} does not occur on a function position in an application
483     λx.E x            \lam{E} is not a lambda abstraction.
484     \stoptrans
485
486     η-expansion is a well known transformation from lambda calculus. What
487     this transformation does, is take any expression that has a function type
488     and turn it into a lambda expression (giving an explicit name to the
489     argument). There are some extra conditions that ensure that this
490     transformation does not apply infinitely (which are not necessarily part
491     of the conventional definition of η-expansion).
492
493     Consider the following function, in Core notation, which is a fairly obvious way to specify a
494     simple \small{ALU} (Note that it is not yet in normal form, but
495     \in{example}[ex:AddSubAlu] shows the normal form of this function).
496     The parentheses around the \lam{+} and \lam{-} operators are
497     commonly used in Haskell to show that the operators are used as
498     normal functions, instead of \emph{infix} operators (\eg, the
499     operators appear before their arguments, instead of in between).
500
501     \startlambda 
502     alu :: Bit -> Word -> Word -> Word
503     alu = λopcode. case opcode of
504       Low -> (+)
505       High -> (-)
506     \stoplambda
507
508     There are a few subexpressions in this function to which we could possibly
509     apply the transformation. Since the pattern of the transformation is only
510     the placeholder \lam{E}, any expression will match that. Whether the
511     transformation applies to an expression is thus solely decided by the
512     conditions to the right of the transformation.
513
514     We will look at each expression in the function in a top down manner. The
515     first expression is the entire expression the function is bound to.
516
517     \startlambda
518     λopcode. case opcode of
519       Low -> (+)
520       High -> (-)
521     \stoplambda
522
523     As said, the expression pattern matches this. The type of this expression is
524     \lam{Bit -> Word -> Word -> Word}, which matches \lam{a -> b} (Note that in
525     this case \lam{a = Bit} and \lam{b = Word -> Word -> Word}).
526
527     Since this expression is at top level, it does not occur at a function
528     position of an application. However, The expression is a lambda abstraction,
529     so this transformation does not apply.
530
531     The next expression we could apply this transformation to, is the body of
532     the lambda abstraction:
533
534     \startlambda
535     case opcode of
536       Low -> (+)
537       High -> (-)
538     \stoplambda
539
540     The type of this expression is \lam{Word -> Word -> Word}, which again
541     matches \lam{a -> b}. The expression is the body of a lambda expression, so
542     it does not occur at a function position of an application. Finally, the
543     expression is not a lambda abstraction but a case expression, so all the
544     conditions match. There are no context conditions to match, so the
545     transformation applies.
546
547     By now, the placeholder \lam{E} is bound to the entire expression. The
548     placeholder \lam{x}, which occurs in the replacement template, is not bound
549     yet, so we need to generate a fresh binder for that. Let us use the binder
550     \lam{a}. This results in the following replacement expression:
551
552     \startlambda
553     λa.(case opcode of
554       Low -> (+)
555       High -> (-)) a
556     \stoplambda
557
558     Continuing with this expression, we see that the transformation does not
559     apply again (it is a lambda expression). Next we look at the body of this
560     lambda abstraction:
561
562     \startlambda
563     (case opcode of
564       Low -> (+)
565       High -> (-)) a
566     \stoplambda
567     
568     Here, the transformation does apply, binding \lam{E} to the entire
569     expression (which has type \lam{Word -> Word}) and binding \lam{x}
570     to the fresh binder \lam{b}, resulting in the replacement:
571
572     \startlambda
573     λb.(case opcode of
574       Low -> (+)
575       High -> (-)) a b
576     \stoplambda
577
578     The transformation does not apply to this lambda abstraction, so we
579     look at its body. For brevity, we will put the case expression on one line from
580     now on.
581
582     \startlambda
583     (case opcode of Low -> (+); High -> (-)) a b
584     \stoplambda
585
586     The type of this expression is \lam{Word}, so it does not match \lam{a -> b}
587     and the transformation does not apply. Next, we have two options for the
588     next expression to look at: the function position and argument position of
589     the application. The expression in the argument position is \lam{b}, which
590     has type \lam{Word}, so the transformation does not apply. The expression in
591     the function position is:
592
593     \startlambda
594     (case opcode of Low -> (+); High -> (-)) a
595     \stoplambda
596
597     Obviously, the transformation does not apply here, since it occurs in
598     function position (which makes the second condition false). In the same
599     way the transformation does not apply to both components of this
600     expression (\lam{case opcode of Low -> (+); High -> (-)} and \lam{a}), so
601     we will skip to the components of the case expression: the scrutinee and
602     both alternatives. Since the opcode is not a function, it does not apply
603     here.
604
605     The first alternative is \lam{(+)}. This expression has a function type
606     (the operator still needs two arguments). It does not occur in function
607     position of an application and it is not a lambda expression, so the
608     transformation applies.
609
610     We look at the \lam{<original expression>} pattern, which is \lam{E}.
611     This means we bind \lam{E} to \lam{(+)}. We then replace the expression
612     with the \lam{<transformed expression>}, replacing all occurences of
613     \lam{E} with \lam{(+)}. In the \lam{<transformed expression>}, the This gives us the replacement expression:
614     \lam{λx.(+) x} (A lambda expression binding \lam{x}, with a body that
615     applies the addition operator to \lam{x}).
616
617     The complete function then becomes:
618     \startlambda
619     (case opcode of Low -> λa1.(+) a1; High -> (-)) a
620     \stoplambda
621
622     Now the transformation no longer applies to the complete first alternative
623     (since it is a lambda expression). It does not apply to the addition
624     operator again, since it is now in function position in an application. It
625     does, however, apply to the application of the addition operator, since
626     that is neither a lambda expression nor does it occur in function
627     position. This means after one more application of the transformation, the
628     function becomes:
629
630     \startlambda
631     (case opcode of Low -> λa1.λb1.(+) a1 b1; High -> (-)) a
632     \stoplambda
633
634     The other alternative is left as an exercise to the reader. The final
635     function, after applying η-expansion until it does no longer apply is:
636
637     \startlambda 
638     alu :: Bit -> Word -> Word -> Word
639     alu = λopcode.λa.b. (case opcode of
640       Low -> λa1.λb1 (+) a1 b1
641       High -> λa2.λb2 (-) a2 b2) a b
642     \stoplambda
643
644     \subsection{Transformation application}
645       In this chapter we define a number of transformations, but how will we apply
646       these? As stated before, our normal form is reached as soon as no
647       transformation applies anymore. This means our application strategy is to
648       simply apply any transformation that applies, and continuing to do that with
649       the result of each transformation.
650
651       In particular, we define no particular order of transformations. Since
652       transformation order should not influence the resulting normal form,
653       this leaves the implementation free to choose any application order that
654       results in an efficient implementation. Unfortunately this is not
655       entirely true for the current set of transformations. See
656       \in{section}[sec:normalization:non-determinism] for a discussion of this
657       problem.
658
659       When applying a single transformation, we try to apply it to every (sub)expression
660       in a function, not just the top level function body. This allows us to
661       keep the transformation descriptions concise and powerful.
662
663     \subsection{Definitions}
664       A \emph{global variable} is any variable (binder) that is bound at the
665       top level of a program, or an external module. A \emph{local variable} is any
666       other variable (\eg, variables local to a function, which can be bound by
667       lambda abstractions, let expressions and pattern matches of case
668       alternatives). This is a slightly different notion of global versus
669       local than what \small{GHC} uses internally, but for our purposes
670       the distinction \GHC\ makes is not useful.
671       \defref{global variable} \defref{local variable}
672
673       A \emph{hardware representable} (or just \emph{representable}) type or value
674       is (a value of) a type that we can generate a signal for in hardware. For
675       example, a bit, a vector of bits, a 32 bit unsigned word, etc. Values that are
676       not runtime representable notably include (but are not limited to): types,
677       dictionaries, functions.
678       \defref{representable}
679
680       A \emph{built-in function} is a function supplied by the Cλash
681       framework, whose implementation is not used to generate \VHDL. This is
682       either because it is no valid Cλash (like most list functions that need
683       recursion) or because a Cλash implementation would be unwanted (for the
684       addition operator, for example, we would rather use the \VHDL addition
685       operator to let the synthesis tool decide what kind of adder to use
686       instead of explicitly describing one in Cλash). \defref{built-in
687       function}
688
689       These are functions like \lam{map}, \lam{hwor}, \lam{+} and \lam{length}.
690
691       For these functions, Cλash has a \emph{built-in hardware translation},
692       so calls to these functions can still be translated.  Built-in functions
693       must have a valid Haskell implementation, of course, to allow
694       simulation. 
695
696       A \emph{user-defined} function is a function for which no built-in
697       translation is available and whose definition will thus need to be
698       translated to Cλash. \defref{user-defined function}
699
700       \subsubsection[sec:normalization:predicates]{Predicates}
701         Here, we define a number of predicates that can be used below to concisely
702         specify conditions.
703
704         \emph{gvar(expr)} is true when \emph{expr} is a variable that references a
705         global variable. It is false when it references a local variable.
706
707         \emph{lvar(expr)} is the complement of \emph{gvar}; it is true when \emph{expr}
708         references a local variable, false when it references a global variable.
709
710         \emph{representable(expr)} is true when \emph{expr} is \emph{representable}.
711
712     \subsection[sec:normalization:uniq]{Binder uniqueness}
713       A common problem in transformation systems, is binder uniqueness. When not
714       considering this problem, it is easy to create transformations that mix up
715       bindings and cause name collisions. Take for example, the following core
716       expression:
717
718       \startlambda
719       (λa.λb.λc. a * b * c) x c
720       \stoplambda
721
722       By applying β-reduction (see \in{section}[sec:normalization:beta]) once,
723       we can simplify this expression to:
724
725       \startlambda
726       (λb.λc. x * b * c) c
727       \stoplambda
728
729       Now, we have replaced the \lam{a} binder with a reference to the \lam{x}
730       binder. No harm done here. But note that we see multiple occurences of the
731       \lam{c} binder. The first is a binding occurence, to which the second refers.
732       The last, however refers to \emph{another} instance of \lam{c}, which is
733       bound somewhere outside of this expression. Now, if we would apply beta
734       reduction without taking heed of binder uniqueness, we would get:
735
736       \startlambda
737       λc. x * c * c
738       \stoplambda
739
740       This is obviously not what was supposed to happen! The root of this problem is
741       the reuse of binders: identical binders can be bound in different,
742       but overlapping scopes. Any variable reference in those
743       overlapping scopes then refers to the variable bound in the inner
744       (smallest) scope. There is not way to refer to the variable in the
745       outer scope. This effect is usually referred to as
746       \emph{shadowing}: when a binder is bound in a scope where the
747       binder already had a value, the inner binding is said to
748       \emph{shadow} the outer binding. In the example above, the \lam{c}
749       binder was bound outside of the expression and in the inner lambda
750       expression. Inside that lambda expression, only the inner \lam{c}
751       can be accessed.
752
753       There are a number of ways to solve this. \small{GHC} has isolated this
754       problem to their binder substitution code, which performs \emph{deshadowing}
755       during its expression traversal. This means that any binding that shadows
756       another binding on a higher level is replaced by a new binder that does not
757       shadow any other binding. This non-shadowing invariant is enough to prevent
758       binder uniqueness problems in \small{GHC}.
759
760       In our transformation system, maintaining this non-shadowing invariant is
761       a bit harder to do (mostly due to implementation issues, the prototype
762       does not use \small{GHC}'s subsitution code). Also, the following points
763       can be observed.
764
765       \startitemize
766       \item Deshadowing does not guarantee overall uniqueness. For example, the
767       following (slightly contrived) expression shows the identifier \lam{x} bound in
768       two seperate places (and to different values), even though no shadowing
769       occurs.
770
771       \startlambda
772       (let x = 1 in x) + (let x = 2 in x)
773       \stoplambda
774
775       \item In our normal form (and the resulting \small{VHDL}), all binders
776       (signals) within the same function (entity) will end up in the same
777       scope. To allow this, all binders within the same function should be
778       unique.
779
780       \item When we know that all binders in an expression are unique, moving around
781       or removing a subexpression will never cause any binder conflicts. If we have
782       some way to generate fresh binders, introducing new subexpressions will not
783       cause any problems either. The only way to cause conflicts is thus to
784       duplicate an existing subexpression.
785       \stopitemize
786
787       Given the above, our prototype maintains a unique binder invariant. This
788       means that in any given moment during normalization, all binders \emph{within
789       a single function} must be unique. To achieve this, we apply the following
790       technique.
791
792       \todo{Define fresh binders and unique supplies}
793
794       \startitemize
795       \item Before starting normalization, all binders in the function are made
796       unique. This is done by generating a fresh binder for every binder used. This
797       also replaces binders that did not cause any conflict, but it does ensure that
798       all binders within the function are generated by the same unique supply.
799       \refdef{fresh binder}
800       \item Whenever a new binder must be generated, we generate a fresh binder that
801       is guaranteed to be different from \emph{all binders generated so far}. This
802       can thus never introduce duplication and will maintain the invariant.
803       \item Whenever (a part of) an expression is duplicated (for example when
804       inlining), all binders in the expression are replaced with fresh binders
805       (using the same method as at the start of normalization). These fresh binders
806       can never introduce duplication, so this will maintain the invariant.
807       \item Whenever we move part of an expression around within the function, there
808       is no need to do anything special. There is obviously no way to introduce
809       duplication by moving expressions around. Since we know that each of the
810       binders is already unique, there is no way to introduce (incorrect) shadowing
811       either.
812       \stopitemize
813
814   \section{Transform passes}
815     In this section we describe the actual transforms.
816
817     Each transformation will be described informally first, explaining
818     the need for and goal of the transformation. Then, we will formally define
819     the transformation using the syntax introduced in
820     \in{section}[sec:normalization:transformation].
821
822     \subsection{General cleanup}
823       \placeintermezzo{}{
824         \defref{substitution notation}
825         \startframedtext[width=8cm,background=box,frame=no]
826         \startalignment[center]
827           {\tfa Substitution notation}
828         \stopalignment
829         \blank[medium]
830
831         In some of the transformations in this chapter, we need to perform
832         substitution on an expression. Substitution means replacing every
833         occurence of some expression (usually a variable reference) with
834         another expression.
835
836         There have been a lot of different notations used in literature for
837         specifying substitution. The notation that will be used in this report
838         is the following:
839
840         \startlambda
841           E[A=>B]
842         \stoplambda
843
844         This means expression \lam{E} with all occurences of \lam{A} replaced
845         with \lam{B}.
846         \stopframedtext
847       }
848
849       These transformations are general cleanup transformations, that aim to
850       make expressions simpler. These transformations usually clean up the
851       mess left behind by other transformations or clean up expressions to
852       expose new transformation opportunities for other transformations.
853
854       Most of these transformations are standard optimizations in other
855       compilers as well. However, in our compiler, most of these are not just
856       optimizations, but they are required to get our program into intended
857       normal form.
858
859       \subsubsection[sec:normalization:beta]{β-reduction}
860         β-reduction is a well known transformation from lambda calculus, where it is
861         the main reduction step. It reduces applications of lambda abstractions,
862         removing both the lambda abstraction and the application.
863
864         In our transformation system, this step helps to remove unwanted lambda
865         abstractions (basically all but the ones at the top level). Other
866         transformations (application propagation, non-representable inlining) make
867         sure that most lambda abstractions will eventually be reducable by
868         β-reduction.
869
870         Note that β-reduction also works on type lambda abstractions and type
871         applications as well. This means the substitution below also works on
872         type variables, in the case that the binder is a type variable and teh
873         expression applied to is a type.
874
875         \starttrans
876         (λx.E) M
877         -----------------
878         E[x=>M]
879         \stoptrans
880
881         % And an example
882         \startbuffer[from]
883         (λa. 2 * a) (2 * b)
884         \stopbuffer
885
886         \startbuffer[to]
887         2 * (2 * b)
888         \stopbuffer
889
890         \transexample{beta}{β-reduction}{from}{to}
891
892         \startbuffer[from]
893         (λt.λa::t. a) @Int
894         \stopbuffer
895
896         \startbuffer[to]
897         (λa::Int. a)
898         \stopbuffer
899
900         \transexample{beta-type}{β-reduction for type abstractions}{from}{to}
901        
902       \subsubsection{Unused let binding removal}
903         This transformation removes let bindings that are never used.
904         Occasionally, \GHC's desugarer introduces some unused let bindings.
905
906         This normalization pass should really be not be necessary to get
907         into intended normal form (since the intended normal form
908         definition \refdef{intended normal form definition} does not
909         require that every binding is used), but in practice the
910         desugarer or simplifier emits some bindings that cannot be
911         normalized (e.g., calls to a
912         \hs{Control.Exception.Base.patError}) but are not used anywhere
913         either. To prevent the \VHDL\ generation from breaking on these
914         artifacts, this transformation removes them.
915
916         \todo{Do not use old-style numerals in transformations}
917         \starttrans
918         letrec
919           a0 = E0
920           \vdots
921           ai = Ei
922           \vdots
923           an = En
924         in
925           M                             \lam{ai} does not occur free in \lam{M}
926         ----------------------------    \lam{\forall j, 0 ≤ j ≤ n, j ≠ i} (\lam{ai} does not occur free in \lam{Ej})
927         letrec
928           a0 = E0
929           \vdots
930           ai-1 = Ei-1
931           ai+1 = Ei+1
932           \vdots
933           an = En
934         in
935           M
936         \stoptrans
937
938         % And an example
939         \startbuffer[from]
940         let
941           x = 1
942         in
943           2
944         \stopbuffer
945
946         \startbuffer[to]
947         let
948         in
949           2
950         \stopbuffer
951
952         \transexample{unusedlet}{Unused let binding removal}{from}{to}
953
954       \subsubsection{Empty let removal}
955         This transformation is simple: it removes recursive lets that have no bindings
956         (which usually occurs when unused let binding removal removes the last
957         binding from it).
958
959         Note that there is no need to define this transformation for
960         non-recursive lets, since they always contain exactly one binding.
961
962         \starttrans
963         letrec in M
964         --------------
965         M
966         \stoptrans
967
968         % And an example
969         \startbuffer[from]
970         let
971         in
972           2
973         \stopbuffer
974
975         \startbuffer[to]
976           2
977         \stopbuffer
978
979         \transexample{emptylet}{Empty let removal}{from}{to}
980
981       \subsubsection[sec:normalization:simplelet]{Simple let binding removal}
982         This transformation inlines simple let bindings, that bind some
983         binder to some other binder instead of a more complex expression (\ie\
984         a = b).
985
986         This transformation is not needed to get an expression into intended
987         normal form (since these bindings are part of the intended normal
988         form), but makes the resulting \small{VHDL} a lot shorter.
989        
990         \refdef{substitution notation}
991         \starttrans
992         letrec
993           a0 = E0
994           \vdots
995           ai = b
996           \vdots
997           an = En
998         in
999           M
1000         -----------------------------  \lam{b} is a variable reference
1001         letrec                         \lam{ai} ≠ \lam{b}
1002           a0 = E0 [ai=>b]
1003           \vdots
1004           ai-1 = Ei-1 [ai=>b]
1005           ai+1 = Ei+1 [ai=>b]
1006           \vdots
1007           an = En [ai=>b]
1008         in
1009           M[ai=>b]
1010         \stoptrans
1011
1012         \todo{example}
1013
1014       \subsubsection{Cast propagation / simplification}
1015         This transform pushes casts down into the expression as far as
1016         possible. This transformation has been added to make a few
1017         specific corner cases work, but it is not clear yet if this
1018         transformation handles cast expressions completely or in the
1019         right way. See \in{section}[sec:normalization:castproblems].
1020
1021         \starttrans
1022         (let binds in E) ▶ T
1023         -------------------------
1024         let binds in (E ▶ T)
1025         \stoptrans
1026
1027         \starttrans
1028         (case S of
1029           p0 -> E0
1030           \vdots
1031           pn -> En
1032         ) ▶ T
1033         -------------------------
1034         case S of
1035           p0 -> E0 ▶ T
1036           \vdots
1037           pn -> En ▶ T
1038         \stoptrans
1039
1040       \subsubsection{Top level binding inlining}
1041         \refdef{top level binding}
1042         This transform takes simple top level bindings generated by the
1043         \small{GHC} compiler. \small{GHC} sometimes generates very simple
1044         \quote{wrapper} bindings, which are bound to just a variable
1045         reference, or contain just a (partial) function appliation with
1046         the type and dictionary arguments filled in (such as the
1047         \lam{(+)} in the example below).
1048
1049         Note that this transformation is completely optional. It is not
1050         required to get any function into intended normal form, but it does help making
1051         the resulting VHDL output easier to read (since it removes components
1052         that do not add any real structure, but do hide away operations and
1053         cause extra clutter).
1054
1055         This transform takes any top level binding generated by \GHC,
1056         whose normalized form contains only a single let binding.
1057
1058         \starttrans
1059         x = λa0 ... λan.let y = E in y
1060         ~
1061         x
1062         --------------------------------------         \lam{x} is generated by the compiler
1063         λa0 ... λan.let y = E in y
1064         \stoptrans
1065
1066         \startbuffer[from]
1067         (+) :: Word -> Word -> Word
1068         (+) = GHC.Num.(+) @Word \$dNum
1069         ~
1070         (+) a b
1071         \stopbuffer
1072         \startbuffer[to]
1073         GHC.Num.(+) @ Alu.Word \$dNum a b
1074         \stopbuffer
1075
1076         \transexample{toplevelinline}{Top level binding inlining}{from}{to}
1077        
1078         \in{Example}[ex:trans:toplevelinline] shows a typical application of
1079         the addition operator generated by \GHC. The type and dictionary
1080         arguments used here are described in
1081         \in{Section}[section:prototype:polymorphism].
1082
1083         Without this transformation, there would be a \lam{(+)} entity
1084         in the \VHDL\ which would just add its inputs. This generates a
1085         lot of overhead in the \VHDL, which is particularly annoying
1086         when browsing the generated RTL schematic (especially since most
1087         non-alphanumerics, like all characters in \lam{(+)}, are not
1088         allowed in \VHDL\ architecture names\footnote{Technically, it is
1089         allowed to use non-alphanumerics when using extended
1090         identifiers, but it seems that none of the tooling likes
1091         extended identifiers in filenames, so it effectively does not
1092         work.}, so the entity would be called \quote{w7aA7f} or
1093         something similarly meaningless and autogenerated).
1094
1095     \subsection{Program structure}
1096       These transformations are aimed at normalizing the overall structure
1097       into the intended form. This means ensuring there is a lambda abstraction
1098       at the top for every argument (input port or current state), putting all
1099       of the other value definitions in let bindings and making the final
1100       return value a simple variable reference.
1101
1102       \subsubsection[sec:normalization:eta]{η-expansion}
1103         This transformation makes sure that all arguments of a function-typed
1104         expression are named, by introducing lambda expressions. When combined with
1105         β-reduction and non-representable binding inlining, all function-typed
1106         expressions should be lambda abstractions or global identifiers.
1107
1108         \starttrans
1109         E                 \lam{E :: a -> b}
1110         --------------    \lam{E} does not occur on a function position in an application
1111         λx.E x            \lam{E} is not a lambda abstraction.
1112         \stoptrans
1113
1114         \startbuffer[from]
1115         foo = λa.case a of 
1116           True -> λb.mul b b
1117           False -> id
1118         \stopbuffer
1119
1120         \startbuffer[to]
1121         foo = λa.λx.(case a of 
1122             True -> λb.mul b b
1123             False -> λy.id y) x
1124         \stopbuffer
1125
1126         \transexample{eta}{η-expansion}{from}{to}
1127
1128       \subsubsection[sec:normalization:appprop]{Application propagation}
1129         This transformation is meant to propagate application expressions downwards
1130         into expressions as far as possible. This allows partial applications inside
1131         expressions to become fully applied and exposes new transformation
1132         opportunities for other transformations (like β-reduction and
1133         specialization).
1134
1135         Since all binders in our expression are unique (see
1136         \in{section}[sec:normalization:uniq]), there is no risk that we will
1137         introduce unintended shadowing by moving an expression into a lower
1138         scope. Also, since only move expression into smaller scopes (down into
1139         our expression), there is no risk of moving a variable reference out
1140         of the scope in which it is defined.
1141
1142         \starttrans
1143         (letrec binds in E) M
1144         ------------------------
1145         letrec binds in E M
1146         \stoptrans
1147
1148         % And an example
1149         \startbuffer[from]
1150         ( letrec
1151             val = 1
1152           in 
1153             add val
1154         ) 3
1155         \stopbuffer
1156
1157         \startbuffer[to]
1158         letrec
1159           val = 1
1160         in 
1161           add val 3
1162         \stopbuffer
1163
1164         \transexample{appproplet}{Application propagation for a let expression}{from}{to}
1165
1166         \starttrans
1167         (case x of
1168           p0 -> E0
1169           \vdots
1170           pn -> En) M
1171         -----------------
1172         case x of
1173           p0 -> E0 M
1174           \vdots
1175           pn -> En M
1176         \stoptrans
1177
1178         % And an example
1179         \startbuffer[from]
1180         ( case x of 
1181             True -> id
1182             False -> neg
1183         ) 1
1184         \stopbuffer
1185
1186         \startbuffer[to]
1187         case x of 
1188           True -> id 1
1189           False -> neg 1
1190         \stopbuffer
1191
1192         \transexample{apppropcase}{Application propagation for a case expression}{from}{to}
1193
1194       \subsubsection[sec:normalization:letrecurse]{Let recursification}
1195         This transformation makes all non-recursive lets recursive. In the
1196         end, we want a single recursive let in our normalized program, so all
1197         non-recursive lets can be converted. This also makes other
1198         transformations simpler: they only need to be specified for recursive
1199         let expressions (and simply will not apply to non-recursive let
1200         expressions until this transformation has been applied).
1201
1202         \starttrans
1203         let
1204           a = E
1205         in
1206           M
1207         ------------------------------------------
1208         letrec
1209           a = E
1210         in
1211           M
1212         \stoptrans
1213
1214       \subsubsection{Let flattening}
1215         This transformation puts nested lets in the same scope, by lifting the
1216         binding(s) of the inner let into the outer let. Eventually, this will
1217         cause all let bindings to appear in the same scope.
1218
1219         This transformation only applies to recursive lets, since all
1220         non-recursive lets will be made recursive (see
1221         \in{section}[sec:normalization:letrecurse]).
1222
1223         Since we are joining two scopes together, there is no risk of moving a
1224         variable reference out of the scope where it is defined.
1225
1226         \starttrans
1227         letrec 
1228           a0 = E0
1229           \vdots
1230           ai = (letrec bindings in M)
1231           \vdots
1232           an = En
1233         in
1234           N
1235         ------------------------------------------
1236         letrec
1237           a0 = E0
1238           \vdots
1239           ai = M
1240           \vdots
1241           an = En
1242           bindings
1243         in
1244           N
1245         \stoptrans
1246
1247         \startbuffer[from]
1248         letrec
1249           a = 1
1250           b = letrec
1251             x = a
1252             y = c
1253           in
1254             x + y
1255           c = 2
1256         in
1257           b
1258         \stopbuffer
1259         \startbuffer[to]
1260         letrec
1261           a = 1
1262           b = x + y
1263           c = 2
1264           x = a
1265           y = c
1266         in
1267           b
1268         \stopbuffer
1269
1270         \transexample{letflat}{Let flattening}{from}{to}
1271
1272       \subsubsection{Return value simplification}
1273         This transformation ensures that the return value of a function is always a
1274         simple local variable reference.
1275
1276         This transformation only applies to the entire body of a
1277         function instead of any subexpression in a function. This is
1278         achieved by the contexts, like \lam{x = E}, though this is
1279         strictly not correct (you could read this as "if there is any
1280         function \lam{x} that binds \lam{E}, any \lam{E} can be
1281         transformed, while we only mean the \lam{E} that is bound by
1282         \lam{x}).
1283
1284         Note that the return value is not simplified if its not
1285         representable.  Otherwise, this would cause a direct loop with
1286         the inlining of unrepresentable bindings. If the return value is
1287         not representable because it has a function type, η-expansion
1288         should make sure that this transformation will eventually apply.
1289         If the value is not representable for other reasons, the
1290         function result itself is not representable, meaning this
1291         function is not translatable anyway.
1292
1293         \starttrans
1294         x = E                            \lam{E} is representable
1295         ~                                \lam{E} is not a lambda abstraction
1296         E                                \lam{E} is not a let expression
1297         ---------------------------      \lam{E} is not a local variable reference
1298         letrec x = E in x
1299         \stoptrans
1300
1301         \starttrans
1302         x = λv0 ... λvn.E                \lam{E} is representable
1303         ~                                \lam{E} is not a lambda abstraction
1304         E                                \lam{E} is not a let expression
1305         ---------------------------      \lam{E} is not a local variable reference
1306         letrec x = E in x
1307         \stoptrans
1308
1309         \starttrans
1310         x = λv0 ... λvn.let ... in E
1311         ~                                \lam{E} is representable
1312         E                                \lam{E} is not a local variable reference
1313         -----------------------------
1314         letrec x = E in x
1315         \stoptrans
1316
1317         \startbuffer[from]
1318         x = add 1 2
1319         \stopbuffer
1320
1321         \startbuffer[to]
1322         x = letrec x = add 1 2 in x
1323         \stopbuffer
1324
1325         \transexample{retvalsimpl}{Return value simplification}{from}{to}
1326         
1327         \todo{More examples}
1328
1329     \subsection[sec:normalization:argsimpl]{Representable arguments simplification}
1330       This section contains just a single transformation that deals with
1331       representable arguments in applications. Non-representable arguments are
1332       handled by the transformations in
1333       \in{section}[sec:normalization:nonrep]. 
1334       
1335       This transformation ensures that all representable arguments will become
1336       references to local variables. This ensures they will become references
1337       to local signals in the resulting \small{VHDL}, which is required due to
1338       limitations in the component instantiation code in \VHDL\ (one can only
1339       assign a signal or constant to an input port). By ensuring that all
1340       arguments are always simple variable references, we always have a signal
1341       available to map to the input ports.
1342
1343       To reduce a complex expression to a simple variable reference, we create
1344       a new let expression around the application, which binds the complex
1345       expression to a new variable. The original function is then applied to
1346       this variable.
1347
1348       \refdef{global variable}
1349       Note that references to \emph{global variables} (like a top level
1350       function without arguments, but also an argumentless dataconstructors
1351       like \lam{True}) are also simplified. Only local variables generate
1352       signals in the resulting architecture. Even though argumentless
1353       dataconstructors generate constants in generated \VHDL\ code and could be
1354       mapped to an input port directly, they are still simplified to make the
1355       normal form more regular.
1356
1357       \refdef{representable}
1358       \starttrans
1359       M N
1360       --------------------    \lam{N} is representable
1361       letrec x = N in M x     \lam{N} is not a local variable reference
1362       \stoptrans
1363       \refdef{local variable}
1364
1365       \startbuffer[from]
1366       add (add a 1) 1
1367       \stopbuffer
1368
1369       \startbuffer[to]
1370       letrec x = add a 1 in add x 1
1371       \stopbuffer
1372
1373       \transexample{argsimpl}{Argument simplification}{from}{to}
1374
1375     \subsection[sec:normalization:built-ins]{Built-in functions}
1376       This section deals with (arguments to) built-in functions.  In the
1377       intended normal form definition\refdef{intended normal form definition}
1378       we can see that there are three sorts of arguments a built-in function
1379       can receive.
1380       
1381       \startitemize[KR]
1382         \item A representable local variable reference. This is the most
1383         common argument to any function. The argument simplification
1384         transformation described in \in{section}[sec:normalization:argsimpl]
1385         makes sure that \emph{any} representable argument to \emph{any}
1386         function (including built-in functions) is turned into a local variable
1387         reference.
1388         \item (A partial application of) a top level function (either built-in on
1389         user-defined). The function extraction transformation described in
1390         this section takes care of turning every functiontyped argument into
1391         (a partial application of) a top level function.
1392         \item Any expression that is not representable and does not have a
1393         function type. Since these can be any expression, there is no
1394         transformation needed. Note that this category is exactly all
1395         expressions that are not transformed by the transformations for the
1396         previous two categories. This means that \emph{any} core expression
1397         that is used as an argument to a built-in function will be either
1398         transformed into one of the above categories, or end up in this
1399         categorie. In any case, the result is in normal form.
1400       \stopitemize
1401
1402       As noted, the argument simplification will handle any representable
1403       arguments to a built-in function. The following transformation is needed
1404       to handle non-representable arguments with a function type, all other
1405       non-representable arguments do not need any special handling.
1406
1407       \subsubsection[sec:normalization:funextract]{Function extraction}
1408         This transform deals with function-typed arguments to built-in
1409         functions. 
1410         Since built-in functions cannot be specialized (see
1411         \in{section}[sec:normalization:specialize]) to remove the arguments,
1412         these arguments are extracted into a new global function instead. In
1413         other words, we create a new top level function that has exactly the
1414         extracted argument as its body. This greatly simplifies the
1415         translation rules needed for built-in functions, since they only need
1416         to handle (partial applications of) top level functions.
1417
1418         Any free variables occuring in the extracted arguments will become
1419         parameters to the new global function. The original argument is replaced
1420         with a reference to the new function, applied to any free variables from
1421         the original argument.
1422
1423         This transformation is useful when applying higher-order built-in functions
1424         like \hs{map} to a lambda abstraction, for example. In this case, the code
1425         that generates \small{VHDL} for \hs{map} only needs to handle top level functions and
1426         partial applications, not any other expression (such as lambda abstractions or
1427         even more complicated expressions).
1428
1429         \starttrans
1430         M N                     \lam{M} is (a partial aplication of) a built-in function.
1431         ---------------------   \lam{f0 ... fn} are all free local variables of \lam{N}
1432         M (x f0 ... fn)         \lam{N :: a -> b}
1433         ~                       \lam{N} is not a (partial application of) a top level function
1434         x = λf0 ... λfn.N
1435         \stoptrans
1436
1437         \startbuffer[from]
1438         addList = λb.λxs.map (λa . add a b) xs
1439         \stopbuffer
1440
1441         \startbuffer[to]
1442         addList = λb.λxs.map (f b) xs
1443         ~
1444         f = λb.λa.add a b
1445         \stopbuffer
1446
1447         \transexample{funextract}{Function extraction}{from}{to}
1448
1449         Note that the function \lam{f} will still need normalization after
1450         this.
1451
1452     \subsection{Case normalisation}
1453       The transformations in this section ensure that case statements end up
1454       in normal form.
1455
1456       \subsubsection{Scrutinee simplification}
1457         This transform ensures that the scrutinee of a case expression is always
1458         a simple variable reference.
1459
1460         \starttrans
1461         case E of
1462           alts
1463         -----------------        \lam{E} is not a local variable reference
1464         letrec x = E in 
1465           case x of
1466             alts
1467         \stoptrans
1468
1469         \startbuffer[from]
1470         case (foo a) of
1471           True -> a
1472           False -> b
1473         \stopbuffer
1474
1475         \startbuffer[to]
1476         letrec x = foo a in
1477           case x of
1478             True -> a
1479             False -> b
1480         \stopbuffer
1481
1482         \transexample{letflat}{Case normalisation}{from}{to}
1483
1484
1485         \placeintermezzo{}{
1486           \defref{wild binders}
1487           \startframedtext[width=7cm,background=box,frame=no]
1488           \startalignment[center]
1489             {\tfa Wild binders}
1490           \stopalignment
1491           \blank[medium]
1492             In a functional expression, a \emph{wild binder} refers to any
1493             binder that is never referenced. This means that even though it
1494             will be bound to a particular value, that value is never used.
1495
1496             The Haskell syntax offers the underscore as a wild binder that
1497             cannot even be referenced (It can be seen as introducing a new,
1498             anonymous, binder everytime it is used).
1499             
1500             In these transformations, the term wild binder will sometimes be
1501             used to indicate that a binder must not be referenced.
1502           \stopframedtext
1503         }
1504
1505       \subsubsection{Scrutinee binder removal}
1506         This transformation removes (or rather, makes wild) the binder to
1507         which the scrutinee is bound after evaluation. This is done by
1508         replacing the bndr with the scrutinee in all alternatives. To prevent
1509         duplication of work, this transformation is only applied when the
1510         scrutinee is already a simple variable reference (but the previous
1511         transformation ensures this will eventually be the case). The
1512         scrutinee binder itself is replaced by a wild binder (which is no
1513         longer displayed).
1514
1515         Note that one could argue that this transformation can change the
1516         meaning of the Core expression. In the regular Core semantics, a case
1517         expression forces the evaluation of its scrutinee and can be used to
1518         implement strict evaluation. However, in the generated \VHDL,
1519         evaluation is always strict. So the semantics we assign to the Core
1520         expression (which differ only at this particular point), this
1521         transformation is completely valid.
1522
1523         \starttrans
1524         case x of bndr
1525           alts
1526         -----------------        \lam{x} is a local variable reference
1527         case x of
1528           alts[bndr=>x]
1529         \stoptrans
1530
1531         \startbuffer[from]
1532         case x of y
1533           True -> y
1534           False -> not y
1535         \stopbuffer
1536
1537         \startbuffer[to]
1538         case x of
1539           True -> x
1540           False -> not x
1541         \stopbuffer
1542
1543         \transexample{scrutbndrremove}{Scrutinee binder removal}{from}{to}
1544
1545       \subsubsection{Case normalization}
1546         This transformation ensures that all case expressions get a form
1547         that is allowed by the intended normal form. This means they
1548         will become one of:
1549
1550         \startitemize
1551         \item An extractor case with a single alternative that picks a field
1552         from a datatype, \eg\ \lam{case x of (a, b) -> a}.
1553         \item A selector case with multiple alternatives and only wild binders, that
1554         makes a choice between expressions based on the constructor of another
1555         expression, \eg\ \lam{case x of Low -> a; High -> b}.
1556         \stopitemize
1557
1558         For an arbitrary case, that has \lam{n} alternatives, with
1559         \lam{m} binders in each alternatives, this will result in \lam{m
1560         * n} extractor case expression to get at each variable, \lam{n}
1561         let bindings for each of the alternatives' value and a single
1562         selector case to select the right value out of these.
1563
1564         Technically, the defintion of this transformation would require
1565         that the constructor for every alternative has exactly the same
1566         amount (\lam{m}) of arguments, but of course this transformation
1567         also applies when this is not the case.
1568         
1569         \starttrans
1570         case E of
1571           C0 v0,0 ... v0,m -> E0
1572           \vdots
1573           Cn vn,0 ... vn,m -> En
1574         --------------------------------------------------- \lam{\forall i \forall j, 0 ≤ i ≤ n, 0 ≤ i < m} (\lam{wi,j} is a wild (unused) binder)
1575         letrec                                              The case expression is not an extractor case
1576           v0,0 = case E of C0 x0,0 .. x0,m -> x0,0          The case expression is not a selector case
1577           \vdots
1578           v0,m = case E of C0 x0,0 .. x0,m -> x0,m
1579           \vdots
1580           vn,m = case E of Cn xn,0 .. xn,m -> xn,m
1581           y0 = E0
1582           \vdots
1583           yn = En
1584         in
1585           case E of
1586             C0 w0,0 ... w0,m -> y0
1587             \vdots
1588             Cn wn,0 ... wn,m -> yn
1589         \stoptrans
1590
1591         Note that this transformation applies to case expressions with any
1592         scrutinee. If the scrutinee is a complex expression, this might
1593         result in duplication of work (hardware). An extra condition to
1594         only apply this transformation when the scrutinee is already
1595         simple (effectively causing this transformation to be only
1596         applied after the scrutinee simplification transformation) might
1597         be in order. 
1598
1599         \startbuffer[from]
1600         case a of
1601           True -> add b 1
1602           False -> add b 2
1603         \stopbuffer
1604
1605         \startbuffer[to]
1606         letrec
1607           x0 = add b 1
1608           x1 = add b 2
1609         in
1610           case a of
1611             True -> x0
1612             False -> x1
1613         \stopbuffer
1614
1615         \transexample{selcasesimpl}{Selector case simplification}{from}{to}
1616
1617         \startbuffer[from]
1618         case a of
1619           (,) b c -> add b c
1620         \stopbuffer
1621         \startbuffer[to]
1622         letrec
1623           b = case a of (,) b c -> b
1624           c = case a of (,) b c -> c
1625           x0 = add b c
1626         in
1627           case a of
1628             (,) w0 w1 -> x0
1629         \stopbuffer
1630
1631         \transexample{excasesimpl}{Extractor case simplification}{from}{to}
1632
1633         \refdef{selector case}
1634         In \in{example}[ex:trans:excasesimpl] the case expression is expanded
1635         into multiple case expressions, including a pretty useless expression
1636         (that is neither a selector or extractor case). This case can be
1637         removed by the Case removal transformation in
1638         \in{section}[sec:transformation:caseremoval].
1639
1640       \subsubsection[sec:transformation:caseremoval]{Case removal}
1641         This transform removes any case expression with a single alternative and
1642         only wild binders.\refdef{wild binders}
1643
1644         These "useless" case expressions are usually leftovers from case simplification
1645         on extractor case (see the previous example).
1646
1647         \starttrans
1648         case x of
1649           C v0 ... vm -> E
1650         ----------------------     \lam{\forall i, 0 ≤ i ≤ m} (\lam{vi} does not occur free in E)
1651         E
1652         \stoptrans
1653
1654         \startbuffer[from]
1655         case a of
1656           (,) w0 w1 -> x0
1657         \stopbuffer
1658
1659         \startbuffer[to]
1660         x0
1661         \stopbuffer
1662
1663         \transexample{caserem}{Case removal}{from}{to}
1664
1665     \subsection[sec:normalization:nonrep]{Removing unrepresentable values}
1666       The transformations in this section are aimed at making all the
1667       values used in our expression representable. There are two main
1668       transformations that are applied to \emph{all} unrepresentable let
1669       bindings and function arguments. These are meant to address three
1670       different kinds of unrepresentable values: polymorphic values,
1671       higher-order values and literals. The transformation are described
1672       generically: they apply to all non-representable values. However,
1673       non-representable values that do not fall into one of these three
1674       categories will be moved around by these transformations but are
1675       unlikely to completely disappear. They usually mean the program was not
1676       valid in the first place, because unsupported types were used (for
1677       example, a program using strings).
1678      
1679       Each of these three categories will be detailed below, followed by the
1680       actual transformations.
1681
1682       \subsubsection{Removing Polymorphism}
1683         As noted in \in{section}[sec:prototype:polymporphism],
1684         polymorphism is made explicit in Core through type and
1685         dictionary arguments. To remove the polymorphism from a
1686         function, we can simply specialize the polymorphic function for
1687         the particular type applied to it. The same goes for dictionary
1688         arguments. To remove polymorphism from let bound values, we
1689         simply inline the let bindings that have a polymorphic type,
1690         which should (eventually) make sure that the polymorphic
1691         expression is applied to a type and/or dictionary, which can
1692         then be removed by β-reduction (\in{section}[sec:normalization:beta]).
1693
1694         Since both type and dictionary arguments are not representable,
1695         \refdef{representable}
1696         the non-representable argument specialization and
1697         non-representable let binding inlining transformations below
1698         take care of exactly this.
1699
1700         There is one case where polymorphism cannot be completely
1701         removed: built-in functions are still allowed to be polymorphic
1702         (Since we have no function body that we could properly
1703         specialize). However, the code that generates \VHDL\ for built-in
1704         functions knows how to handle this, so this is not a problem.
1705
1706       \subsubsection[sec:normalization:defunctionalization]{Defunctionalization}
1707         These transformations remove higher-order expressions from our
1708         program, making all values first-order. The approach used for
1709         defunctionalization uses a combination of specialization, inlining and
1710         some cleanup transformations, was also proposed in parallel research
1711         by Neil Mitchell \cite[mitchell09].
1712       
1713         Higher order values are always introduced by lambda abstractions, none
1714         of the other Core expression elements can introduce a function type.
1715         However, other expressions can \emph{have} a function type, when they
1716         have a lambda expression in their body. 
1717         
1718         For example, the following expression is a higher-order expression
1719         that is not a lambda expression itself:
1720         
1721         \refdef{id function}
1722         \startlambda
1723           case x of
1724             High -> id
1725             Low -> λx.x
1726         \stoplambda
1727
1728         The reference to the \lam{id} function shows that we can introduce a
1729         higher-order expression in our program without using a lambda
1730         expression directly. However, inside the definition of the \lam{id}
1731         function, we can be sure that a lambda expression is present.
1732         
1733         Looking closely at the definition of our normal form in
1734         \in{section}[sec:normalization:intendednormalform], we can see that
1735         there are three possibilities for higher-order values to appear in our
1736         intended normal form:
1737
1738         \startitemize[KR]
1739           \item[item:toplambda] Lambda abstractions can appear at the highest level of a
1740           top level function. These lambda abstractions introduce the
1741           arguments (input ports / current state) of the function.
1742           \item[item:built-inarg] (Partial applications of) top level functions can appear as an
1743           argument to a built-in function.
1744           \item[item:completeapp] (Partial applications of) top level functions can appear in
1745           function position of an application. Since a partial application
1746           cannot appear anywhere else (except as built-in function arguments),
1747           all partial applications are applied, meaning that all applications
1748           will become complete applications. However, since application of
1749           arguments happens one by one, in the expression:
1750           \startlambda
1751             f 1 2
1752           \stoplambda
1753           the subexpression \lam{f 1} has a function type. But this is
1754           allowed, since it is inside a complete application.
1755         \stopitemize
1756
1757         We will take a typical function with some higher-order values as an
1758         example. The following function takes two arguments: a \lam{Bit} and a
1759         list of numbers. Depending on the first argument, each number in the
1760         list is doubled, or the list is returned unmodified. For the sake of
1761         the example, no polymorphism is shown. In reality, at least map would
1762         be polymorphic.
1763
1764         \startlambda
1765         λy.let double = λx. x + x in
1766              case y of
1767                 Low -> map double
1768                 High -> λz. z
1769         \stoplambda
1770
1771         This example shows a number of higher-order values that we cannot
1772         translate to \VHDL\ directly. The \lam{double} binder bound in the let
1773         expression has a function type, as well as both of the alternatives of
1774         the case expression. The first alternative is a partial application of
1775         the \lam{map} built-in function, whereas the second alternative is a
1776         lambda abstraction.
1777
1778         To reduce all higher-order values to one of the above items, a number
1779         of transformations we have already seen are used. The η-expansion
1780         transformation from \in{section}[sec:normalization:eta] ensures all
1781         function arguments are introduced by lambda abstraction on the highest
1782         level of a function. These lambda arguments are allowed because of
1783         \in{item}[item:toplambda] above. After η-expansion, our example
1784         becomes a bit bigger:
1785
1786         \startlambda
1787         λy.λq.(let double = λx. x + x in
1788                  case y of
1789                    Low -> map double
1790                    High -> λz. z
1791               ) q
1792         \stoplambda
1793
1794         η-expansion also introduces extra applications (the application of
1795         the let expression to \lam{q} in the above example). These
1796         applications can then propagated down by the application propagation
1797         transformation (\in{section}[sec:normalization:appprop]). In our
1798         example, the \lam{q} and \lam{r} variable will be propagated into the
1799         let expression and then into the case expression:
1800
1801         \startlambda
1802         λy.λq.let double = λx. x + x in
1803                 case y of
1804                   Low -> map double q
1805                   High -> (λz. z) q
1806         \stoplambda
1807         
1808         This propagation makes higher-order values become applied (in
1809         particular both of the alternatives of the case now have a
1810         representable type). Completely applied top level functions (like the
1811         first alternative) are now no longer invalid (they fall under
1812         \in{item}[item:completeapp] above). (Completely) applied lambda
1813         abstractions can be removed by β-expansion. For our example,
1814         applying β-expansion results in the following:
1815
1816         \startlambda
1817         λy.λq.let double = λx. x + x in
1818                 case y of
1819                   Low -> map double q
1820                   High -> q
1821         \stoplambda
1822
1823         As you can see in our example, all of this moves applications towards
1824         the higher-order values, but misses higher-order functions bound by
1825         let expressions. The applications cannot be moved towards these values
1826         (since they can be used in multiple places), so the values will have
1827         to be moved towards the applications. This is achieved by inlining all
1828         higher-order values bound by let applications, by the
1829         non-representable binding inlining transformation below. When applying
1830         it to our example, we get the following:
1831         
1832         \startlambda
1833         λy.λq.case y of
1834                 Low -> map (λx. x + x) q
1835                 High -> q
1836         \stoplambda
1837
1838         We have nearly eliminated all unsupported higher-order values from this
1839         expressions. The one that is remaining is the first argument to the
1840         \lam{map} function. Having higher-order arguments to a built-in
1841         function like \lam{map} is allowed in the intended normal form, but
1842         only if the argument is a (partial application) of a top level
1843         function. This is easily done by introducing a new top level function
1844         and put the lambda abstraction inside. This is done by the function
1845         extraction transformation from
1846         \in{section}[sec:normalization:funextract].
1847
1848         \startlambda
1849         λy.λq.case y of
1850                 Low -> map func q
1851                 High -> q
1852         \stoplambda
1853
1854         This also introduces a new function, that we have called \lam{func}:
1855
1856         \startlambda
1857         func = λx. x + x
1858         \stoplambda
1859
1860         Note that this does not actually remove the lambda, but now it is a
1861         lambda at the highest level of a function, which is allowed in the
1862         intended normal form.
1863
1864         There is one case that has not been discussed yet. What if the
1865         \lam{map} function in the example above was not a built-in function
1866         but a user-defined function? Then extracting the lambda expression
1867         into a new function would not be enough, since user-defined functions
1868         can never have higher-order arguments. For example, the following
1869         expression shows an example:
1870
1871         \startlambda
1872         twice :: (Word -> Word) -> Word -> Word
1873         twice = λf.λa.f (f a)
1874
1875         main = λa.app (λx. x + x) a
1876         \stoplambda
1877
1878         This example shows a function \lam{twice} that takes a function as a
1879         first argument and applies that function twice to the second argument.
1880         Again, we have made the function monomorphic for clarity, even though
1881         this function would be a lot more useful if it was polymorphic. The
1882         function \lam{main} uses \lam{twice} to apply a lambda epression twice.
1883
1884         When faced with a user defined function, a body is available for that
1885         function. This means we could create a specialized version of the
1886         function that only works for this particular higher-order argument
1887         (\ie, we can just remove the argument and call the specialized
1888         function without the argument). This transformation is detailed below.
1889         Applying this transformation to the example gives:
1890
1891         \startlambda
1892         twice' :: Word -> Word
1893         twice' = λb.(λf.λa.f (f a)) (λx. x + x) b
1894
1895         main = λa.app' a
1896         \stoplambda
1897
1898         The \lam{main} function is now in normal form, since the only
1899         higher-order value there is the top level lambda expression. The new
1900         \lam{twice'} function is a bit complex, but the entire original body
1901         of the original \lam{twice} function is wrapped in a lambda
1902         abstraction and applied to the argument we have specialized for
1903         (\lam{λx. x + x}) and the other arguments. This complex expression can
1904         fortunately be effectively reduced by repeatedly applying β-reduction: 
1905
1906         \startlambda
1907         twice' :: Word -> Word
1908         twice' = λb.(b + b) + (b + b)
1909         \stoplambda
1910
1911         This example also shows that the resulting normal form might not be as
1912         efficient as we might hope it to be (it is calculating \lam{(b + b)}
1913         twice). This is discussed in more detail in
1914         \in{section}[sec:normalization:duplicatework].
1915
1916       \subsubsection{Literals}
1917         There are a limited number of literals available in Haskell and Core.
1918         \refdef{enumerated types} When using (enumerating) algebraic
1919         datatypes, a literal is just a reference to the corresponding data
1920         constructor, which has a representable type (the algebraic datatype)
1921         and can be translated directly. This also holds for literals of the
1922         \hs{Bool} Haskell type, which is just an enumerated type.
1923
1924         There is, however, a second type of literal that does not have a
1925         representable type: integer literals. Cλash supports using integer
1926         literals for all three integer types supported (\hs{SizedWord},
1927         \hs{SizedInt} and \hs{RangedWord}). This is implemented using
1928         Haskell's \hs{Num} type class, which offers a \hs{fromInteger} method
1929         that converts any \hs{Integer} to the Cλash datatypes.
1930
1931         When \GHC\ sees integer literals, it will automatically insert calls to
1932         the \hs{fromInteger} method in the resulting Core expression. For
1933         example, the following expression in Haskell creates a 32 bit unsigned
1934         word with the value 1. The explicit type signature is needed, since
1935         there is no context for \GHC\ to determine the type from otherwise.
1936
1937         \starthaskell
1938         1 :: SizedWord D32
1939         \stophaskell
1940
1941         This Haskell code results in the following Core expression:
1942
1943         \startlambda
1944         fromInteger @(SizedWord D32) \$dNum (smallInteger 10)
1945         \stoplambda
1946
1947         The literal 10 will have the type \lam{GHC.Prim.Int\#}, which is
1948         converted into an \lam{Integer} by \lam{smallInteger}. Finally, the
1949         \lam{fromInteger} function will finally convert this into a
1950         \lam{SizedWord D32}.
1951
1952         Both the \lam{GHC.Prim.Int\#} and \lam{Integer} types are not
1953         representable, and cannot be translated directly. Fortunately, there
1954         is no need to translate them, since \lam{fromInteger} is a built-in
1955         function that knows how to handle these values. However, this does
1956         require that the \lam{fromInteger} function is directly applied to
1957         these non-representable literal values, otherwise errors will occur.
1958         For example, the following expression is not in the intended normal
1959         form, since one of the let bindings has an unrepresentable type
1960         (\lam{Integer}):
1961
1962         \startlambda
1963         let l = smallInteger 10 in fromInteger @(SizedWord D32) \$dNum l
1964         \stoplambda
1965
1966         By inlining these let-bindings, we can ensure that unrepresentable
1967         literals bound by a let binding end up in an application of the
1968         appropriate built-in function, where they are allowed. Since it is
1969         possible that the application of that function is in a different
1970         function than the definition of the literal value, we will always need
1971         to specialize away any unrepresentable literals that are used as
1972         function arguments. The following two transformations do exactly this.
1973
1974       \subsubsection{Non-representable binding inlining}
1975         This transform inlines let bindings that are bound to a
1976         non-representable value. Since we can never generate a signal
1977         assignment for these bindings (we cannot declare a signal assignment
1978         with a non-representable type, for obvious reasons), we have no choice
1979         but to inline the binding to remove it.
1980
1981         As we have seen in the previous sections, inlining these bindings
1982         solves (part of) the polymorphism, higher-order values and
1983         unrepresentable literals in an expression.
1984
1985         \refdef{substitution notation}
1986         \starttrans
1987         letrec 
1988           a0 = E0
1989           \vdots
1990           ai = Ei
1991           \vdots
1992           an = En
1993         in
1994           M
1995         --------------------------    \lam{Ei} has a non-representable type.
1996         letrec
1997           a0 = E0 [ai=>Ei] \vdots
1998           ai-1 = Ei-1 [ai=>Ei]
1999           ai+1 = Ei+1 [ai=>Ei]
2000           \vdots
2001           an = En [ai=>Ei]
2002         in
2003           M[ai=>Ei]
2004         \stoptrans
2005
2006         \startbuffer[from]
2007         letrec
2008           a = smallInteger 10
2009           inc = λb -> add b 1
2010           inc' = add 1
2011           x = fromInteger a 
2012         in
2013           inc (inc' x)
2014         \stopbuffer
2015
2016         \startbuffer[to]
2017         letrec
2018           x = fromInteger (smallInteger 10)
2019         in
2020           (λb -> add b 1) (add 1 x)
2021         \stopbuffer
2022
2023         \transexample{nonrepinline}{Nonrepresentable binding inlining}{from}{to}
2024
2025       \subsubsection[sec:normalization:specialize]{Function specialization}
2026         This transform removes arguments to user-defined functions that are
2027         not representable at runtime. This is done by creating a
2028         \emph{specialized} version of the function that only works for one
2029         particular value of that argument (in other words, the argument can be
2030         removed).
2031
2032         Specialization means to create a specialized version of the called
2033         function, with one argument already filled in. As a simple example, in
2034         the following program (this is not actual Core, since it directly uses
2035         a literal with the unrepresentable type \lam{GHC.Prim.Int\#}).
2036
2037         \startlambda
2038         f = λa.λb.a + b
2039         inc = λa.f a 1
2040         \stoplambda
2041
2042         We could specialize the function \lam{f} against the literal argument
2043         1, with the following result:
2044
2045         \startlambda
2046         f' = λa.a + 1
2047         inc = λa.f' a
2048         \stoplambda
2049
2050         In some way, this transformation is similar to β-reduction, but it
2051         operates across function boundaries. It is also similar to
2052         non-representable let binding inlining above, since it sort of
2053         \quote{inlines} an expression into a called function.
2054
2055         Special care must be taken when the argument has any free variables.
2056         If this is the case, the original argument should not be removed
2057         completely, but replaced by all the free variables of the expression.
2058         In this way, the original expression can still be evaluated inside the
2059         new function.
2060
2061         To prevent us from propagating the same argument over and over, a
2062         simple local variable reference is not propagated (since is has
2063         exactly one free variable, itself, we would only replace that argument
2064         with itself).
2065
2066         This shows that any free local variables that are not runtime
2067         representable cannot be brought into normal form by this transform. We
2068         rely on an inlining or β-reduction transformation to replace such a
2069         variable with an expression we can propagate again.
2070
2071         \starttrans
2072         x = E
2073         ~
2074         x Y0 ... Yi ... Yn                               \lam{Yi} is not representable
2075         ---------------------------------------------    \lam{Yi} is not a local variable reference
2076         x' Y0 ... Yi-1 f0 ...  fm Yi+1 ... Yn            \lam{f0 ... fm} are all free local vars of \lam{Yi}
2077         ~                                                \lam{T0 ... Tn} are the types of \lam{Y0 ... Yn}
2078         x' = λ(y0 :: T0) ... λ(yi-1 :: Ty-1). 
2079              λf0 ... λfm.
2080              λ(yi+1 :: Ty+1) ...  λ(yn :: Tn).       
2081                E y0 ... yi-1 Yi yi+1 ... yn   
2082         \stoptrans
2083
2084         This is a bit of a complex transformation. It transforms an
2085         application of the function \lam{x}, where one of the arguments
2086         (\lam{Y_i}) is not representable. A new
2087         function \lam{x'} is created that wraps the body of the old function.
2088         The body of the new function becomes a number of nested lambda
2089         abstractions, one for each of the original arguments that are left
2090         unchanged.
2091         
2092         The ith argument is replaced with the free variables of
2093         \lam{Y_i}. Note that we reuse the same binders as those used in
2094         \lam{Y_i}, since we can then just use \lam{Y_i} inside the new
2095         function body and have all of the variables it uses be in scope.
2096
2097         The argument that we are specializing for, \lam{Y_i}, is put inside
2098         the new function body. The old function body is applied to it. Since
2099         we use this new function only in place of an application with that
2100         particular argument \lam{Y_i}, behaviour should not change.
2101         
2102         Note that the types of the arguments of our new function are taken
2103         from the types of the \emph{actual} arguments (\lam{T0 ... Tn}). This
2104         means that any polymorphism in the arguments is removed, even when the
2105         corresponding explicit type lambda is not removed
2106         yet.
2107
2108         \todo{Examples. Perhaps reference the previous sections}
2109
2110   \section{Unsolved problems}
2111     The above system of transformations has been implemented in the prototype
2112     and seems to work well to compile simple and more complex examples of
2113     hardware descriptions. \todo{Ref christiaan?} However, this normalization
2114     system has not seen enough review and work to be complete and work for
2115     every Core expression that is supplied to it. A number of problems
2116     have already been identified and are discussed in this section.
2117
2118     \subsection[sec:normalization:duplicatework]{Work duplication}
2119         A possible problem of β-reduction is that it could duplicate work.
2120         When the expression applied is not a simple variable reference, but
2121         requires calculation and the binder the lambda abstraction binds to
2122         is used more than once, more hardware might be generated than strictly
2123         needed. 
2124
2125         As an example, consider the expression:
2126
2127         \startlambda
2128         (λx. x + x) (a * b)
2129         \stoplambda
2130
2131         When applying β-reduction to this expression, we get:
2132
2133         \startlambda
2134         (a * b) + (a * b)
2135         \stoplambda
2136
2137         which of course calculates \lam{(a * b)} twice.
2138         
2139         A possible solution to this would be to use the following alternative
2140         transformation, which is of course no longer normal β-reduction. The
2141         followin transformation has not been tested in the prototype, but is
2142         given here for future reference:
2143
2144         \starttrans
2145         (λx.E) M
2146         -----------------
2147         letrec x = M in E
2148         \stoptrans
2149         
2150         This does not seem like much of an improvement, but it does get rid of
2151         the lambda expression (and the associated higher-order value), while
2152         at the same time introducing a new let binding. Since the result of
2153         every application or case expression must be bound by a let expression
2154         in the intended normal form anyway, this is probably not a problem. If
2155         the argument happens to be a variable reference, then simple let
2156         binding removal (\in{section}[sec:normalization:simplelet]) will
2157         remove it, making the result identical to that of the original
2158         β-reduction transformation.
2159
2160         When also applying argument simplification to the above example, we
2161         get the following expression:
2162
2163         \startlambda
2164         let y = (a * b)
2165             z = (a * b)
2166         in y + z
2167         \stoplambda
2168
2169         Looking at this, we could imagine an alternative approach: create a
2170         transformation that removes let bindings that bind identical values.
2171         In the above expression, the \lam{y} and \lam{z} variables could be
2172         merged together, resulting in the more efficient expression:
2173
2174         \startlambda
2175         let y = (a * b) in y + y
2176         \stoplambda
2177
2178       \subsection[sec:normalization:non-determinism]{Non-determinism}
2179         As an example, again consider the following expression:
2180
2181         \startlambda
2182         (λx. x + x) (a * b)
2183         \stoplambda
2184
2185         We can apply both β-reduction (\in{section}[sec:normalization:beta])
2186         as well as argument simplification
2187         (\in{section}[sec:normalization:argsimpl]) to this expression.
2188
2189         When applying argument simplification first and then β-reduction, we
2190         get the following expression:
2191
2192         \startlambda
2193         let y = (a * b) in y + y
2194         \stoplambda
2195
2196         When applying β-reduction first and then argument simplification, we
2197         get the following expression:
2198
2199         \startlambda
2200         let y = (a * b)
2201             z = (a * b)
2202         in y + z
2203         \stoplambda
2204
2205         As you can see, this is a different expression. This means that the
2206         order of expressions, does in fact change the resulting normal form,
2207         which is something that we would like to avoid. In this particular
2208         case one of the alternatives is even clearly more efficient, so we
2209         would of course like the more efficient form to be the normal form.
2210
2211         For this particular problem, the solutions for duplication of work
2212         seem from the previous section seem to fix the determinism of our
2213         transformation system as well. However, it is likely that there are
2214         other occurences of this problem.
2215
2216       \subsection[sec:normalization:castproblems]{Casts}
2217         We do not fully understand the use of cast expressions in Core, so
2218         there are probably expressions involving cast expressions that cannot
2219         be brought into intended normal form by this transformation system.
2220
2221         The uses of casts in the core system should be investigated more and
2222         transformations will probably need updating to handle them in all
2223         cases.
2224
2225       \subsection[sec:normalization:stateproblems]{Normalization of stateful descriptions}
2226         Currently, the intended normal form definition\refdef{intended
2227         normal form definition} offers enough freedom to describe all
2228         valid stateful descriptions, but is not limiting enough. It is
2229         possible to write descriptions which are in intended normal
2230         form, but cannot be translated into \VHDL\ in a meaningful way
2231         (\eg, a function that swaps two substates in its result, or a
2232         function that changes a substate itself instead of passing it to
2233         a subfunction).
2234
2235         It is now up to the programmer to not do anything funny with
2236         these state values, whereas the normalization just tries not to
2237         mess up the flow of state values. In practice, there are
2238         situations where a Core program that \emph{could} be a valid
2239         stateful description is not translateable by the prototype. This
2240         most often happens when statefulness is mixed with pattern
2241         matching, causing a state input to be unpacked multiple times or
2242         be unpacked and repacked only in some of the code paths.
2243
2244         Without going into detail about the exact problems (of which
2245         there are probably more than have shown up so far), it seems
2246         unlikely that these problems can be solved entirely by just
2247         improving the \VHDL\ state generation in the final stage. The
2248         normalization stage seems the best place to apply the rewriting
2249         needed to support more complex stateful descriptions. This does
2250         of course mean that the intended normal form definition must be
2251         extended as well to be more specific about how state handling
2252         should look like in normal form.
2253         \in{Section}[sec:prototype:statelimits] already contains a
2254         tight description of the limitations on the use of state
2255         variables, which could be adapted into the intended normal form.
2256
2257   \section[sec:normalization:properties]{Provable properties}
2258     When looking at the system of transformations outlined above, there are a
2259     number of questions that we can ask ourselves. The main question is of course:
2260     \quote{Does our system work as intended?}. We can split this question into a
2261     number of subquestions:
2262
2263     \startitemize[KR]
2264     \item[q:termination] Does our system \emph{terminate}? Since our system will
2265     keep running as long as transformations apply, there is an obvious risk that
2266     it will keep running indefinitely. This typically happens when one
2267     transformation produces a result that is transformed back to the original
2268     by another transformation, or when one or more transformations keep
2269     expanding some expression.
2270     \item[q:soundness] Is our system \emph{sound}? Since our transformations
2271     continuously modify the expression, there is an obvious risk that the final
2272     normal form will not be equivalent to the original program: its meaning could
2273     have changed.
2274     \item[q:completeness] Is our system \emph{complete}? Since we have a complex
2275     system of transformations, there is an obvious risk that some expressions will
2276     not end up in our intended normal form, because we forgot some transformation.
2277     In other words: does our transformation system result in our intended normal
2278     form for all possible inputs?
2279     \item[q:determinism] Is our system \emph{deterministic}? Since we have defined
2280     no particular order in which the transformation should be applied, there is an
2281     obvious risk that different transformation orderings will result in
2282     \emph{different} normal forms. They might still both be intended normal forms
2283     (if our system is \emph{complete}) and describe correct hardware (if our
2284     system is \emph{sound}), so this property is less important than the previous
2285     three: the translator would still function properly without it.
2286     \stopitemize
2287
2288     Unfortunately, the final transformation system has only been
2289     developed in the final part of the research, leaving no more time
2290     for verifying these properties. In fact, it is likely that the
2291     current transformation system still violates some of these
2292     properties in some cases (see
2293     \in{section}[sec:normalization:non-determinism] and
2294     \in{section}[sec:normalization:stateproblems]) and should be improved (or
2295     extra conditions on the input hardware descriptions should be formulated).
2296
2297     This is most likely the case with the completeness and determinism
2298     properties, perhaps also the termination property. The soundness
2299     property probably holds, since it is easier to manually verify (each
2300     transformation can be reviewed separately).
2301
2302     Even though no complete proofs have been made, some ideas for
2303     possible proof strategies are shown below.
2304
2305     \subsection{Graph representation}
2306       Before looking into how to prove these properties, we will look at
2307       transformation systems from a graph perspective. We will first define
2308       the graph view and then illustrate it using a simple example from lambda
2309       calculus (which is a different system than the Cλash normalization
2310       system). The nodes of the graph are all possible Core expressions. The
2311       (directed) edges of the graph are transformations. When a transformation
2312       α applies to an expression \lam{A} to produce an expression \lam{B}, we
2313       add an edge from the node for \lam{A} to the node for \lam{B}, labeled
2314       α.
2315
2316       \startuseMPgraphic{TransformGraph}
2317         save a, b, c, d;
2318
2319         % Nodes
2320         newCircle.a(btex \lam{(λx.λy. (+) x y) 1} etex);
2321         newCircle.b(btex \lam{λy. (+) 1 y} etex);
2322         newCircle.c(btex \lam{(λx.(+) x) 1} etex);
2323         newCircle.d(btex \lam{(+) 1} etex);
2324
2325         b.c = origin;
2326         c.c = b.c + (4cm, 0cm);
2327         a.c = midpoint(b.c, c.c) + (0cm, 4cm);
2328         d.c = midpoint(b.c, c.c) - (0cm, 3cm);
2329
2330         % β-conversion between a and b
2331         ncarc.a(a)(b) "name(bred)";
2332         ObjLabel.a(btex $\xrightarrow[normal]{}{β}$ etex) "labpathname(bred)", "labdir(rt)";
2333         ncarc.b(b)(a) "name(bexp)", "linestyle(dashed withdots)";
2334         ObjLabel.b(btex $\xleftarrow[normal]{}{β}$ etex) "labpathname(bexp)", "labdir(lft)";
2335
2336         % η-conversion between a and c
2337         ncarc.a(a)(c) "name(ered)";
2338         ObjLabel.a(btex $\xrightarrow[normal]{}{η}$ etex) "labpathname(ered)", "labdir(rt)";
2339         ncarc.c(c)(a) "name(eexp)", "linestyle(dashed withdots)";
2340         ObjLabel.c(btex $\xleftarrow[normal]{}{η}$ etex) "labpathname(eexp)", "labdir(lft)";
2341
2342         % η-conversion between b and d
2343         ncarc.b(b)(d) "name(ered)";
2344         ObjLabel.b(btex $\xrightarrow[normal]{}{η}$ etex) "labpathname(ered)", "labdir(rt)";
2345         ncarc.d(d)(b) "name(eexp)", "linestyle(dashed withdots)";
2346         ObjLabel.d(btex $\xleftarrow[normal]{}{η}$ etex) "labpathname(eexp)", "labdir(lft)";
2347
2348         % β-conversion between c and d
2349         ncarc.c(c)(d) "name(bred)";
2350         ObjLabel.c(btex $\xrightarrow[normal]{}{β}$ etex) "labpathname(bred)", "labdir(rt)";
2351         ncarc.d(d)(c) "name(bexp)", "linestyle(dashed withdots)";
2352         ObjLabel.d(btex $\xleftarrow[normal]{}{β}$ etex) "labpathname(bexp)", "labdir(lft)";
2353
2354         % Draw objects and lines
2355         drawObj(a, b, c, d);
2356       \stopuseMPgraphic
2357
2358       \placeexample[right][ex:TransformGraph]{Partial graph of a lambda calculus
2359       system with β and η reduction (solid lines) and expansion (dotted lines).}
2360           \boxedgraphic{TransformGraph}
2361
2362       Of course the graph for Cλash is unbounded, since we can construct an
2363       infinite amount of Core expressions. Also, there might potentially be
2364       multiple edges between two given nodes (with different labels), though
2365       this seems unlikely to actually happen in our system.
2366
2367       See \in{example}[ex:TransformGraph] for the graph representation of a very
2368       simple lambda calculus that contains just the expressions \lam{(λx.λy. (+) x
2369       y) 1}, \lam{λy. (+) 1 y}, \lam{(λx.(+) x) 1} and \lam{(+) 1}. The
2370       transformation system consists of β-reduction and η-reduction (solid edges) or
2371       β-expansion and η-expansion (dotted edges).
2372
2373       \todo{Define β-reduction and η-reduction?}
2374
2375       In such a graph a node (expression) is in normal form if it has no
2376       outgoing edges (meaning no transformation applies to it). The set of
2377       nodes without outgoing edges is called the \emph{normal set}. Similarly,
2378       the set of nodes containing expressions in intended normal form
2379       \refdef{intended normal form} is called the \emph{intended normal set}.
2380
2381       From such a graph, we can derive some properties easily:
2382       \startitemize[KR]
2383         \item A system will \emph{terminate} if there is no walk (sequence of
2384         edges, or transformations) of infinite length in the graph (this
2385         includes cycles, but can also happen without cycles).
2386         \item Soundness is not easily represented in the graph.
2387         \item A system is \emph{complete} if all of the nodes in the normal set have
2388         the intended normal form. The inverse (that all of the nodes outside of
2389         the normal set are \emph{not} in the intended normal form) is not
2390         strictly required. In other words, our normal set must be a
2391         subset of the intended normal form, but they do not need to be
2392         the same set.
2393         form.
2394         \item A system is deterministic if all paths starting at a particular
2395         node, which end in a node in the normal set, end at the same node.
2396       \stopitemize
2397
2398       When looking at the \in{example}[ex:TransformGraph], we see that the system
2399       terminates for both the reduction and expansion systems (but note that, for
2400       expansion, this is only true because we have limited the possible
2401       expressions.  In complete lambda calculus, there would be a path from
2402       \lam{(λx.λy. (+) x y) 1} to \lam{(λx.λy.(λz.(+) z) x y) 1} to
2403       \lam{(λx.λy.(λz.(λq.(+) q) z) x y) 1} etc.)
2404
2405       If we would consider the system with both expansion and reduction, there
2406       would no longer be termination either, since there would be cycles all
2407       over the place.
2408
2409       The reduction and expansion systems have a normal set of containing just
2410       \lam{(+) 1} or \lam{(λx.λy. (+) x y) 1} respectively. Since all paths in
2411       either system end up in these normal forms, both systems are \emph{complete}.
2412       Also, since there is only one node in the normal set, it must obviously be
2413       \emph{deterministic} as well.
2414
2415     \subsection{Termination}
2416       In general, proving termination of an arbitrary program is a very
2417       hard problem. \todo{Ref about arbitrary termination} Fortunately,
2418       we only have to prove termination for our specific transformation
2419       system.
2420
2421       A common approach for these kinds of proofs is to associate a
2422       measure with each possible expression in our system. If we can
2423       show that each transformation strictly decreases this measure
2424       (\ie, the expression transformed to has a lower measure than the
2425       expression transformed from).  \todo{ref about measure-based
2426       termination proofs / analysis}
2427       
2428       A good measure for a system consisting of just β-reduction would
2429       be the number of lambda expressions in the expression. Since every
2430       application of β-reduction removes a lambda abstraction (and there
2431       is always a bounded number of lambda abstractions in every
2432       expression) we can easily see that a transformation system with
2433       just β-reduction will always terminate.
2434
2435       For our complete system, this measure would be fairly complex
2436       (probably the sum of a lot of things). Since the (conditions on)
2437       our transformations are pretty complex, we would need to include
2438       both simple things like the number of let expressions as well as
2439       more complex things like the number of case expressions that are
2440       not yet in normal form.
2441
2442       No real attempt has been made at finding a suitable measure for
2443       our system yet.
2444
2445     \subsection{Soundness}
2446       Soundness is a property that can be proven for each transformation
2447       separately. Since our system only runs separate transformations
2448       sequentially, if each of our transformations leaves the
2449       \emph{meaning} of the expression unchanged, then the entire system
2450       will of course leave the meaning unchanged and is thus
2451       \emph{sound}.
2452
2453       The current prototype has only been verified in an ad-hoc fashion
2454       by inspecting (the code for) each transformation. A more formal
2455       verification would be more appropriate.
2456
2457       To be able to formally show that each transformation properly
2458       preserves the meaning of every expression, we require an exact
2459       definition of the \emph{meaning} of every expression, so we can
2460       compare them. A definition of the operational semantics of \GHC's Core
2461       language is available \cite[sulzmann07], but this does not seem
2462       sufficient for our goals (but it is a good start).
2463
2464       It should be possible to have a single formal definition of
2465       meaning for Core for both normal Core compilation by \GHC\ and for
2466       our compilation to \VHDL. The main difference seems to be that in
2467       hardware every expression is always evaluated, while in software
2468       it is only evaluated if needed, but it should be possible to
2469       assign a meaning to core expressions that assumes neither.
2470       
2471       Since each of the transformations can be applied to any
2472       subexpression as well, there is a constraint on our meaning
2473       definition: the meaning of an expression should depend only on the
2474       meaning of subexpressions, not on the expressions themselves. For
2475       example, the meaning of the application in \lam{f (let x = 4 in
2476       x)} should be the same as the meaning of the application in \lam{f
2477       4}, since the argument subexpression has the same meaning (though
2478       the actual expression is different).
2479       
2480     \subsection{Completeness}
2481       Proving completeness is probably not hard, but it could be a lot
2482       of work. We have seen above that to prove completeness, we must
2483       show that the normal set of our graph representation is a subset
2484       of the intended normal set.
2485
2486       However, it is hard to systematically generate or reason about the
2487       normal set, since it is defined as any nodes to which no
2488       transformation applies. To determine this set, each transformation
2489       must be considered and when a transformation is added, the entire
2490       set should be re-evaluated. This means it is hard to show that
2491       each node in the normal set is also in the intended normal set.
2492       Reasoning about our intended normal set is easier, since we know
2493       how to generate it from its definition. \refdef{intended normal
2494       form definition}
2495
2496       Fortunately, we can also prove the complement (which is
2497       equivalent, since $A \subseteq B \Leftrightarrow \overline{B}
2498       \subseteq \overline{A}$): show that the set of nodes not in
2499       intended normal form is a subset of the set of nodes not in normal
2500       form. In other words, show that for every expression that is not
2501       in intended normal form, that there is at least one transformation
2502       that applies to it (since that means it is not in normal form
2503       either and since $A \subseteq C \Leftrightarrow \forall x (x \in A
2504       \rightarrow x \in C)$).
2505
2506       By systematically reviewing the entire Core language definition
2507       along with the intended normal form definition (both of which have
2508       a similar structure), it should be possible to identify all
2509       possible (sets of) core expressions that are not in intended
2510       normal form and identify a transformation that applies to it.
2511       
2512       This approach is especially useful for proving completeness of our
2513       system, since if expressions exist to which none of the
2514       transformations apply (\ie\ if the system is not yet complete), it
2515       is immediately clear which expressions these are and adding
2516       (or modifying) transformations to fix this should be relatively
2517       easy.
2518
2519       As observed above, applying this approach is a lot of work, since
2520       we need to check every (set of) transformation(s) separately.
2521
2522       \todo{Perhaps do a few steps of the proofs as proof-of-concept}
2523
2524 % vim: set sw=2 sts=2 expandtab: