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