ed55016047d2f4c8e33cd1bddb89ef4d8962c080
[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{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       \todo{Fix indentation}
329       \startlambda
330       \italic{normal} = \italic{lambda}
331       \italic{lambda} = λvar.\italic{lambda} (representable(var))
332                       | \italic{toplet} 
333       \italic{toplet} = letrec [\italic{binding}...] in var (representable(varvar))
334       \italic{binding} = var = \italic{rhs} (representable(rhs))
335                        -- State packing and unpacking by coercion
336                        | var0 = var1 :: State ty (lvar(var1))
337                        | var0 = var1 :: ty (var0 :: State ty) (lvar(var1))
338       \italic{rhs} = userapp
339                    | builtinapp
340                    -- Extractor case
341                    | case var of C a0 ... an -> ai (lvar(var))
342                    -- Selector case
343                    | case var of (lvar(var))
344                       DEFAULT -> var0 (lvar(var0))
345                       C w0 ... wn -> resvar (\forall{}i, wi \neq resvar, lvar(resvar))
346       \italic{userapp} = \italic{userfunc}
347                        | \italic{userapp} {userarg}
348       \italic{userfunc} = var (gvar(var))
349       \italic{userarg} = var (lvar(var))
350       \italic{builtinapp} = \italic{builtinfunc}
351                           | \italic{builtinapp} \italic{builtinarg}
352       \italic{builtinfunc} = var (bvar(var))
353       \italic{builtinarg} = \italic{coreexpr}
354       \stoplambda
355
356       \todo{Limit builtinarg further}
357
358       \todo{There can still be other casts around (which the code can handle,
359       e.g., ignore), which still need to be documented here}
360
361       \todo{Note about the selector case. It just supports Bit and Bool
362       currently, perhaps it should be generalized in the normal form? This is
363       no longer true, btw}
364
365       When looking at such a program from a hardware perspective, the top level
366       lambda's define the input ports. The variable referenc in the body of
367       the recursive let expression is the output port. Most function
368       applications bound by the let expression define a component
369       instantiation, where the input and output ports are mapped to local
370       signals or arguments. Some of the others use a builtin construction (\eg
371       the \lam{case} expression) or call a builtin function (\eg \lam{+} or
372       \lam{map}). For these, a hardcoded \small{VHDL} translation is
373       available.
374
375   \section[sec:normalization:transformation]{Transformation notation}
376     To be able to concisely present transformations, we use a specific format
377     for them. It is a simple format, similar to one used in logic reasoning.
378
379     Such a transformation description looks like the following.
380
381     \starttrans
382     <context conditions>
383     ~
384     <original expression>
385     --------------------------          <expression conditions>
386     <transformed expresssion>
387     ~
388     <context additions>
389     \stoptrans
390
391     This format desribes a transformation that applies to \lam{<original
392     expresssion>} and transforms it into \lam{<transformed expression>}, assuming
393     that all conditions apply. In this format, there are a number of placeholders
394     in pointy brackets, most of which should be rather obvious in their meaning.
395     Nevertheless, we will more precisely specify their meaning below:
396
397       \startdesc{<original expression>} The expression pattern that will be matched
398       against (subexpressions of) the expression to be transformed. We call this a
399       pattern, because it can contain \emph{placeholders} (variables), which match
400       any expression or binder. Any such placeholder is said to be \emph{bound} to
401       the expression it matches. It is convention to use an uppercase letter (\eg
402       \lam{M} or \lam{E}) to refer to any expression (including a simple variable
403       reference) and lowercase letters (\eg \lam{v} or \lam{b}) to refer to
404       (references to) binders.
405
406       For example, the pattern \lam{a + B} will match the expression 
407       \lam{v + (2 * w)} (binding \lam{a} to \lam{v} and \lam{B} to 
408       \lam{(2 * w)}), but not \lam{(2 * w) + v}.
409       \stopdesc
410
411       \startdesc{<expression conditions>}
412       These are extra conditions on the expression that is matched. These
413       conditions can be used to further limit the cases in which the
414       transformation applies, commonly to prevent a transformation from
415       causing a loop with itself or another transformation.
416
417       Only if these conditions are \emph{all} true, the transformation
418       applies.
419       \stopdesc
420
421       \startdesc{<context conditions>}
422       These are a number of extra conditions on the context of the function. In
423       particular, these conditions can require some (other) top level function to be
424       present, whose value matches the pattern given here. The format of each of
425       these conditions is: \lam{binder = <pattern>}.
426
427       Typically, the binder is some placeholder bound in the \lam{<original
428       expression>}, while the pattern contains some placeholders that are used in
429       the \lam{transformed expression}.
430       
431       Only if a top level binder exists that matches each binder and pattern,
432       the transformation applies.
433       \stopdesc
434
435       \startdesc{<transformed expression>}
436       This is the expression template that is the result of the transformation. If, looking
437       at the above three items, the transformation applies, the \lam{<original
438       expression>} is completely replaced with the \lam{<transformed expression>}.
439       We call this a template, because it can contain placeholders, referring to
440       any placeholder bound by the \lam{<original expression>} or the
441       \lam{<context conditions>}. The resulting expression will have those
442       placeholders replaced by the values bound to them.
443
444       Any binder (lowercase) placeholder that has no value bound to it yet will be
445       bound to (and replaced with) a fresh binder.
446       \stopdesc
447
448       \startdesc{<context additions>}
449       These are templates for new functions to add to the context. This is a way
450       to have a transformation create new top level functions.
451
452       Each addition has the form \lam{binder = template}. As above, any
453       placeholder in the addition is replaced with the value bound to it, and any
454       binder placeholder that has no value bound to it yet will be bound to (and
455       replaced with) a fresh binder.
456       \stopdesc
457
458     As an example, we'll look at η-abstraction:
459
460     \starttrans
461     E                 \lam{E :: a -> b}
462     --------------    \lam{E} does not occur on a function position in an application
463     λx.E x            \lam{E} is not a lambda abstraction.
464     \stoptrans
465
466     η-abstraction is a well known transformation from lambda calculus. What
467     this transformation does, is take any expression that has a function type
468     and turn it into a lambda expression (giving an explicit name to the
469     argument). There are some extra conditions that ensure that this
470     transformation does not apply infinitely (which are not necessarily part
471     of the conventional definition of η-abstraction).
472
473     Consider the following function, which is a fairly obvious way to specify a
474     simple ALU (Note that \in{example}[ex:AddSubAlu] shows the normal form of this
475     function). The parentheses around the \lam{+} and \lam{-} operators are
476     commonly used in Haskell to show that the operators are used as normal
477     functions, instead of \emph{infix} operators (\eg, the operators appear
478     before their arguments, instead of in between).
479
480     \startlambda 
481     alu :: Bit -> Word -> Word -> Word
482     alu = λopcode. case opcode of
483       Low -> (+)
484       High -> (-)
485     \stoplambda
486
487     There are a few subexpressions in this function to which we could possibly
488     apply the transformation. Since the pattern of the transformation is only
489     the placeholder \lam{E}, any expression will match that. Whether the
490     transformation applies to an expression is thus solely decided by the
491     conditions to the right of the transformation.
492
493     We will look at each expression in the function in a top down manner. The
494     first expression is the entire expression the function is bound to.
495
496     \startlambda
497     λopcode. case opcode of
498       Low -> (+)
499       High -> (-)
500     \stoplambda
501
502     As said, the expression pattern matches this. The type of this expression is
503     \lam{Bit -> Word -> Word -> Word}, which matches \lam{a -> b} (Note that in
504     this case \lam{a = Bit} and \lam{b = Word -> Word -> Word}).
505
506     Since this expression is at top level, it does not occur at a function
507     position of an application. However, The expression is a lambda abstraction,
508     so this transformation does not apply.
509
510     The next expression we could apply this transformation to, is the body of
511     the lambda abstraction:
512
513     \startlambda
514     case opcode of
515       Low -> (+)
516       High -> (-)
517     \stoplambda
518
519     The type of this expression is \lam{Word -> Word -> Word}, which again
520     matches \lam{a -> b}. The expression is the body of a lambda expression, so
521     it does not occur at a function position of an application. Finally, the
522     expression is not a lambda abstraction but a case expression, so all the
523     conditions match. There are no context conditions to match, so the
524     transformation applies.
525
526     By now, the placeholder \lam{E} is bound to the entire expression. The
527     placeholder \lam{x}, which occurs in the replacement template, is not bound
528     yet, so we need to generate a fresh binder for that. Let's use the binder
529     \lam{a}. This results in the following replacement expression:
530
531     \startlambda
532     λa.(case opcode of
533       Low -> (+)
534       High -> (-)) a
535     \stoplambda
536
537     Continuing with this expression, we see that the transformation does not
538     apply again (it is a lambda expression). Next we look at the body of this
539     lambda abstraction:
540
541     \startlambda
542     (case opcode of
543       Low -> (+)
544       High -> (-)) a
545     \stoplambda
546     
547     Here, the transformation does apply, binding \lam{E} to the entire
548     expression and \lam{x} to the fresh binder \lam{b}, resulting in the
549     replacement:
550
551     \startlambda
552     λb.(case opcode of
553       Low -> (+)
554       High -> (-)) a b
555     \stoplambda
556
557     Again, the transformation does not apply to this lambda abstraction, so we
558     look at its body. For brevity, we'll put the case statement on one line from
559     now on.
560
561     \startlambda
562     (case opcode of Low -> (+); High -> (-)) a b
563     \stoplambda
564
565     The type of this expression is \lam{Word}, so it does not match \lam{a -> b}
566     and the transformation does not apply. Next, we have two options for the
567     next expression to look at: The function position and argument position of
568     the application. The expression in the argument position is \lam{b}, which
569     has type \lam{Word}, so the transformation does not apply. The expression in
570     the function position is:
571
572     \startlambda
573     (case opcode of Low -> (+); High -> (-)) a
574     \stoplambda
575
576     Obviously, the transformation does not apply here, since it occurs in
577     function position (which makes the second condition false). In the same
578     way the transformation does not apply to both components of this
579     expression (\lam{case opcode of Low -> (+); High -> (-)} and \lam{a}), so
580     we'll skip to the components of the case expression: The scrutinee and
581     both alternatives. Since the opcode is not a function, it does not apply
582     here.
583
584     The first alternative is \lam{(+)}. This expression has a function type
585     (the operator still needs two arguments). It does not occur in function
586     position of an application and it is not a lambda expression, so the
587     transformation applies.
588
589     We look at the \lam{<original expression>} pattern, which is \lam{E}.
590     This means we bind \lam{E} to \lam{(+)}. We then replace the expression
591     with the \lam{<transformed expression>}, replacing all occurences of
592     \lam{E} with \lam{(+)}. In the \lam{<transformed expression>}, the This gives us the replacement expression:
593     \lam{λx.(+) x} (A lambda expression binding \lam{x}, with a body that
594     applies the addition operator to \lam{x}).
595
596     The complete function then becomes:
597     \startlambda
598     (case opcode of Low -> λa1.(+) a1; High -> (-)) a
599     \stoplambda
600
601     Now the transformation no longer applies to the complete first alternative
602     (since it is a lambda expression). It does not apply to the addition
603     operator again, since it is now in function position in an application. It
604     does, however, apply to the application of the addition operator, since
605     that is neither a lambda expression nor does it occur in function
606     position. This means after one more application of the transformation, the
607     function becomes:
608
609     \startlambda
610     (case opcode of Low -> λa1.λb1.(+) a1 b1; High -> (-)) a
611     \stoplambda
612
613     The other alternative is left as an exercise to the reader. The final
614     function, after applying η-abstraction until it does no longer apply is:
615
616     \startlambda 
617     alu :: Bit -> Word -> Word -> Word
618     alu = λopcode.λa.b. (case opcode of
619       Low -> λa1.λb1 (+) a1 b1
620       High -> λa2.λb2 (-) a2 b2) a b
621     \stoplambda
622
623     \subsection{Transformation application}
624       In this chapter we define a number of transformations, but how will we apply
625       these? As stated before, our normal form is reached as soon as no
626       transformation applies anymore. This means our application strategy is to
627       simply apply any transformation that applies, and continuing to do that with
628       the result of each transformation.
629
630       In particular, we define no particular order of transformations. Since
631       transformation order should not influence the resulting normal form,
632       \todo{This is not really true, but would like it to be...} this leaves
633       the implementation free to choose any application order that results in
634       an efficient implementation.
635
636       When applying a single transformation, we try to apply it to every (sub)expression
637       in a function, not just the top level function body. This allows us to
638       keep the transformation descriptions concise and powerful.
639
640     \subsection{Definitions}
641       In the following sections, we will be using a number of functions and
642       notations, which we will define here.
643
644       \todo{Define substitution (notation)}
645
646       \subsubsection{Concepts}
647         A \emph{global variable} is any variable (binder) that is bound at the
648         top level of a program, or an external module. A \emph{local variable} is any
649         other variable (\eg, variables local to a function, which can be bound by
650         lambda abstractions, let expressions and pattern matches of case
651         alternatives).  Note that this is a slightly different notion of global versus
652         local than what \small{GHC} uses internally.
653         \defref{global variable} \defref{local variable}
654
655         A \emph{hardware representable} (or just \emph{representable}) type or value
656         is (a value of) a type that we can generate a signal for in hardware. For
657         example, a bit, a vector of bits, a 32 bit unsigned word, etc. Values that are
658         not runtime representable notably include (but are not limited to): Types,
659         dictionaries, functions.
660         \defref{representable}
661
662         A \emph{builtin function} is a function supplied by the Cλash framework, whose
663         implementation is not valid Cλash. The implementation is of course valid
664         Haskell, for simulation, but it is not expressable in Cλash.
665         \defref{builtin function} \defref{user-defined function}
666
667       For these functions, Cλash has a \emph{builtin hardware translation}, so calls
668       to these functions can still be translated. These are functions like
669       \lam{map}, \lam{hwor} and \lam{length}.
670
671       A \emph{user-defined} function is a function for which we do have a Cλash
672       implementation available.
673
674       \subsubsection{Predicates}
675         Here, we define a number of predicates that can be used below to concisely
676         specify conditions.\refdef{global variable}
677
678         \emph{gvar(expr)} is true when \emph{expr} is a variable that references a
679         global variable. It is false when it references a local variable.
680
681         \refdef{local variable}\emph{lvar(expr)} is the complement of \emph{gvar}; it is true when \emph{expr}
682         references a local variable, false when it references a global variable.
683
684         \refdef{representable}\emph{representable(expr)} or \emph{representable(var)} is true when
685         \emph{expr} or \emph{var} is \emph{representable}.
686
687     \subsection[sec:normalization:uniq]{Binder uniqueness}
688       A common problem in transformation systems, is binder uniqueness. When not
689       considering this problem, it is easy to create transformations that mix up
690       bindings and cause name collisions. Take for example, the following core
691       expression:
692
693       \startlambda
694       (λa.λb.λc. a * b * c) x c
695       \stoplambda
696
697       By applying β-reduction (see \in{section}[sec:normalization:beta]) once,
698       we can simplify this expression to:
699
700       \startlambda
701       (λb.λc. x * b * c) c
702       \stoplambda
703
704       Now, we have replaced the \lam{a} binder with a reference to the \lam{x}
705       binder. No harm done here. But note that we see multiple occurences of the
706       \lam{c} binder. The first is a binding occurence, to which the second refers.
707       The last, however refers to \emph{another} instance of \lam{c}, which is
708       bound somewhere outside of this expression. Now, if we would apply beta
709       reduction without taking heed of binder uniqueness, we would get:
710
711       \startlambda
712       λc. x * c * c
713       \stoplambda
714
715       This is obviously not what was supposed to happen! The root of this problem is
716       the reuse of binders: Identical binders can be bound in different scopes, such
717       that only the inner one is \quote{visible} in the inner expression. In the example
718       above, the \lam{c} binder was bound outside of the expression and in the inner
719       lambda expression. Inside that lambda expression, only the inner \lam{c} is
720       visible.
721
722       There are a number of ways to solve this. \small{GHC} has isolated this
723       problem to their binder substitution code, which performs \emph{deshadowing}
724       during its expression traversal. This means that any binding that shadows
725       another binding on a higher level is replaced by a new binder that does not
726       shadow any other binding. This non-shadowing invariant is enough to prevent
727       binder uniqueness problems in \small{GHC}.
728
729       In our transformation system, maintaining this non-shadowing invariant is
730       a bit harder to do (mostly due to implementation issues, the prototype doesn't
731       use \small{GHC}'s subsitution code). Also, the following points can be
732       observed.
733
734       \startitemize
735       \item Deshadowing does not guarantee overall uniqueness. For example, the
736       following (slightly contrived) expression shows the identifier \lam{x} bound in
737       two seperate places (and to different values), even though no shadowing
738       occurs.
739
740       \startlambda
741       (let x = 1 in x) + (let x = 2 in x)
742       \stoplambda
743
744       \item In our normal form (and the resulting \small{VHDL}), all binders
745       (signals) within the same function (entity) will end up in the same
746       scope. To allow this, all binders within the same function should be
747       unique.
748
749       \item When we know that all binders in an expression are unique, moving around
750       or removing a subexpression will never cause any binder conflicts. If we have
751       some way to generate fresh binders, introducing new subexpressions will not
752       cause any problems either. The only way to cause conflicts is thus to
753       duplicate an existing subexpression.
754       \stopitemize
755
756       Given the above, our prototype maintains a unique binder invariant. This
757       means that in any given moment during normalization, all binders \emph{within
758       a single function} must be unique. To achieve this, we apply the following
759       technique.
760
761       \todo{Define fresh binders and unique supplies}
762
763       \startitemize
764       \item Before starting normalization, all binders in the function are made
765       unique. This is done by generating a fresh binder for every binder used. This
766       also replaces binders that did not cause any conflict, but it does ensure that
767       all binders within the function are generated by the same unique supply.
768       \refdef{fresh binder}
769       \item Whenever a new binder must be generated, we generate a fresh binder that
770       is guaranteed to be different from \emph{all binders generated so far}. This
771       can thus never introduce duplication and will maintain the invariant.
772       \item Whenever (a part of) an expression is duplicated (for example when
773       inlining), all binders in the expression are replaced with fresh binders
774       (using the same method as at the start of normalization). These fresh binders
775       can never introduce duplication, so this will maintain the invariant.
776       \item Whenever we move part of an expression around within the function, there
777       is no need to do anything special. There is obviously no way to introduce
778       duplication by moving expressions around. Since we know that each of the
779       binders is already unique, there is no way to introduce (incorrect) shadowing
780       either.
781       \stopitemize
782
783   \section{Transform passes}
784     In this section we describe the actual transforms.
785
786     Each transformation will be described informally first, explaining
787     the need for and goal of the transformation. Then, we will formally define
788     the transformation using the syntax introduced in
789     \in{section}[sec:normalization:transformation].
790
791     \subsection{General cleanup}
792       These transformations are general cleanup transformations, that aim to
793       make expressions simpler. These transformations usually clean up the
794        mess left behind by other transformations or clean up expressions to
795        expose new transformation opportunities for other transformations.
796
797        Most of these transformations are standard optimizations in other
798        compilers as well. However, in our compiler, most of these are not just
799        optimizations, but they are required to get our program into intended
800        normal form.
801
802       \subsubsection[sec:normalization:beta]{β-reduction}
803         β-reduction is a well known transformation from lambda calculus, where it is
804         the main reduction step. It reduces applications of lambda abstractions,
805         removing both the lambda abstraction and the application.
806
807         In our transformation system, this step helps to remove unwanted lambda
808         abstractions (basically all but the ones at the top level). Other
809         transformations (application propagation, non-representable inlining) make
810         sure that most lambda abstractions will eventually be reducable by
811         β-reduction.
812
813         \starttrans
814         (λx.E) M
815         -----------------
816         E[x=>M]
817         \stoptrans
818
819         % And an example
820         \startbuffer[from]
821         (λa. 2 * a) (2 * b)
822         \stopbuffer
823
824         \startbuffer[to]
825         2 * (2 * b)
826         \stopbuffer
827
828         \transexample{beta}{β-reduction}{from}{to}
829
830       \subsubsection{Empty let removal}
831         This transformation is simple: It removes recursive lets that have no bindings
832         (which usually occurs when unused let binding removal removes the last
833         binding from it).
834
835         Note that there is no need to define this transformation for
836         non-recursive lets, since they always contain exactly one binding.
837
838         \starttrans
839         letrec in M
840         --------------
841         M
842         \stoptrans
843
844         \todo{Example}
845
846       \subsubsection{Simple let binding removal}
847         This transformation inlines simple let bindings, that bind some
848         binder to some other binder instead of a more complex expression (\ie
849         a = b).
850
851         This transformation is not needed to get an expression into intended
852         normal form (since these bindings are part of the intended normal
853         form), but makes the resulting \small{VHDL} a lot shorter.
854         
855         \starttrans
856         letrec
857           a0 = E0
858           \vdots
859           ai = b
860           \vdots
861           an = En
862         in
863           M
864         -----------------------------  \lam{b} is a variable reference
865         letrec                         \lam{ai} ≠ \lam{b}
866           a0 = E0 [ai=>b]
867           \vdots
868           ai-1 = Ei-1 [ai=>b]
869           ai+1 = Ei+1 [ai=>b]
870           \vdots
871           an = En [ai=>b]
872         in
873           M[ai=>b]
874         \stoptrans
875
876         \todo{example}
877
878       \subsubsection{Unused let binding removal}
879         This transformation removes let bindings that are never used.
880         Occasionally, \GHC's desugarer introduces some unused let bindings.
881
882         This normalization pass should really be unneeded to get into intended normal form
883         (since unused bindings are not forbidden by the normal form), but in practice
884         the desugarer or simplifier emits some unused bindings that cannot be
885         normalized (e.g., calls to a \type{PatError}\todo{Check this name}). Also,
886         this transformation makes the resulting \small{VHDL} a lot shorter.
887
888         \todo{Don't use old-style numerals in transformations}
889         \starttrans
890         letrec
891           a0 = E0
892           \vdots
893           ai = Ei
894           \vdots
895           an = En
896         in
897           M                             \lam{ai} does not occur free in \lam{M}
898         ----------------------------    \forall j, 0 ≤ j ≤ n, j ≠ i (\lam{ai} does not occur free in \lam{Ej})
899         letrec
900           a0 = E0
901           \vdots
902           ai-1 = Ei-1
903           ai+1 = Ei+1
904           \vdots
905           an = En
906         in
907           M
908         \stoptrans
909
910         \todo{Example}
911
912       \subsubsection{Cast propagation / simplification}
913         This transform pushes casts down into the expression as far as possible.
914         Since its exact role and need is not clear yet, this transformation is
915         not yet specified.
916
917         \todo{Cast propagation}
918
919       \subsubsection{Top level binding inlining}
920         This transform takes simple top level bindings generated by the
921         \small{GHC} compiler. \small{GHC} sometimes generates very simple
922         \quote{wrapper} bindings, which are bound to just a variable
923         reference, or a partial application to constants or other variable
924         references.
925
926         Note that this transformation is completely optional. It is not
927         required to get any function into intended normal form, but it does help making
928         the resulting VHDL output easier to read (since it removes a bunch of
929         components that are really boring).
930
931         This transform takes any top level binding generated by the compiler,
932         whose normalized form contains only a single let binding.
933
934         \starttrans
935         x = λa0 ... λan.let y = E in y
936         ~
937         x
938         --------------------------------------         \lam{x} is generated by the compiler
939         λa0 ... λan.let y = E in y
940         \stoptrans
941
942         \startbuffer[from]
943         (+) :: Word -> Word -> Word
944         (+) = GHC.Num.(+) @Word $dNum
945         ~
946         (+) a b
947         \stopbuffer
948         \startbuffer[to]
949         GHC.Num.(+) @ Alu.Word $dNum a b
950         \stopbuffer
951
952         \transexample{toplevelinline}{Top level binding inlining}{from}{to}
953        
954         Example \in{ex:trans:toplevelinline} shows a typical application of
955         the addition operator generated by \GHC. The type and dictionary
956         arguments used here are described in
957         \in{section:prototype:polymorphism}.
958
959         Without this transformation, there would be a (+) entity in the
960         architecture which would just add its inputs. This generates a lot of
961         overhead in the VHDL, which is particularly annoying when browsing the
962         generated RTL schematic (especially since + is not allowed in VHDL
963         architecture names\footnote{Technically, it is allowed to use
964         non-alphanumerics when using extended identifiers, but it seems that
965         none of the tooling likes extended identifiers in filenames, so it
966         effectively doesn't work}, so the entity would be called
967         \quote{w7aA7f} or something similarly unreadable and autogenerated).
968
969     \subsection{Program structure}
970       These transformations are aimed at normalizing the overall structure
971       into the intended form. This means ensuring there is a lambda abstraction
972       at the top for every argument (input port or current state), putting all
973       of the other value definitions in let bindings and making the final
974       return value a simple variable reference.
975
976       \subsubsection{η-abstraction}
977         This transformation makes sure that all arguments of a function-typed
978         expression are named, by introducing lambda expressions. When combined with
979         β-reduction and non-representable binding inlining, all function-typed
980         expressions should be lambda abstractions or global identifiers.
981
982         \starttrans
983         E                 \lam{E :: a -> b}
984         --------------    \lam{E} is not the first argument of an application.
985         λx.E x            \lam{E} is not a lambda abstraction.
986                           \lam{x} is a variable that does not occur free in \lam{E}.
987         \stoptrans
988
989         \startbuffer[from]
990         foo = λa.case a of 
991           True -> λb.mul b b
992           False -> id
993         \stopbuffer
994
995         \startbuffer[to]
996         foo = λa.λx.(case a of 
997             True -> λb.mul b b
998             False -> λy.id y) x
999         \stopbuffer
1000
1001         \transexample{eta}{η-abstraction}{from}{to}
1002
1003       \subsubsection{Application propagation}
1004         This transformation is meant to propagate application expressions downwards
1005         into expressions as far as possible. This allows partial applications inside
1006         expressions to become fully applied and exposes new transformation
1007         opportunities for other transformations (like β-reduction and
1008         specialization).
1009
1010         Since all binders in our expression are unique (see
1011         \in{section}[sec:normalization:uniq]), there is no risk that we will
1012         introduce unintended shadowing by moving an expression into a lower
1013         scope. Also, since only move expression into smaller scopes (down into
1014         our expression), there is no risk of moving a variable reference out
1015         of the scope in which it is defined.
1016
1017         \starttrans
1018         (letrec binds in E) M
1019         ------------------------
1020         letrec binds in E M
1021         \stoptrans
1022
1023         % And an example
1024         \startbuffer[from]
1025         ( letrec
1026             val = 1
1027           in 
1028             add val
1029         ) 3
1030         \stopbuffer
1031
1032         \startbuffer[to]
1033         letrec
1034           val = 1
1035         in 
1036           add val 3
1037         \stopbuffer
1038
1039         \transexample{appproplet}{Application propagation for a let expression}{from}{to}
1040
1041         \starttrans
1042         (case x of
1043           p1 -> E1
1044           \vdots
1045           pn -> En) M
1046         -----------------
1047         case x of
1048           p1 -> E1 M
1049           \vdots
1050           pn -> En M
1051         \stoptrans
1052
1053         % And an example
1054         \startbuffer[from]
1055         ( case x of 
1056             True -> id
1057             False -> neg
1058         ) 1
1059         \stopbuffer
1060
1061         \startbuffer[to]
1062         case x of 
1063           True -> id 1
1064           False -> neg 1
1065         \stopbuffer
1066
1067         \transexample{apppropcase}{Application propagation for a case expression}{from}{to}
1068
1069       \subsubsection{Let recursification}
1070         This transformation makes all non-recursive lets recursive. In the
1071         end, we want a single recursive let in our normalized program, so all
1072         non-recursive lets can be converted. This also makes other
1073         transformations simpler: They can simply assume all lets are
1074         recursive.
1075
1076         \starttrans
1077         let
1078           a = E
1079         in
1080           M
1081         ------------------------------------------
1082         letrec
1083           a = E
1084         in
1085           M
1086         \stoptrans
1087
1088       \subsubsection{Let flattening}
1089         This transformation puts nested lets in the same scope, by lifting the
1090         binding(s) of the inner let into the outer let. Eventually, this will
1091         cause all let bindings to appear in the same scope.
1092
1093         This transformation only applies to recursive lets, since all
1094         non-recursive lets will be made recursive (see
1095         \in{section}[sec:normalization:letrecurse]).
1096
1097         Since we are joining two scopes together, there is no risk of moving a
1098         variable reference out of the scope where it is defined.
1099
1100         \starttrans
1101         letrec 
1102           a0 = E0
1103           \vdots
1104           ai = (letrec bindings in M)
1105           \vdots
1106           an = En
1107         in
1108           N
1109         ------------------------------------------
1110         letrec
1111           a0 = E0
1112           \vdots
1113           ai = M
1114           \vdots
1115           an = En
1116           bindings
1117         in
1118           N
1119         \stoptrans
1120
1121         \startbuffer[from]
1122         letrec
1123           a = 1
1124           b = letrec
1125             x = a
1126             y = c
1127           in
1128             x + y
1129           c = 2
1130         in
1131           b
1132         \stopbuffer
1133         \startbuffer[to]
1134         letrec
1135           a = 1
1136           b = x + y
1137           c = 2
1138           x = a
1139           y = c
1140         in
1141           b
1142         \stopbuffer
1143
1144         \transexample{letflat}{Let flattening}{from}{to}
1145
1146       \subsubsection{Return value simplification}
1147         This transformation ensures that the return value of a function is always a
1148         simple local variable reference.
1149
1150         Currently implemented using lambda simplification, let simplification, and
1151         top simplification. Should change into something like the following, which
1152         works only on the result of a function instead of any subexpression. This is
1153         achieved by the contexts, like \lam{x = E}, though this is strictly not
1154         correct (you could read this as "if there is any function \lam{x} that binds
1155         \lam{E}, any \lam{E} can be transformed, while we only mean the \lam{E} that
1156         is bound by \lam{x}. This might need some extra notes or something).
1157
1158         Note that the return value is not simplified if its not representable.
1159         Otherwise, this would cause a direct loop with the inlining of
1160         unrepresentable bindings. If the return value is not
1161         representable because it has a function type, η-abstraction should
1162         make sure that this transformation will eventually apply. If the value
1163         is not representable for other reasons, the function result itself is
1164         not representable, meaning this function is not translatable anyway.
1165
1166         \starttrans
1167         x = E                            \lam{E} is representable
1168         ~                                \lam{E} is not a lambda abstraction
1169         E                                \lam{E} is not a let expression
1170         ---------------------------      \lam{E} is not a local variable reference
1171         letrec x = E in x
1172         \stoptrans
1173
1174         \starttrans
1175         x = λv0 ... λvn.E
1176         ~                                \lam{E} is representable
1177         E                                \lam{E} is not a let expression
1178         ---------------------------      \lam{E} is not a local variable reference
1179         letrec x = E in x
1180         \stoptrans
1181
1182         \starttrans
1183         x = λv0 ... λvn.let ... in E
1184         ~                                \lam{E} is representable
1185         E                                \lam{E} is not a local variable reference
1186         -----------------------------
1187         letrec x = E in x
1188         \stoptrans
1189
1190         \startbuffer[from]
1191         x = add 1 2
1192         \stopbuffer
1193
1194         \startbuffer[to]
1195         x = letrec x = add 1 2 in x
1196         \stopbuffer
1197
1198         \transexample{retvalsimpl}{Return value simplification}{from}{to}
1199         
1200         \todo{More examples}
1201
1202     \subsection{Argument simplification}
1203       The transforms in this section deal with simplifying application
1204       arguments into normal form. The goal here is to:
1205
1206       \todo{This section should only talk about representable arguments. Non
1207       representable arguments are treated by specialization.}
1208
1209       \startitemize
1210        \item Make all arguments of user-defined functions (\eg, of which
1211        we have a function body) simple variable references of a runtime
1212        representable type. This is needed, since these applications will be turned
1213        into component instantiations.
1214        \item Make all arguments of builtin functions one of:
1215          \startitemize
1216           \item A type argument.
1217           \item A dictionary argument.
1218           \item A type level expression.
1219           \item A variable reference of a runtime representable type.
1220           \item A variable reference or partial application of a function type.
1221          \stopitemize
1222       \stopitemize
1223
1224       When looking at the arguments of a user-defined function, we can
1225       divide them into two categories:
1226       \startitemize
1227         \item Arguments of a runtime representable type (\eg bits or vectors).
1228
1229               These arguments can be preserved in the program, since they can
1230               be translated to input ports later on.  However, since we can
1231               only connect signals to input ports, these arguments must be
1232               reduced to simple variables (for which signals will be
1233               produced). This is taken care of by the argument extraction
1234               transform.
1235         \item Non-runtime representable typed arguments. \todo{Move this
1236         bullet to specialization}
1237               
1238               These arguments cannot be preserved in the program, since we
1239               cannot represent them as input or output ports in the resulting
1240               \small{VHDL}. To remove them, we create a specialized version of the
1241               called function with these arguments filled in. This is done by
1242               the argument propagation transform.
1243
1244               Typically, these arguments are type and dictionary arguments that are
1245               used to make functions polymorphic. By propagating these arguments, we
1246               are essentially doing the same which GHC does when it specializes
1247               functions: Creating multiple variants of the same function, one for
1248               each type for which it is used. Other common non-representable
1249               arguments are functions, e.g. when calling a higher order function
1250               with another function or a lambda abstraction as an argument.
1251
1252               The reason for doing this is similar to the reasoning provided for
1253               the inlining of non-representable let bindings above. In fact, this
1254               argument propagation could be viewed as a form of cross-function
1255               inlining.
1256       \stopitemize
1257
1258       \todo{Move this itemization into a new section about builtin functions}
1259       When looking at the arguments of a builtin function, we can divide them
1260       into categories: 
1261
1262       \startitemize
1263         \item Arguments of a runtime representable type.
1264               
1265               As we have seen with user-defined functions, these arguments can
1266               always be reduced to a simple variable reference, by the
1267               argument extraction transform. Performing this transform for
1268               builtin functions as well, means that the translation of builtin
1269               functions can be limited to signal references, instead of
1270               needing to support all possible expressions.
1271
1272         \item Arguments of a function type.
1273               
1274               These arguments are functions passed to higher order builtins,
1275               like \lam{map} and \lam{foldl}. Since implementing these
1276               functions for arbitrary function-typed expressions (\eg, lambda
1277               expressions) is rather comlex, we reduce these arguments to
1278               (partial applications of) global functions.
1279               
1280               We can still support arbitrary expressions from the user code,
1281               by creating a new global function containing that expression.
1282               This way, we can simply replace the argument with a reference to
1283               that new function. However, since the expression can contain any
1284               number of free variables we also have to include partial
1285               applications in our normal form.
1286
1287               This category of arguments is handled by the function extraction
1288               transform.
1289         \item Other unrepresentable arguments.
1290               
1291               These arguments can take a few different forms:
1292               \startdesc{Type arguments}
1293                 In the core language, type arguments can only take a single
1294                 form: A type wrapped in the Type constructor. Also, there is
1295                 nothing that can be done with type expressions, except for
1296                 applying functions to them, so we can simply leave type
1297                 arguments as they are.
1298               \stopdesc
1299               \startdesc{Dictionary arguments}
1300                 In the core language, dictionary arguments are used to find
1301                 operations operating on one of the type arguments (mostly for
1302                 finding class methods). Since we will not actually evaluatie
1303                 the function body for builtin functions and can generate
1304                 code for builtin functions by just looking at the type
1305                 arguments, these arguments can be ignored and left as they
1306                 are.
1307               \stopdesc
1308               \startdesc{Type level arguments}
1309                 Sometimes, we want to pass a value to a builtin function, but
1310                 we need to know the value at compile time. Additionally, the
1311                 value has an impact on the type of the function. This is
1312                 encoded using type-level values, where the actual value of the
1313                 argument is not important, but the type encodes some integer,
1314                 for example. Since the value is not important, the actual form
1315                 of the expression does not matter either and we can leave
1316                 these arguments as they are.
1317               \stopdesc
1318               \startdesc{Other arguments}
1319                 Technically, there is still a wide array of arguments that can
1320                 be passed, but does not fall into any of the above categories.
1321                 However, none of the supported builtin functions requires such
1322                 an argument. This leaves use with passing unsupported types to
1323                 a function, such as calling \lam{head} on a list of functions.
1324
1325                 In these cases, it would be impossible to generate hardware
1326                 for such a function call anyway, so we can ignore these
1327                 arguments.
1328
1329                 The only way to generate hardware for builtin functions with
1330                 arguments like these, is to expand the function call into an
1331                 equivalent core expression (\eg, expand map into a series of
1332                 function applications). But for now, we choose to simply not
1333                 support expressions like these.
1334               \stopdesc
1335
1336               From the above, we can conclude that we can simply ignore these
1337               other unrepresentable arguments and focus on the first two
1338               categories instead.
1339       \stopitemize
1340
1341       \subsubsection{Argument simplification}
1342         This transform deals with arguments to functions that
1343         are of a runtime representable type. It ensures that they will all become
1344         references to global variables, or local signals in the resulting
1345         \small{VHDL}, which is required due to limitations in the component
1346         instantiation code in \VHDL (one can only assign a signal or constant
1347         to an input port). By ensuring that all arguments are always simple
1348         variable references, we always have a signal available to assign to
1349         input ports.
1350
1351         \todo{Say something about dataconstructors (without arguments, like True
1352         or False), which are variable references of a runtime representable
1353         type, but do not result in a signal.}
1354
1355         To reduce a complex expression to a simple variable reference, we create
1356         a new let expression around the application, which binds the complex
1357         expression to a new variable. The original function is then applied to
1358         this variable.
1359
1360         Note that a reference to a \emph{global variable} (like a top level
1361         function without arguments, but also an argumentless dataconstructors
1362         like \lam{True}) is also simplified. Only local variables generate
1363         signals in the resulting architecture. 
1364
1365         \refdef{representable}
1366         \starttrans
1367         M N
1368         --------------------    \lam{N} is representable
1369         letrec x = N in M x     \lam{N} is not a local variable reference
1370         \stoptrans
1371         \refdef{local variable}
1372
1373         \startbuffer[from]
1374         add (add a 1) 1
1375         \stopbuffer
1376
1377         \startbuffer[to]
1378         letrec x = add a 1 in add x 1
1379         \stopbuffer
1380
1381         \transexample{argextract}{Argument extraction}{from}{to}
1382       
1383       \subsubsection{Function extraction}
1384         \todo{Move to section about builtin functions}
1385         This transform deals with function-typed arguments to builtin
1386         functions.  Since builtin functions cannot be specialized to remove
1387         the arguments, we choose to extract these arguments into a new global
1388         function instead. This greatly simplifies the translation rules needed
1389         for builtin functions. \todo{Should we talk about these? Reference
1390         Christiaan?}
1391
1392         Any free variables occuring in the extracted arguments will become
1393         parameters to the new global function. The original argument is replaced
1394         with a reference to the new function, applied to any free variables from
1395         the original argument.
1396
1397         This transformation is useful when applying higher order builtin functions
1398         like \hs{map} to a lambda abstraction, for example. In this case, the code
1399         that generates \small{VHDL} for \hs{map} only needs to handle top level functions and
1400         partial applications, not any other expression (such as lambda abstractions or
1401         even more complicated expressions).
1402
1403         \starttrans
1404         M N                     \lam{M} is (a partial aplication of) a builtin function.
1405         ---------------------   \lam{f0 ... fn} are all free local variables of \lam{N}
1406         M (x f0 ... fn)         \lam{N :: a -> b}
1407         ~                       \lam{N} is not a (partial application of) a top level function
1408         x = λf0 ... λfn.N
1409         \stoptrans
1410
1411         \todo{Split this example}
1412         \startbuffer[from]
1413         map (λa . add a b) xs
1414
1415         map (add b) ys
1416         \stopbuffer
1417
1418         \startbuffer[to]
1419         map (x0 b) xs
1420
1421         map x1 ys
1422         ~
1423         x0 = λb.λa.add a b
1424         x1 = λb.add b
1425         \stopbuffer
1426
1427         \transexample{funextract}{Function extraction}{from}{to}
1428
1429         Note that \lam{x0} and {x1} will still need normalization after this.
1430
1431       \subsubsection{Argument propagation}
1432         \todo{Rename this section to specialization and move it into a
1433         separate section}
1434
1435         This transform deals with arguments to user-defined functions that are
1436         not representable at runtime. This means these arguments cannot be
1437         preserved in the final form and most be {\em propagated}.
1438
1439         Propagation means to create a specialized version of the called
1440         function, with the propagated argument already filled in. As a simple
1441         example, in the following program:
1442
1443         \startlambda
1444         f = λa.λb.a + b
1445         inc = λa.f a 1
1446         \stoplambda
1447
1448         We could {\em propagate} the constant argument 1, with the following
1449         result:
1450
1451         \startlambda
1452         f' = λa.a + 1
1453         inc = λa.f' a
1454         \stoplambda
1455
1456         Special care must be taken when the to-be-propagated expression has any
1457         free variables. If this is the case, the original argument should not be
1458         removed completely, but replaced by all the free variables of the
1459         expression. In this way, the original expression can still be evaluated
1460         inside the new function. Also, this brings us closer to our goal: All
1461         these free variables will be simple variable references.
1462
1463         To prevent us from propagating the same argument over and over, a simple
1464         local variable reference is not propagated (since is has exactly one
1465         free variable, itself, we would only replace that argument with itself).
1466
1467         This shows that any free local variables that are not runtime representable
1468         cannot be brought into normal form by this transform. We rely on an
1469         inlining transformation to replace such a variable with an expression we
1470         can propagate again.
1471
1472         \starttrans
1473         x = E
1474         ~
1475         x Y0 ... Yi ... Yn                               \lam{Yi} is not of a runtime representable type
1476         ---------------------------------------------    \lam{Yi} is not a local variable reference
1477         x' y0 ... yi-1 f0 ...  fm Yi+1 ... Yn            \lam{f0 ... fm} are all free local vars of \lam{Yi}
1478         ~
1479         x' = λy0 ... λyi-1. λf0 ... λfm. λyi+1 ... λyn .       
1480               E y0 ... yi-1 Yi yi+1 ... yn   
1481         \stoptrans
1482
1483         \todo{Describe what the formal specification means}
1484         \todo{Note that we don't change the sepcialised function body, only
1485         wrap it}
1486
1487         \todo{Example}
1488
1489
1490     \subsection{Case normalisation}
1491       \subsubsection{Scrutinee simplification}
1492         This transform ensures that the scrutinee of a case expression is always
1493         a simple variable reference.
1494
1495         \starttrans
1496         case E of
1497           alts
1498         -----------------        \lam{E} is not a local variable reference
1499         letrec x = E in 
1500           case E of
1501             alts
1502         \stoptrans
1503
1504         \startbuffer[from]
1505         case (foo a) of
1506           True -> a
1507           False -> b
1508         \stopbuffer
1509
1510         \startbuffer[to]
1511         letrec x = foo a in
1512           case x of
1513             True -> a
1514             False -> b
1515         \stopbuffer
1516
1517         \transexample{letflat}{Let flattening}{from}{to}
1518
1519
1520       \subsubsection{Case simplification}
1521         This transformation ensures that all case expressions become normal form. This
1522         means they will become one of:
1523         \startitemize
1524         \item An extractor case with a single alternative that picks a single field
1525         from a datatype, \eg \lam{case x of (a, b) -> a}.
1526         \item A selector case with multiple alternatives and only wild binders, that
1527         makes a choice between expressions based on the constructor of another
1528         expression, \eg \lam{case x of Low -> a; High -> b}.
1529         \stopitemize
1530         
1531         \defref{wild binder}
1532         \starttrans
1533         case E of
1534           C0 v0,0 ... v0,m -> E0
1535           \vdots
1536           Cn vn,0 ... vn,m -> En
1537         --------------------------------------------------- \forall i \forall j, 0 ≤ i ≤ n, 0 ≤ i < m (\lam{wi,j} is a wild (unused) binder)
1538         letrec
1539           v0,0 = case E of C0 v0,0 .. v0,m -> v0,0
1540           \vdots
1541           v0,m = case E of C0 v0,0 .. v0,m -> v0,m
1542           \vdots
1543           vn,m = case E of Cn vn,0 .. vn,m -> vn,m
1544           x0 = E0
1545           \vdots
1546           xn = En
1547         in
1548           case E of
1549             C0 w0,0 ... w0,m -> x0
1550             \vdots
1551             Cn wn,0 ... wn,m -> xn
1552         \stoptrans
1553         \todo{Check the subscripts of this transformation}
1554
1555         Note that this transformation applies to case statements with any
1556         scrutinee. If the scrutinee is a complex expression, this might result
1557         in duplicate hardware. An extra condition to only apply this
1558         transformation when the scrutinee is already simple (effectively
1559         causing this transformation to be only applied after the scrutinee
1560         simplification transformation) might be in order. 
1561
1562         \fxnote{This transformation specified like this is complicated and misses
1563         conditions to prevent looping with itself. Perhaps it should be split here for
1564         discussion?}
1565
1566         \startbuffer[from]
1567         case a of
1568           True -> add b 1
1569           False -> add b 2
1570         \stopbuffer
1571
1572         \startbuffer[to]
1573         letnonrec
1574           x0 = add b 1
1575           x1 = add b 2
1576         in
1577           case a of
1578             True -> x0
1579             False -> x1
1580         \stopbuffer
1581
1582         \transexample{selcasesimpl}{Selector case simplification}{from}{to}
1583
1584         \startbuffer[from]
1585         case a of
1586           (,) b c -> add b c
1587         \stopbuffer
1588         \startbuffer[to]
1589         letrec
1590           b = case a of (,) b c -> b
1591           c = case a of (,) b c -> c
1592           x0 = add b c
1593         in
1594           case a of
1595             (,) w0 w1 -> x0
1596         \stopbuffer
1597
1598         \transexample{excasesimpl}{Extractor case simplification}{from}{to}
1599
1600         \refdef{selector case}
1601         In \in{example}[ex:trans:excasesimpl] the case expression is expanded
1602         into multiple case expressions, including a pretty useless expression
1603         (that is neither a selector or extractor case). This case can be
1604         removed by the Case removal transformation in
1605         \in{section}[sec:transformation:caseremoval].
1606
1607       \subsubsection[sec:transformation:caseremoval]{Case removal}
1608         This transform removes any case statements with a single alternative and
1609         only wild binders.
1610
1611         These "useless" case statements are usually leftovers from case simplification
1612         on extractor case (see the previous example).
1613
1614         \starttrans
1615         case x of
1616           C v0 ... vm -> E
1617         ----------------------     \lam{\forall i, 0 ≤ i ≤ m} (\lam{vi} does not occur free in E)
1618         E
1619         \stoptrans
1620
1621         \startbuffer[from]
1622         case a of
1623           (,) w0 w1 -> x0
1624         \stopbuffer
1625
1626         \startbuffer[to]
1627         x0
1628         \stopbuffer
1629
1630         \transexample{caserem}{Case removal}{from}{to}
1631
1632   \todo{Move these two sections somewhere? Perhaps not?}
1633   \subsection{Removing polymorphism}
1634     Reference type-specialization (== argument propagation)
1635
1636     Reference polymporphic binding inlining (== non-representable binding
1637     inlining).
1638
1639   \subsection{Defunctionalization}
1640     These transformations remove most higher order expressions from our
1641     program, making it completely first-order (the only exception here is for
1642     arguments to builtin functions, since we can't specialize builtin
1643     function. \todo{Talk more about this somewhere}
1644
1645     Reference higher-order-specialization (== argument propagation)
1646
1647       \subsubsection{Non-representable binding inlining}
1648         \todo{Move this section into a new section (together with
1649         specialization?)}
1650         This transform inlines let bindings that are bound to a
1651         non-representable value. Since we can never generate a signal
1652         assignment for these bindings (we cannot declare a signal assignment
1653         with a non-representable type, for obvious reasons), we have no choice
1654         but to inline the binding to remove it.
1655
1656         If the binding is non-representable because it is a lambda abstraction, it is
1657         likely that it will inlined into an application and β-reduction will remove
1658         the lambda abstraction and turn it into a representable expression at the
1659         inline site. The same holds for partial applications, which can be turned into
1660         full applications by inlining.
1661
1662         Other cases of non-representable bindings we see in practice are primitive
1663         Haskell types. In most cases, these will not result in a valid normalized
1664         output, but then the input would have been invalid to start with. There is one
1665         exception to this: When a builtin function is applied to a non-representable
1666         expression, things might work out in some cases. For example, when you write a
1667         literal \hs{SizedInt} in Haskell, like \hs{1 :: SizedInt D8}, this results in
1668         the following core: \lam{fromInteger (smallInteger 10)}, where for example
1669         \lam{10 :: GHC.Prim.Int\#} and \lam{smallInteger 10 :: Integer} have
1670         non-representable types. \todo{Expand on this. This/these paragraph(s)
1671         should probably become a separate discussion somewhere else}
1672
1673         \todo{Can this duplicate work?}
1674
1675         \starttrans
1676         letrec 
1677           a0 = E0
1678           \vdots
1679           ai = Ei
1680           \vdots
1681           an = En
1682         in
1683           M
1684         --------------------------    \lam{Ei} has a non-representable type.
1685         letrec
1686           a0 = E0 [ai=>Ei] \vdots
1687           ai-1 = Ei-1 [ai=>Ei]
1688           ai+1 = Ei+1 [ai=>Ei]
1689           \vdots
1690           an = En [ai=>Ei]
1691         in
1692           M[ai=>Ei]
1693         \stoptrans
1694
1695         \startbuffer[from]
1696         letrec
1697           a = smallInteger 10
1698           inc = λb -> add b 1
1699           inc' = add 1
1700           x = fromInteger a 
1701         in
1702           inc (inc' x)
1703         \stopbuffer
1704
1705         \startbuffer[to]
1706         letrec
1707           x = fromInteger (smallInteger 10)
1708         in
1709           (λb -> add b 1) (add 1 x)
1710         \stopbuffer
1711
1712         \transexample{nonrepinline}{Nonrepresentable binding inlining}{from}{to}
1713
1714
1715   \section{Provable properties}
1716     When looking at the system of transformations outlined above, there are a
1717     number of questions that we can ask ourselves. The main question is of course:
1718     \quote{Does our system work as intended?}. We can split this question into a
1719     number of subquestions:
1720
1721     \startitemize[KR]
1722     \item[q:termination] Does our system \emph{terminate}? Since our system will
1723     keep running as long as transformations apply, there is an obvious risk that
1724     it will keep running indefinitely. This typically happens when one
1725     transformation produces a result that is transformed back to the original
1726     by another transformation, or when one or more transformations keep
1727     expanding some expression.
1728     \item[q:soundness] Is our system \emph{sound}? Since our transformations
1729     continuously modify the expression, there is an obvious risk that the final
1730     normal form will not be equivalent to the original program: Its meaning could
1731     have changed.
1732     \item[q:completeness] Is our system \emph{complete}? Since we have a complex
1733     system of transformations, there is an obvious risk that some expressions will
1734     not end up in our intended normal form, because we forgot some transformation.
1735     In other words: Does our transformation system result in our intended normal
1736     form for all possible inputs?
1737     \item[q:determinism] Is our system \emph{deterministic}? Since we have defined
1738     no particular order in which the transformation should be applied, there is an
1739     obvious risk that different transformation orderings will result in
1740     \emph{different} normal forms. They might still both be intended normal forms
1741     (if our system is \emph{complete}) and describe correct hardware (if our
1742     system is \emph{sound}), so this property is less important than the previous
1743     three: The translator would still function properly without it.
1744     \stopitemize
1745
1746     \subsection{Graph representation}
1747       Before looking into how to prove these properties, we'll look at our
1748       transformation system from a graph perspective. The nodes of the graph are
1749       all possible Core expressions. The (directed) edges of the graph are
1750       transformations. When a transformation α applies to an expression \lam{A} to
1751       produce an expression \lam{B}, we add an edge from the node for \lam{A} to the
1752       node for \lam{B}, labeled α.
1753
1754       \startuseMPgraphic{TransformGraph}
1755         save a, b, c, d;
1756
1757         % Nodes
1758         newCircle.a(btex \lam{(λx.λy. (+) x y) 1} etex);
1759         newCircle.b(btex \lam{λy. (+) 1 y} etex);
1760         newCircle.c(btex \lam{(λx.(+) x) 1} etex);
1761         newCircle.d(btex \lam{(+) 1} etex);
1762
1763         b.c = origin;
1764         c.c = b.c + (4cm, 0cm);
1765         a.c = midpoint(b.c, c.c) + (0cm, 4cm);
1766         d.c = midpoint(b.c, c.c) - (0cm, 3cm);
1767
1768         % β-conversion between a and b
1769         ncarc.a(a)(b) "name(bred)";
1770         ObjLabel.a(btex $\xrightarrow[normal]{}{β}$ etex) "labpathname(bred)", "labdir(rt)";
1771         ncarc.b(b)(a) "name(bexp)", "linestyle(dashed withdots)";
1772         ObjLabel.b(btex $\xleftarrow[normal]{}{β}$ etex) "labpathname(bexp)", "labdir(lft)";
1773
1774         % η-conversion between a and c
1775         ncarc.a(a)(c) "name(ered)";
1776         ObjLabel.a(btex $\xrightarrow[normal]{}{η}$ etex) "labpathname(ered)", "labdir(rt)";
1777         ncarc.c(c)(a) "name(eexp)", "linestyle(dashed withdots)";
1778         ObjLabel.c(btex $\xleftarrow[normal]{}{η}$ etex) "labpathname(eexp)", "labdir(lft)";
1779
1780         % η-conversion between b and d
1781         ncarc.b(b)(d) "name(ered)";
1782         ObjLabel.b(btex $\xrightarrow[normal]{}{η}$ etex) "labpathname(ered)", "labdir(rt)";
1783         ncarc.d(d)(b) "name(eexp)", "linestyle(dashed withdots)";
1784         ObjLabel.d(btex $\xleftarrow[normal]{}{η}$ etex) "labpathname(eexp)", "labdir(lft)";
1785
1786         % β-conversion between c and d
1787         ncarc.c(c)(d) "name(bred)";
1788         ObjLabel.c(btex $\xrightarrow[normal]{}{β}$ etex) "labpathname(bred)", "labdir(rt)";
1789         ncarc.d(d)(c) "name(bexp)", "linestyle(dashed withdots)";
1790         ObjLabel.d(btex $\xleftarrow[normal]{}{β}$ etex) "labpathname(bexp)", "labdir(lft)";
1791
1792         % Draw objects and lines
1793         drawObj(a, b, c, d);
1794       \stopuseMPgraphic
1795
1796       \placeexample[right][ex:TransformGraph]{Partial graph of a lambda calculus
1797       system with β and η reduction (solid lines) and expansion (dotted lines).}
1798           \boxedgraphic{TransformGraph}
1799
1800       Of course our graph is unbounded, since we can construct an infinite amount of
1801       Core expressions. Also, there might potentially be multiple edges between two
1802       given nodes (with different labels), though seems unlikely to actually happen
1803       in our system.
1804
1805       See \in{example}[ex:TransformGraph] for the graph representation of a very
1806       simple lambda calculus that contains just the expressions \lam{(λx.λy. (+) x
1807       y) 1}, \lam{λy. (+) 1 y}, \lam{(λx.(+) x) 1} and \lam{(+) 1}. The
1808       transformation system consists of β-reduction and η-reduction (solid edges) or
1809       β-expansion and η-expansion (dotted edges).
1810
1811       \todo{Define β-reduction and η-reduction?}
1812
1813       Note that the normal form of such a system consists of the set of nodes
1814       (expressions) without outgoing edges, since those are the expression to which
1815       no transformation applies anymore. We call this set of nodes the \emph{normal
1816       set}.
1817
1818       From such a graph, we can derive some properties easily:
1819       \startitemize[KR]
1820         \item A system will \emph{terminate} if there is no path of infinite length
1821         in the graph (this includes cycles, but can also happen without cycles).
1822         \item Soundness is not easily represented in the graph.
1823         \item A system is \emph{complete} if all of the nodes in the normal set have
1824         the intended normal form. The inverse (that all of the nodes outside of
1825         the normal set are \emph{not} in the intended normal form) is not
1826         strictly required.
1827         \item A system is deterministic if all paths starting at a particular
1828         node, which end in a node in the normal set, end at the same node.
1829       \stopitemize
1830
1831       When looking at the \in{example}[ex:TransformGraph], we see that the system
1832       terminates for both the reduction and expansion systems (but note that, for
1833       expansion, this is only true because we've limited the possible
1834       expressions.  In comlete lambda calculus, there would be a path from
1835       \lam{(λx.λy. (+) x y) 1} to \lam{(λx.λy.(λz.(+) z) x y) 1} to
1836       \lam{(λx.λy.(λz.(λq.(+) q) z) x y) 1} etc.)
1837
1838       If we would consider the system with both expansion and reduction, there
1839       would no longer be termination either, since there would be cycles all
1840       over the place.
1841
1842       The reduction and expansion systems have a normal set of containing just
1843       \lam{(+) 1} or \lam{(λx.λy. (+) x y) 1} respectively. Since all paths in
1844       either system end up in these normal forms, both systems are \emph{complete}.
1845       Also, since there is only one node in the normal set, it must obviously be
1846       \emph{deterministic} as well.
1847
1848     \todo{Add content to these sections}
1849     \subsection{Termination}
1850       Approach: Counting.
1851
1852       Church-Rosser?
1853
1854     \subsection{Soundness}
1855       Needs formal definition of semantics.
1856       Prove for each transformation seperately, implies soundness of the system.
1857      
1858     \subsection{Completeness}
1859       Show that any transformation applies to every Core expression that is not
1860       in normal form. To prove: no transformation applies => in intended form.
1861       Show the reverse: Not in intended form => transformation applies.
1862
1863     \subsection{Determinism}
1864       How to prove this?