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