2a7a077d269bb8d1a1bd6fedd62c67fff888eaba
[matthijs/master-project/report.git] / Chapters / HardwareDescription.tex
1 \chapter[chap:description]{Hardware description}
2   In this chapter an overview will be provided of the hardware
3   description language that was created and the issues that have arisen
4   in the process. The focus will be on the issues of the language, not
5   the implementation. The prototype implementation will be discussed in
6   \in{chapter}[chap:prototype].
7
8   To translate Haskell to hardware, every Haskell construct needs a
9   translation to \VHDL. There are often multiple valid translations
10   possible. When faced with choices, the most obvious choice has been
11   chosen wherever possible. In a lot of cases, when a programmer looks
12   at a functional hardware description it is completely clear what
13   hardware is described. We want our translator to generate exactly that
14   hardware whenever possible, to make working with Cλash as intuitive as
15   possible.
16    
17   \placeintermezzo{}{
18     \defref{reading examples}
19     \startframedtext[width=9cm,background=box,frame=no]
20     \startalignment[center]
21       {\tfa Reading the examples}
22     \stopalignment
23     \blank[medium]
24       In this thesis, a lot of functional code will be presented. Part of this
25       will be valid Cλash code, but others will just be small Haskell or Core
26       snippets to illustrate a concept.
27
28       In these examples, some functions and types will be used, without
29       properly defining every one of them. These functions (like \hs{and},
30       \hs{not}, \hs{add}, \hs{+}, etc.) and types (like \hs{Bit}, \hs{Word},
31       \hs{Bool}, etc.) are usually pretty self-explanatory.
32
33       The special type \hs{[t]} means \quote{list of \hs{t}'s}, where \hs{t}
34       can be any other type.
35
36       Of particular note is the use of the \hs{::} operator. It is used in
37       Haskell to explicitly declare the type of function or let binding. In
38       these examples and the text, we will occasionally use this operator to
39       show the type of arbitrary expressions, even where this would not
40       normally be valid. Just reading the \hs{::} operator as \quote{and also
41       note that \emph{this} expression has \emph{this} type} should work out.
42     \stopframedtext
43   }
44
45   In this chapter we describe how to interpret a Haskell program from a
46   hardware perspective. We provide a description of each Haskell language
47   element that needs translation, to provide a clear picture of what is
48   supported and how.
49
50
51   \section[sec:description:application]{Function application}
52   The basic syntactic elements of a functional program are functions and
53   function application. These have a single obvious \small{VHDL}
54   translation: each top level function becomes a hardware component, where each
55   argument is an input port and the result value is the (single) output
56   port. This output port can have a complex type (such as a tuple), so
57   having just a single output port does not pose a limitation.
58
59   Each function application in turn becomes component instantiation. Here, the
60   result of each argument expression is assigned to a signal, which is mapped
61   to the corresponding input port. The output port of the function is also
62   mapped to a signal, which is used as the result of the application.
63
64   Since every top level function generates its own component, the
65   hierarchy of of function calls is reflected in the final \VHDL\ output
66   as well, creating a hierarchical \VHDL\ description of the hardware.
67   This separation in different components makes the resulting \VHDL\
68   output easier to read and debug.
69
70   \in{Example}[ex:And3] shows a simple program using only function
71   application and the corresponding architecture.
72
73 \startbuffer[And3]
74 -- A simple function that returns 
75 -- conjunction of three bits
76 and3 :: Bit -> Bit -> Bit -> Bit
77 and3 a b c = and (and a b) c
78 \stopbuffer
79
80   \startuseMPgraphic{And3}
81     save a, b, c, anda, andb, out;
82
83     % I/O ports
84     newCircle.a(btex $a$ etex) "framed(false)";
85     newCircle.b(btex $b$ etex) "framed(false)";
86     newCircle.c(btex $c$ etex) "framed(false)";
87     newCircle.out(btex $out$ etex) "framed(false)";
88
89     % Components
90     newCircle.anda(btex $and$ etex);
91     newCircle.andb(btex $and$ etex);
92
93     a.c    = origin;
94     b.c    = a.c + (0cm, 1cm);
95     c.c    = b.c + (0cm, 1cm);
96     anda.c = midpoint(a.c, b.c) + (2cm, 0cm);
97     andb.c = midpoint(b.c, c.c) + (4cm, 0cm);
98
99     out.c   = andb.c + (2cm, 0cm);
100
101     % Draw objects and lines
102     drawObj(a, b, c, anda, andb, out);
103
104     ncarc(a)(anda) "arcangle(-10)";
105     ncarc(b)(anda);
106     ncarc(anda)(andb);
107     ncarc(c)(andb);
108     ncline(andb)(out);
109   \stopuseMPgraphic
110
111   \placeexample[][ex:And3]{Simple three input and gate.}
112     \startcombination[2*1]
113       {\typebufferhs{And3}}{Haskell description using function applications.}
114       {\boxedgraphic{And3}}{The architecture described by the Haskell description.}
115     \stopcombination
116
117   \placeintermezzo{}{
118     \defref{top level binder}
119     \defref{top level function}
120     \startframedtext[width=8cm,background=box,frame=no]
121     \startalignment[center]
122       {\tfa Top level binders and functions}
123     \stopalignment
124     \blank[medium]
125       A top level binder is any binder (variable) that is declared in
126       the \quote{global} scope of a Haskell program (as opposed to a
127       binder that is bound inside a function.
128
129       In Haskell, there is no sharp distinction between a variable and a
130       function: a function is just a variable (binder) with a function
131       type. This means that a top level function is just any top level
132       binder with a function type.
133
134       As an example, consider the following Haskell snippet:
135
136       \starthaskell
137         foo :: Int -> Int
138         foo x = inc x
139           where
140             inc = \y -> y + 1
141       \stophaskell
142
143       Here, \hs{foo} is a top level binder, whereas \hs{inc} is a
144       function (since it is bound to a lambda extraction, indicated by
145       the backslash) but is not a top level binder or function.  Since
146       the type of \hs{foo} is a function type, namely \hs{Int -> Int},
147       it is also a top level function.
148     \stopframedtext
149   }
150   \section{Choice}
151     Although describing components and connections allows us to describe a lot of
152     hardware designs already, there is an obvious thing missing: choice. We
153     need some way to be able to choose between values based on another value.
154     In Haskell, choice is achieved by \hs{case} expressions, \hs{if}
155     expressions, pattern matching and guards.
156
157     An obvious way to add choice to our language without having to recognize
158     any of Haskell's syntax, would be to add a primivite \quote{\hs{if}}
159     function. This function would take three arguments: the condition, the
160     value to return when the condition is true and the value to return when
161     the condition is false.
162
163     This \hs{if} function would then essentially describe a multiplexer and
164     allows us to describe any architecture that uses multiplexers.
165
166     However, to be able to describe our hardware in a more convenient way, we
167     also want to translate Haskell's choice mechanisms. The easiest of these
168     are of course case expressions (and \hs{if} expressions, which can be very
169     directly translated to \hs{case} expressions). A \hs{case} expression can in turn
170     simply be translated to a conditional assignment, where the conditions use
171     equality comparisons against the constructors in the \hs{case} expressions.
172
173     In \in{example}[ex:CaseInv] a simple \hs{case} expression is shown,
174     scrutinizing a boolean value. The corresponding architecture has a
175     comparator to determine which of the constructors is on the \hs{in}
176     input. There is a multiplexer to select the output signal. The two options
177     for the output signals are just constants, but these could have been more
178     complex expressions (in which case also both of them would be working in
179     parallel, regardless of which output would be chosen eventually).
180
181     If we would translate a Boolean to a bit value, we could of course remove
182     the comparator and directly feed 'in' into the multiplexer (or even use an
183     inverter instead of a multiplexer).  However, we will try to make a
184     general translation, which works for all possible \hs{case} expressions.
185     Optimizations such as these are left for the \VHDL\ synthesizer, which
186     handles them very well.
187
188     \placeintermezzo{}{
189       \startframedtext[width=8cm,background=box,frame=no]
190       \startalignment[center]
191         {\tfa Arguments / results vs. inputs / outputs}
192       \stopalignment
193       \blank[medium]
194         Due to the translation chosen for function application, there is a
195         very strong relation between arguments, results, inputs and outputs.
196         For clarity, the former two will always refer to the arguments and
197         results in the functional description (either Haskell or Core). The
198         latter two will refer to input and output ports in the generated
199         \VHDL.
200
201         Even though these concepts seem to be nearly identical, when stateful
202         functions are introduces we will see arguments and results that will
203         not get translated into input and output ports, making this
204         distinction more important.
205       \stopframedtext
206     }
207
208     A slightly more complex (but very powerful) form of choice is pattern
209     matching. A function can be defined in multiple clauses, where each clause
210     specifies a pattern. When the arguments match the pattern, the
211     corresponding clause will be used.
212
213     The architecture described by \in{example}[ex:PatternInv] is of course the
214     same one as the one in \in{example}[ex:CaseInv]. The general interpretation
215     of pattern matching is also similar to that of \hs{case} expressions: generate
216     hardware for each of the clauses (like each of the clauses of a \hs{case}
217     expression) and connect them to the function output through (a number of
218     nested) multiplexers. These multiplexers are driven by comparators and
219     other logic, that check each pattern in turn.
220
221     In these examples we have seen only binary case expressions and pattern
222     matches (\ie, with two alternatives). In practice, case expressions can
223     choose between more than two values, resulting in a number of nested
224     multiplexers.
225
226     \startbuffer[CaseInv]
227     inv :: Bool -> Bool
228     inv x = case x of
229       True -> False
230       False -> True
231     \stopbuffer
232
233     \startuseMPgraphic{CaseInv}
234       save in, truecmp, falseout, trueout, out, cmp, mux;
235
236       % I/O ports
237       newCircle.in(btex $in$ etex) "framed(false)";
238       newCircle.out(btex $out$ etex) "framed(false)";
239       % Constants
240       newBox.truecmp(btex $True$ etex) "framed(false)";
241       newBox.trueout(btex $True$ etex) "framed(false)";
242       newBox.falseout(btex $False$ etex) "framed(false)";
243
244       % Components
245       newCircle.cmp(btex $==$ etex);
246       newMux.mux;
247
248       in.c       = origin;
249       cmp.c      = in.c + (3cm, 0cm);
250       truecmp.c  = cmp.c + (-1cm, 1cm);
251       mux.sel    = cmp.e + (1cm, -1cm);
252       falseout.c = mux.inpa - (2cm, 0cm);
253       trueout.c  = mux.inpb - (2cm, 0cm);
254       out.c      = mux.out + (2cm, 0cm);
255
256       % Draw objects and lines
257       drawObj(in, out, truecmp, trueout, falseout, cmp, mux);
258
259       ncline(in)(cmp);
260       ncarc(truecmp)(cmp);
261       nccurve(cmp.e)(mux.sel) "angleA(0)", "angleB(-90)";
262       ncline(falseout)(mux) "posB(inpa)";
263       ncline(trueout)(mux) "posB(inpb)";
264       ncline(mux)(out) "posA(out)";
265     \stopuseMPgraphic
266
267     \placeexample[][ex:CaseInv]{Simple inverter.}
268       \startcombination[2*1]
269         {\typebufferhs{CaseInv}}{Haskell description using a Case expression.}
270         {\boxedgraphic{CaseInv}}{The architecture described by the Haskell description.}
271       \stopcombination
272
273     \startbuffer[PatternInv]
274     inv :: Bool -> Bool
275     inv True = False
276     inv False = True
277     \stopbuffer
278
279     \placeexample[][ex:PatternInv]{Simple inverter using pattern matching.
280     Describes the same architecture as \in{example}[ex:CaseInv].}
281         {\typebufferhs{PatternInv}}
282
283   \section{Types}
284     Translation of two most basic functional concepts has been
285     discussed: function application and choice. Before looking further
286     into less obvious concepts like higher-order expressions and
287     polymorphism, the possible types that can be used in hardware
288     descriptions will be discussed.
289
290     Some way is needed to translate every values used to its hardware
291     equivalents. In particular, this means a hardware equivalent for
292     every \emph{type} used in a hardware description is needed
293
294     Since most functional languages have a lot of standard types that
295     are hard to translate (integers without a fixed size, lists without
296     a static length, etc.), a number of \quote{built-in} types will be
297     defined first. These types are built-in in the sense that our
298     compiler will have a fixed VHDL type for these. User defined types,
299     on the other hand, will have their hardware type derived directly
300     from their Haskell declaration automatically, according to the rules
301     sketched here.
302
303     \todo{Introduce Haskell type syntax (type constructors, type application,
304     :: operator?)}
305
306     \subsection{Built-in types}
307       The language currently supports the following built-in types. Of these,
308       only the \hs{Bool} type is supported by Haskell out of the box (the
309       others are defined by the Cλash package, so they are user-defined types
310       from Haskell's point of view).
311
312       \startdesc{\hs{Bit}}
313         This is the most basic type available. It is mapped directly onto
314         the \type{std_logic} \small{VHDL} type. Mapping this to the
315         \type{bit} type might make more sense (since the Haskell version
316         only has two values), but using \type{std_logic} is more standard
317         (and allowed for some experimentation with don't care values)
318
319         \todo{Sidenote bit vs stdlogic}
320       \stopdesc
321       \startdesc{\hs{Bool}}
322         This is the only built-in Haskell type supported and is translated
323         exactly like the Bit type (where a value of \hs{True} corresponds to a
324         value of \hs{High}). Supporting the Bool type is particularly
325         useful to support \hs{if ... then ... else ...} expressions, which
326         always have a \hs{Bool} value for the condition.
327
328         A \hs{Bool} is translated to a \type{std_logic}, just like \hs{Bit}.
329       \stopdesc
330       \startdesc{\hs{SizedWord}, \hs{SizedInt}}
331         These are types to represent integers. A \hs{SizedWord} is unsigned,
332         while a \hs{SizedInt} is signed. These types are parameterized by a
333         length type, so you can define an unsigned word of 32 bits wide as
334         follows:
335         
336         \starthaskell
337           type Word32 = SizedWord D32
338         \stophaskell
339
340         Here, a type synonym \hs{Word32} is defined that is equal to the
341         \hs{SizedWord} type constructor applied to the type \hs{D32}. \hs{D32}
342         is the \emph{type level representation} of the decimal number 32,
343         making the \hs{Word32} type a 32-bit unsigned word.
344
345         These types are translated to the \small{VHDL} \type{unsigned} and
346         \type{signed} respectively.
347         \todo{Sidenote on dependent typing?}
348       \stopdesc
349       \startdesc{\hs{Vector}}
350         This is a vector type, that can contain elements of any other type and
351         has a fixed length. It has two type parameters: its
352         length and the type of the elements contained in it. By putting the
353         length parameter in the type, the length of a vector can be determined
354         at compile time, instead of only at runtime for conventional lists.
355
356         The \hs{Vector} type constructor takes two type arguments: the length
357         of the vector and the type of the elements contained in it. The state
358         type of an 8 element register bank would then for example be:
359
360         \starthaskell
361         type RegisterState = Vector D8 Word32
362         \stophaskell
363
364         Here, a type synonym \hs{RegisterState} is defined that is equal to
365         the \hs{Vector} type constructor applied to the types \hs{D8} (The type
366         level representation of the decimal number 8) and \hs{Word32} (The 32
367         bit word type as defined above). In other words, the
368         \hs{RegisterState} type is a vector of 8 32-bit words.
369
370         A fixed size vector is translated to a \small{VHDL} array type.
371       \stopdesc
372       \startdesc{\hs{RangedWord}}
373         This is another type to describe integers, but unlike the previous
374         two it has no specific bitwidth, but an upper bound. This means that
375         its range is not limited to powers of two, but can be any number.
376         A \hs{RangedWord} only has an upper bound, its lower bound is
377         implicitly zero. There is a lot of added implementation complexity
378         when adding a lower bound and having just an upper bound was enough
379         for the primary purpose of this type: typesafely indexing vectors.
380
381         To define an index for the 8 element vector above, we would do:
382
383         \starthaskell
384         type RegisterIndex = RangedWord D7
385         \stophaskell
386
387         Here, a type synonym \hs{RegisterIndex} is defined that is equal to
388         the \hs{RangedWord} type constructor applied to the type \hs{D7}. In
389         other words, this defines an unsigned word with values from
390         {\definedfont[Serif*normalnum]0 to 7} (inclusive). This word can be be used to index the
391         8 element vector \hs{RegisterState} above.
392
393         This type is translated to the \type{unsigned} \small{VHDL} type.
394       \stopdesc
395
396       The integer and vector built-in types are discussed in more detail
397       in \cite[baaij09].
398
399     \subsection{User-defined types}
400       There are three ways to define new types in Haskell: algebraic
401       datatypes with the \hs{data} keyword, type synonyms with the \hs{type}
402       keyword and type renamings with the \hs{newtype} keyword. \GHC\
403       offers a few more advanced ways to introduce types (type families,
404       existential typing, \small{GADT}s, etc.) which are not standard
405       Haskell.  These will be left outside the scope of this research.
406
407       Only an algebraic datatype declaration actually introduces a
408       completely new type, for which we provide the \VHDL\ translation
409       below. Type synonyms and renamings only define new names for
410       existing types (where synonyms are completely interchangeable and
411       renamings need explicit conversion). Therefore, these do not need
412       any particular \VHDL\ translation, a synonym or renamed type will
413       just use the same representation as the original type. The
414       distinction between a renaming and a synonym does no longer matter
415       in hardware and can be disregarded in the generated \VHDL.
416
417       For algebraic types, we can make the following distinction:
418
419       \startdesc{Product types}
420         A product type is an algebraic datatype with a single constructor with
421         two or more fields, denoted in practice like (a,b), (a,b,c), etc. This
422         is essentially a way to pack a few values together in a record-like
423         structure. In fact, the built-in tuple types are just algebraic product
424         types (and are thus supported in exactly the same way).
425
426         The \quote{product} in its name refers to the collection of values belonging
427         to this type. The collection for a product type is the Cartesian
428         product of the collections for the types of its fields.
429
430         These types are translated to \VHDL\ record types, with one field for
431         every field in the constructor. This translation applies to all single
432         constructor algebraic datatypes, including those with just one
433         field (which are technically not a product, but generate a VHDL
434         record for implementation simplicity).
435       \stopdesc
436       \startdesc{Enumerated types}
437         \defref{enumerated types}
438         An enumerated type is an algebraic datatype with multiple constructors, but
439         none of them have fields. This is essentially a way to get an
440         enum-like type containing alternatives.
441
442         Note that Haskell's \hs{Bool} type is also defined as an
443         enumeration type, but we have a fixed translation for that.
444         
445         These types are translated to \VHDL\ enumerations, with one value for
446         each constructor. This allows references to these constructors to be
447         translated to the corresponding enumeration value.
448       \stopdesc
449       \startdesc{Sum types}
450         A sum type is an algebraic datatype with multiple constructors, where
451         the constructors have one or more fields. Technically, a type with
452         more than one field per constructor is a sum of products type, but
453         for our purposes this distinction does not really make a
454         difference, so this distinction is note made.
455
456         The \quote{sum} in its name refers again to the collection of values
457         belonging to this type. The collection for a sum type is the
458         union of the the collections for each of the constructors.
459
460         Sum types are currently not supported by the prototype, since there is
461         no obvious \VHDL\ alternative. They can easily be emulated, however, as
462         we will see from an example:
463
464         \starthaskell
465         data Sum = A Bit Word | B Word 
466         \stophaskell
467
468         An obvious way to translate this would be to create an enumeration to
469         distinguish the constructors and then create a big record that
470         contains all the fields of all the constructors. This is the same
471         translation that would result from the following enumeration and
472         product type (using a tuple for clarity):
473
474         \starthaskell
475         data SumC = A | B
476         type Sum = (SumC, Bit, Word, Word)
477         \stophaskell
478
479         Here, the \hs{SumC} type effectively signals which of the latter three
480         fields of the \hs{Sum} type are valid (the first two if \hs{A}, the
481         last one if \hs{B}), all the other ones have no useful value.
482
483         An obvious problem with this naive approach is the space usage: the
484         example above generates a fairly big \VHDL\ type. Since we can be
485         sure that the two \hs{Word}s in the \hs{Sum} type will never be valid
486         at the same time, this is a waste of space.
487
488         Obviously, duplication detection could be used to reuse a
489         particular field for another constructor, but this would only
490         partially solve the problem. If two fields would be, for
491         example, an array of 8 bits and an 8 bit unsiged word, these are
492         different types and could not be shared. However, in the final
493         hardware, both of these types would simply be 8 bit connections,
494         so we have a 100\% size increase by not sharing these.
495       \stopdesc
496
497       Another interesting case is that of recursive types. In Haskell, an
498       algebraic datatype can be recursive: any of its field types can be (or
499       contain) the type being defined. The most well-known recursive type is
500       probably the list type, which is defined is:
501       
502       \starthaskell
503       data List t = Empty | Cons t (List t)
504       \stophaskell
505
506       Note that \hs{Empty} is usually written as \hs{[]} and \hs{Cons} as
507       \hs{:}, but this would make the definition harder to read.  This
508       immediately shows the problem with recursive types: what hardware type
509       to allocate here? 
510       
511       If the naive approach for sum types described above would be used,
512       a record would be created where the first field is an enumeration
513       to distinguish \hs{Empty} from \hs{Cons}. Furthermore, two more
514       fields would be added: one with the (\VHDL\ equivalent of) type
515       \hs{t} (assuming this type is actually known at compile time, this
516       should not be a problem) and a second one with type \hs{List t}.
517       The latter one is of course a problem: this is exactly the type
518       that was to be translated in the first place.
519       
520       The resulting \VHDL\ type will thus become infinitely deep. In
521       other words, there is no way to statically determine how long
522       (deep) the list will be (it could even be infinite).
523       
524       In general, recursive types can never be properly translated: all
525       recursive types have a potentially infinite value (even though in
526       practice they will have a bounded value, there is no way for the
527       compiler to automatically determine an upper bound on its size).
528
529   \subsection{Partial application}
530   Now the translation of application, choice and types has been
531   discussed, a more complex concept can be considered: partial
532   applications. A \emph{partial application} is any application whose
533   (return) type is (again) a function type.
534
535   From this, it should be clear that the translation rules for full
536   application does not apply to a partial application: there are not
537   enough values for all the input ports in the resulting \VHDL.
538   \in{Example}[ex:Quadruple] shows an example use of partial application
539   and the corresponding architecture.
540
541 \startbuffer[Quadruple]
542 -- Multiply the input word by four.
543 quadruple :: Word -> Word
544 quadruple n = mul (mul n)
545   where
546     mul = (*) 2
547 \stopbuffer
548
549   \startuseMPgraphic{Quadruple}
550     save in, two, mula, mulb, out;
551
552     % I/O ports
553     newCircle.in(btex $n$ etex) "framed(false)";
554     newCircle.two(btex $2$ etex) "framed(false)";
555     newCircle.out(btex $out$ etex) "framed(false)";
556
557     % Components
558     newCircle.mula(btex $\times$ etex);
559     newCircle.mulb(btex $\times$ etex);
560
561     two.c    = origin;
562     in.c     = two.c + (0cm, 1cm);
563     mula.c  = in.c + (2cm, 0cm);
564     mulb.c  = mula.c + (2cm, 0cm);
565     out.c   = mulb.c + (2cm, 0cm);
566
567     % Draw objects and lines
568     drawObj(in, two, mula, mulb, out);
569
570     nccurve(two)(mula) "angleA(0)", "angleB(45)";
571     nccurve(two)(mulb) "angleA(0)", "angleB(45)";
572     ncline(in)(mula);
573     ncline(mula)(mulb);
574     ncline(mulb)(out);
575   \stopuseMPgraphic
576
577   \placeexample[][ex:Quadruple]{Simple three port and.}
578     \startcombination[2*1]
579       {\typebufferhs{Quadruple}}{Haskell description using function applications.}
580       {\boxedgraphic{Quadruple}}{The architecture described by the Haskell description.}
581     \stopcombination
582
583   Here, the definition of mul is a partial function application: it applies
584   the function \hs{(*) :: Word -> Word -> Word} to the value \hs{2 :: Word},
585   resulting in the expression \hs{(*) 2 :: Word -> Word}. Since this resulting
586   expression is again a function, hardware cannot be generated for it
587   directly.  This is because the hardware to generate for \hs{mul}
588   depends completely on where and how it is used. In this example, it is
589   even used twice.
590
591   However, it is clear that the above hardware description actually
592   describes valid hardware. In general, any partial applied function
593   must eventually become completely applied, at which point hardware for
594   it can be generated using the rules for function application given in
595   \in{section}[sec:description:application]. It might mean that a
596   partial application is passed around quite a bit (even beyond function
597   boundaries), but eventually, the partial application will become
598   completely applied. An example of this principe is given in
599   \in{section}[sec:normalization:defunctionalization].
600
601   \section{Costless specialization}
602     Each (complete) function application in our description generates a
603     component instantiation, or a specific piece of hardware in the final
604     design. It is interesting to note that each application of a function
605     generates a \emph{separate} piece of hardware. In the final design, none
606     of the hardware is shared between applications, even when the applied
607     function is the same (of course, if a particular value, such as the result
608     of a function application, is used twice, it is not calculated twice).
609
610     This is distinctly different from normal program compilation: two separate
611     calls to the same function share the same machine code. Having more
612     machine code has implications for speed (due to less efficient caching)
613     and memory usage. For normal compilation, it is therefore important to
614     keep the amount of functions limited and maximize the code sharing
615     (though there is a tradeoff between speed and memory usage here).
616
617     When generating hardware, this is hardly an issue. Having more \quote{code
618     sharing} does reduce the amount of \small{VHDL} output (Since different
619     component instantiations still share the same component), but after
620     synthesis, the amount of hardware generated is not affected. This
621     means there is no tradeoff between speed and memory (or rather,
622     chip area) usage.
623
624     In particular, if we would duplicate all functions so that there is a
625     separate function for every application in the program (\eg, each function
626     is then only applied exactly once), there would be no increase in hardware
627     size whatsoever.
628     
629     Because of this, a common optimization technique called
630     \emph{specialization} can be applied to hardware generation without any
631     performance or area cost (unlike for software). 
632    
633    \fxnote{Perhaps these next three sections are a bit too
634    implementation-oriented?}
635
636     \subsection{Specialization}
637       \defref{specialization}
638       Given some function that has a \emph{domain} $D$ (\eg, the set of
639       all possible arguments that the function could be applied to), we
640       create a specialized function with exactly the same behaviour, but
641       with a domain $D' \subset D$. This subset can be chosen in all
642       sorts of ways. Any subset is valid for the general definition of
643       specialization, but in practice only some of them provide useful
644       optimization opportunities.
645
646       Common subsets include limiting a polymorphic argument to a single type
647       (\ie, removing polymorphism) or limiting an argument to just a single
648       value (\ie, cross-function constant propagation, effectively removing
649       the argument). 
650       
651       Since we limit the argument domain of the specialized function, its
652       definition can often be optimized further (since now more types or even
653       values of arguments are already known). By replacing any application of
654       the function that falls within the reduced domain by an application of
655       the specialized version, the code gets faster (but the code also gets
656       bigger, since we now have two versions instead of one). If we apply
657       this technique often enough, we can often replace all applications of a
658       function by specialized versions, allowing the original function to be
659       removed (in some cases, this can even give a net reduction of the code
660       compared to the non-specialized version).
661
662       Specialization is useful for our hardware descriptions for functions
663       that contain arguments that cannot be translated to hardware directly
664       (polymorphic or higher-order arguments, for example). If we can create
665       specialized functions that remove the argument, or make it translatable,
666       we can use specialization to make the original, untranslatable, function
667       obsolete.
668
669   \section{Higher order values}
670     What holds for partial application, can be easily generalized to any
671     higher-order expression. This includes partial applications, plain
672     variables (e.g., a binder referring to a top level function), lambda
673     expressions and more complex expressions with a function type (a \hs{case}
674     expression returning lambda's, for example).
675
676     Each of these values cannot be directly represented in hardware (just like
677     partial applications). Also, to make them representable, they need to be
678     applied: function variables and partial applications will then eventually
679     become complete applications, applied lambda expressions disappear by
680     applying β-reduction, etc.
681
682     So any higher-order value will be \quote{pushed down} towards its
683     application just like partial applications. Whenever a function boundary
684     needs to be crossed, the called function can be specialized.
685     
686     \fxnote{This section needs improvement and an example}
687
688   \section{Polymorphism}
689     In Haskell, values can be \emph{polymorphic}: they can have multiple types. For
690     example, the function \hs{fst :: (a, b) -> a} is an example of a
691     polymorphic function: it works for tuples with any two element types. Haskell
692     type classes allow a function to work on a specific set of types, but the
693     general idea is the same. The opposite of this is a \emph{monomorphic}
694     value, which has a single, fixed, type.
695
696 %    A type class is a collection of types for which some operations are
697 %    defined. It is thus possible for a value to be polymorphic while having
698 %    any number of \emph{class constraints}: the value is not defined for
699 %    every type, but only for types in the type class. An example of this is
700 %    the \hs{even :: (Integral a) => a -> Bool} function, which can map any
701 %    value of a type that is member of the \hs{Integral} type class 
702
703     When generating hardware, polymorphism cannot be easily translated. How
704     many wires will you lay down for a value that could have any type? When
705     type classes are involved, what hardware components will you lay down for
706     a class method (whose behaviour depends on the type of its arguments)?
707     Note that Cλash currently does not allow user-defined type classes,
708     but does partly support some of the built-in type classes (like \hs{Num}).
709
710     Fortunately, we can again use the principle of specialization: since every
711     function application generates a separate piece of hardware, we can know
712     the types of all arguments exactly. Provided that existential typing
713     (which is a \GHC\ extension) is not used typing, all of the
714     polymorphic types in a function must depend on the types of the
715     arguments (In other words, the only way to introduce a type variable
716     is in a lambda abstraction).
717
718     If a function is monomorphic, all values inside it are monomorphic as
719     well, so any function that is applied within the function can only be
720     applied to monomorphic values. The applied functions can then be
721     specialized to work just for these specific types, removing the
722     polymorphism from the applied functions as well.
723
724     \defref{entry function}The entry function must not have a
725     polymorphic type (otherwise no hardware interface could be generated
726     for the entry function).
727
728     By induction, this means that all functions that are (indirectly) called
729     by our top level function (meaning all functions that are translated in
730     the final hardware) become monomorphic.
731
732   \section{State}
733     A very important concept in hardware designs is \emph{state}. In a
734     stateless (or, \emph{combinational}) design, every output is  directly and solely dependent on the
735     inputs. In a stateful design, the outputs can depend on the history of
736     inputs, or the \emph{state}. State is usually stored in \emph{registers},
737     which retain their value during a clockcycle, and are typically updated at
738     the start of every clockcycle. Since the updating of the state is tightly
739     coupled (synchronized) to the clock signal, these state updates are often
740     called \emph{synchronous} behaviour.
741
742     \todo{Sidenote? Registers can contain any (complex) type}
743   
744     To make Cλash useful to describe more than simple combinational
745     designs, it needs to be able to describe state in some way.
746
747     \subsection{Approaches to state}
748       In Haskell, functions are always pure (except when using unsafe
749       functions with the \hs{IO} monad, which is not supported by Cλash). This
750       means that the output of a function solely depends on its inputs. If you
751       evaluate a given function with given inputs, it will always provide the
752       same output.
753
754       \placeintermezzo{}{
755         \defref{purity}
756         \startframedtext[width=8cm,background=box,frame=no]
757         \startalignment[center]
758           {\tfa Purity}
759         \stopalignment
760         \blank[medium]
761
762         A function is said to be pure if it satisfies two conditions:
763
764         \startitemize[KR]
765         \item When a pure function is called with the same arguments twice, it should
766         return the same value in both cases.
767         \item When a pure function is called, it should have not
768         observable side-effects.
769         \stopitemize
770
771         Purity is an important property in functional languages, since
772         it enables all kinds of mathematical reasoning and
773         optimizattions with pure functions, that are not guaranteed to
774         be correct for impure functions.
775
776         An example of a pure function is the square root function
777         \hs{sqrt}. An example of an impure function is the \hs{today}
778         function that returns the current date (which of course cannot
779         exist like this in Haskell).
780         \stopframedtext
781       }
782
783       This is a perfect match for a combinational circuit, where the output
784       also solely depends on the inputs. However, when state is involved, this
785       no longer holds. Of course this purity constraint cannot just be
786       removed from Haskell. But even when designing a completely new (hardware
787       description) language, it does not seem to be a good idea to
788       remove this purity. This would that all kinds of interesting properties of
789       the functional language get lost, and all kinds of transformations
790       and optimizations are no longer be meaning preserving.
791
792       So our functions must remain pure, meaning the current state has
793       to be present in the function's arguments in some way. There seem
794       to be two obvious ways to do this: adding the current state as an
795       argument, or including the full history of each argument.
796
797       \subsubsection{Stream arguments and results}
798         Including the entire history of each input (\eg, the value of that
799         input for each previous clockcycle) is an obvious way to make outputs
800         depend on all previous input. This is easily done by making every
801         input a list instead of a single value, containing all previous values
802         as well as the current value.
803
804         An obvious downside of this solution is that on each cycle, all the
805         previous cycles must be resimulated to obtain the current state. To do
806         this, it might be needed to have a recursive helper function as well,
807         which might be hard to be properly analyzed by the compiler.
808
809         A slight variation on this approach is one taken by some of the other
810         functional \small{HDL}s in the field: \todo{References to Lava,
811         ForSyDe, ...} Make functions operate on complete streams. This means
812         that a function is no longer called on every cycle, but just once. It
813         takes stream as inputs instead of values, where each stream contains
814         all the values for every clockcycle since system start. This is easily
815         modeled using an (infinite) list, with one element for each clock
816         cycle. Since the function is only evaluated once, its output must also
817         be a stream. Note that, since we are working with infinite lists and
818         still want to be able to simulate the system cycle-by-cycle, this
819         relies heavily on the lazy semantics of Haskell.
820
821         Since our inputs and outputs are streams, all other (intermediate)
822         values must be streams. All of our primitive operators (\eg, addition,
823         substraction, bitwise operations, etc.) must operate on streams as
824         well (note that changing a single-element operation to a stream
825         operation can done with \hs{map}, \hs{zipwith}, etc.).
826
827         This also means that primitive operations from an existing
828         language such as Haskell cannot be used directly (including some
829         syntax constructs, like \hs{case} expressions and \hs{if}
830         expressions).  This mkes this approach well suited for use in
831         \small{EDSL}s, since those already impose these same
832         limitations. \refdef{EDSL}
833
834         Note that the concept of \emph{state} is no more than having some way
835         to communicate a value from one cycle to the next. By introducing a
836         \hs{delay} function, we can do exactly that: delay (each value in) a
837         stream so that we can "look into" the past. This \hs{delay} function
838         simply outputs a stream where each value is the same as the input
839         value, but shifted one cycle. This causes a \quote{gap} at the
840         beginning of the stream: what is the value of the delay output in the
841         first cycle? For this, the \hs{delay} function has a second input, of
842         which only a single value is used.
843
844         \in{Example}[ex:DelayAcc] shows a simple accumulator expressed in this
845         style.
846
847 \startbuffer[DelayAcc]
848 acc :: Stream Word -> Stream Word
849 acc in = out
850   where
851     out = (delay out 0) + in
852 \stopbuffer
853
854 \startuseMPgraphic{DelayAcc}
855   save in, out, add, reg;
856
857   % I/O ports
858   newCircle.in(btex $in$ etex) "framed(false)";
859   newCircle.out(btex $out$ etex) "framed(false)";
860
861   % Components
862   newReg.reg("") "dx(4mm)", "dy(6mm)", "reflect(true)";
863   newCircle.add(btex + etex);
864   
865   in.c    = origin;
866   add.c   = in.c + (2cm, 0cm);
867   out.c   = add.c + (2cm, 0cm);
868   reg.c   = add.c + (0cm, 2cm);
869
870   % Draw objects and lines
871   drawObj(in, out, add, reg);
872
873   nccurve(add)(reg) "angleA(0)", "angleB(180)", "posB(d)";
874   nccurve(reg)(add) "angleA(180)", "angleB(-45)", "posA(out)";
875   ncline(in)(add);
876   ncline(add)(out);
877 \stopuseMPgraphic
878
879
880         \placeexample[][ex:DelayAcc]{Simple accumulator architecture.}
881           \startcombination[2*1]
882             {\typebufferhs{DelayAcc}}{Haskell description using streams.}
883             {\boxedgraphic{DelayAcc}}{The architecture described by the Haskell description.}
884           \stopcombination
885
886
887         This notation can be confusing (especially due to the loop in the
888         definition of out), but is essentially easy to interpret. There is a
889         single call to delay, resulting in a circuit with a single register,
890         whose input is connected to \hs{out} (which is the output of the
891         adder), and its output is the expression \hs{delay out 0} (which is
892         connected to one of the adder inputs).
893
894       \subsubsection{Explicit state arguments and results}
895         A more explicit way to model state, is to simply add an extra argument
896         containing the current state value. This allows an output to depend on
897         both the inputs as well as the current state while keeping the
898         function pure (letting the result depend only on the arguments), since
899         the current state is now an argument.
900
901         In Haskell, this would look like
902         \in{example}[ex:ExplicitAcc]\footnote[notfinalsyntax]{This
903         example is not in the final Cλash syntax}. \todo{Referencing
904         notfinalsyntax from Introduction.tex doesn't work}
905
906 \startbuffer[ExplicitAcc]
907 -- input -> current state -> (new state, output)
908 acc :: Word -> Word -> (Word, Word)
909 acc in s = (s', out)
910   where
911     out = s + in
912     s'  = out
913 \stopbuffer
914
915         \placeexample[][ex:ExplicitAcc]{Simple accumulator architecture.}
916           \startcombination[2*1]
917             {\typebufferhs{ExplicitAcc}}{Haskell description using explicit state arguments.}
918             % Picture is identical to the one we had just now.
919             {\boxedgraphic{DelayAcc}}{The architecture described by the Haskell description.}
920           \stopcombination
921
922         This approach makes a function's state very explicit, which state
923         variables are used by a function can be completely determined from its
924         type signature (as opposed to the stream approach, where a function
925         looks the same from the outside, regardless of what state variables it
926         uses or whether it is stateful at all).
927         
928         This approach to state has been one of the initial drives behind
929         this research. Unlike a stream based approach it is well suited
930         to completely use existing code and language features (like
931         \hs{if} and \hs{case} expressions) because it operates on normal
932         values. Because of these reasons, this is the approach chosen
933         for Cλash. It will be examined more closely below.
934
935     \subsection{Explicit state specification}
936       The concept of explicit state has been introduced with some
937       examples above, but what are the implications of this approach?
938
939       \subsubsection{Substates}
940         Since a function's state is reflected directly in its type signature,
941         if a function calls other stateful functions (\eg, has subcircuits), it
942         has to somehow know the current state for these called functions. The
943         only way to do this, is to put these \emph{substates} inside the
944         caller's state. This means that a function's state is the sum of the
945         states of all functions it calls, and its own state. This sum
946         can be obtained using something simple like a tuple, or possibly
947         custom algebraic types for clarity.
948
949         This also means that the type of a function (at least the "state"
950         part) is dependent on its own implementation and of the functions it
951         calls.
952
953         This is the major downside of this approach: the separation between
954         interface and implementation is limited. However, since Cλash is not
955         very suitable for separate compilation (see
956         \in{section}[sec:prototype:separate]) this is not a big problem in
957         practice.
958
959         Additionally, when using a type synonym for the state type
960         of each function, we can still provide explicit type signatures
961         while keeping the state specification for a function near its
962         definition only.
963         \todo{Example}
964     
965       \subsubsection{Which arguments and results are stateful?}
966         \fxnote{This section should get some examples}
967         We need some way to know which arguments should become input ports and
968         which argument(s?) should become the current state (\eg, be bound to
969         the register outputs). This does not hold just for the top
970         level function, but also for any subfunction. Or could we perhaps
971         deduce the statefulness of subfunctions by analyzing the flow of data
972         in the calling functions?
973
974         To explore this matter, the following observeration is interesting: we
975         get completely correct behaviour when we put all state registers in
976         the top level entity (or even outside of it). All of the state
977         arguments and results on subfunctions are treated as normal input and
978         output ports. Effectively, a stateful function results in a stateless
979         hardware component that has one of its input ports connected to the
980         output of a register and one of its output ports connected to the
981         input of the same register.
982
983         \todo{Example}
984
985         Of course, even though the hardware described like this has the
986         correct behaviour, unless the layout tool does smart optimizations,
987         there will be a lot of extra wire in the design (since registers will
988         not be close to the component that uses them). Also, when working with
989         the generated \small{VHDL} code, there will be a lot of extra ports
990         just to pass on state values, which can get quite confusing.
991
992         To fix this, we can simply \quote{push} the registers down into the
993         subcircuits. When we see a register that is connected directly to a
994         subcircuit, we remove the corresponding input and output port and put
995         the register inside the subcircuit instead. This is slightly less
996         trivial when looking at the Haskell code instead of the resulting
997         circuit, but the idea is still the same.
998
999         \todo{Example}
1000
1001         However, when applying this technique, we might push registers down
1002         too far. When you intend to store a result of a stateless subfunction
1003         in the caller's state and pass the current value of that state
1004         variable to that same function, the register might get pushed down too
1005         far. It is impossible to distinguish this case from similar code where
1006         the called function is in fact stateful. From this we can conclude
1007         that we have to either:
1008
1009         \todo{Example of wrong downpushing}
1010
1011         \startitemize
1012         \item accept that the generated hardware might not be exactly what we
1013         intended, in some specific cases. In most cases, the hardware will be
1014         what we intended.
1015         \item explicitly annotate state arguments and results in the input
1016         description.
1017         \stopitemize
1018
1019         The first option causes (non-obvious) exceptions in the language
1020         intepretation. Also, automatically determining where registers should
1021         end up is easier to implement correctly with explicit annotations, so
1022         for these reasons we will look at how this annotations could work.
1023
1024         \todo{Sidenote: one or more state arguments?}
1025
1026     \subsection[sec:description:stateann]{Explicit state annotation}
1027       To make our stateful descriptions unambigious and easier to translate,
1028       we need some way for the developer to describe which arguments and
1029       results are intended to become stateful.
1030     
1031       Roughly, we have two ways to achieve this:
1032       \startitemize[KR]
1033         \item Use some kind of annotation method or syntactic construction in
1034         the language to indicate exactly which argument and (part of the)
1035         result is stateful. This means that the annotation lives
1036         \quote{outside} of the function, it is completely invisible when
1037         looking at the function body.
1038         \item Use some kind of annotation on the type level, \ie\ give stateful
1039         arguments and stateful (parts of) results a different type. This has the
1040         potential to make this annotation visible inside the function as well,
1041         such that when looking at a value inside the function body you can
1042         tell if it is stateful by looking at its type. This could possibly make
1043         the translation process a lot easier, since less analysis of the
1044         program flow might be required.
1045       \stopitemize
1046
1047       From these approaches, the type level \quote{annotations} have been
1048       implemented in Cλash. \in{Section}[sec:prototype:statetype] expands on
1049       the possible ways this could have been implemented.
1050
1051   \todo{Note about conditions on state variables and checking them}
1052
1053   \section[sec:recursion]{Recursion}
1054   An important concept in functional languages is recursion. In its most basic
1055   form, recursion is a definition that is described in terms of itself. A
1056   recursive function is thus a function that uses itself in its body. This
1057   usually requires multiple evaluations of this function, with changing
1058   arguments, until eventually an evaluation of the function no longer requires
1059   itself.
1060
1061   Given the notion that each function application will translate to a
1062   component instantiation, we are presented with a problem. A recursive
1063   function would translate to a component that contains itself. Or, more
1064   precisely, that contains an instance of itself. This instance would again
1065   contain an instance of itself, and again, into infinity. This is obviously a
1066   problem for generating hardware.
1067
1068   This is expected for functions that describe infinite recursion. In that
1069   case, we cannot generate hardware that shows correct behaviour in a single
1070   cycle (at best, we could generate hardware that needs an infinite number of
1071   cycles to complete).
1072   
1073   \placeintermezzo{}{
1074     \startframedtext[width=8cm,background=box,frame=no]
1075     \startalignment[center]
1076       {\tfa \hs{null}, \hs{head} and \hs{tail}}
1077     \stopalignment
1078     \blank[medium]
1079       The functions \hs{null}, \hs{head} and \hs{tail} are common list
1080       functions in Haskell. The \hs{null} function simply checks if a list is
1081       empty. The \hs{head} function returns the first element of a list. The
1082       \hs{tail} function returns containing everything \emph{except} the first
1083       element of a list.
1084
1085       In Cλash, there are vector versions of these functions, which do exactly
1086       the same.
1087     \stopframedtext
1088   }
1089
1090   However, most recursive definitions will describe finite
1091   recursion. This is because the recursive call is done conditionally. There
1092   is usually a \hs{case} expression where at least one alternative does not contain
1093   the recursive call, which we call the "base case". If, for each call to the
1094   recursive function, we would be able to detect at compile time which
1095   alternative applies, we would be able to remove the \hs{case} expression and
1096   leave only the base case when it applies. This will ensure that expanding
1097   the recursive functions will terminate after a bounded number of expansions.
1098
1099   This does imply the extra requirement that the base case is detectable at
1100   compile time. In particular, this means that the decision between the base
1101   case and the recursive case must not depend on runtime data.
1102
1103   \subsection{List recursion}
1104   The most common deciding factor in recursion is the length of a list that is
1105   passed in as an argument. Since we represent lists as vectors that encode
1106   the length in the vector type, it seems easy to determine the base case. We
1107   can simply look at the argument type for this. However, it turns out that
1108   this is rather non-trivial to write down in Haskell already, not even
1109   looking at translation. As an example, we would like to write down something
1110   like this:
1111  
1112   \starthaskell
1113     sum :: Vector n Word -> Word
1114     sum xs = case null xs of
1115       True -> 0
1116       False -> head xs + sum (tail xs)
1117   \stophaskell
1118
1119   However, the Haskell typechecker will now use the following reasoning.
1120   For simplicity, the element type of a vector is left out, all vectors
1121   are assumed to have the same element type. Below, we write conditions
1122   on type variables before the \hs{=>} operator. This is not completely
1123   valid Haskell syntax, but serves to illustrate the typechecker
1124   reasoning. Also note that a vector can never have a negative length,
1125   so \hs{Vector n} implicitly means \hs{(n >= 0) => Vector n}.
1126
1127   \todo{This typechecker disregards the type signature}
1128   \startitemize
1129   \item tail has the type \hs{(n > 0) => Vector n -> Vector (n - 1)}
1130   \item This means that xs must have the type \hs{(n > 0) => Vector n}
1131   \item This means that sum must have the type \hs{(n > 0) => Vector n -> a}
1132   (The type \hs{a} is can be anything at this stage, we will not try to finds
1133   its actual type in this example).
1134   \item sum is called with the result of tail as an argument, which has the
1135   type \hs{Vector n} (since \hs{(n > 0) => Vector (n - 1)} is the same as \hs{(n >= 0)
1136   => Vector n}, which is the same as just \hs{Vector n}).
1137   \item This means that sum must have the type \hs{Vector n -> a}
1138   \item This is a contradiction between the type deduced from the body of sum
1139   (the input vector must be non-empty) and the use of sum (the input vector
1140   could have any length).
1141   \stopitemize
1142
1143   As you can see, using a simple \hs{case} expression  at value level causes
1144   the type checker to always typecheck both alternatives, which cannot be
1145   done. The typechecker is unable to distinguish the two case
1146   alternatives (this is partly possible using \small{GADT}s, but that
1147   approach faced other problems \todo{ref christiaan?}).
1148
1149   This is a fundamental problem, that would seem perfectly suited for a
1150   type class.  Considering that we need to switch between to
1151   implementations of the sum function, based on the type of the
1152   argument, this sounds like the perfect problem to solve with a type
1153   class. However, this approach has its own problems (not the least of
1154   them that you need to define a new type class for every recursive
1155   function you want to define).
1156
1157   \todo{This should reference Christiaan}
1158
1159   \subsection{General recursion}
1160   Of course there are other forms of recursion, that do not depend on the
1161   length (and thus type) of a list. For example, simple recursion using a
1162   counter could be expressed, but only translated to hardware for a fixed
1163   number of iterations. Also, this would require extensive support for compile
1164   time simplification (constant propagation) and compile time evaluation
1165   (evaluation of constant comparisons), to ensure non-termination.
1166   Supporting general recursion will probably require strict conditions
1167   on the input descriptions. Even then, it will be hard (if not
1168   impossible) to really guarantee termination, since the user (or \GHC\
1169   desugarer) might use some obscure notation that results in a corner
1170   case of the simplifier that is not caught and thus non-termination.
1171
1172   Evaluating all possible (and non-possible) ways to add recursion to
1173   our descriptions, it seems better to limit the scope of this research
1174   to exclude recursion. This allows for focusing on other interesting
1175   areas instead. By including (built-in) support for a number of
1176   higher-order functions like \hs{map} and \hs{fold}, we can still
1177   express most of the things we would use (list) recursion for.
1178   
1179
1180 % vim: set sw=2 sts=2 expandtab: