Remove some progress documents, they are being stored elsewhere.
[matthijs/master-project/report.git] / Chapters / HardwareDescription.tex
index 2a7a077d269bb8d1a1bd6fedd62c67fff888eaba..f56723c1dd4c46e37495502304c2ece6dc15ed13 100644 (file)
@@ -108,13 +108,37 @@ and3 a b c = and (and a b) c
     ncline(andb)(out);
   \stopuseMPgraphic
 
+  \startbuffer[And3VHDL]
+    entity and3Component_0 is
+         port (\azMyG2\ : in std_logic;
+               \bzMyI2\ : in std_logic;
+               \czMyK2\ : in std_logic;
+               \foozMySzMyS2\ : out std_logic;
+               clock : in std_logic;
+               resetn : in std_logic);
+    end entity and3Component_0;
+
+
+    architecture structural of and3Component_0 is
+         signal \argzMyMzMyM2\ : std_logic;
+    begin
+         \argzMyMzMyM2\ <= \azMyG2\ and \bzMyI2\;
+
+         \foozMySzMyS2\ <= \argzMyMzMyM2\ and \czMyK2\;
+    end architecture structural;
+  \stopbuffer
+
   \placeexample[][ex:And3]{Simple three input and gate.}
     \startcombination[2*1]
       {\typebufferhs{And3}}{Haskell description using function applications.}
       {\boxedgraphic{And3}}{The architecture described by the Haskell description.}
     \stopcombination
 
+  \placeexample[][ex:And3VHDL]{\VHDL\ generated for \hs{and3} from \in{example}[ex:And3]}
+      {\typebuffervhdl{And3VHDL}}
+
   \placeintermezzo{}{
+    \defref{top level binding}
     \defref{top level binder}
     \defref{top level function}
     \startframedtext[width=8cm,background=box,frame=no]
@@ -122,14 +146,18 @@ and3 a b c = and (and a b) c
       {\tfa Top level binders and functions}
     \stopalignment
     \blank[medium]
-      A top level binder is any binder (variable) that is declared in
-      the \quote{global} scope of a Haskell program (as opposed to a
-      binder that is bound inside a function.
+      A \emph{top level binder} is any binder (variable) that is
+      declared in the \quote{global} scope of a Haskell program (as
+      opposed to a binder that is bound inside a function. The binder
+      together with its body is referred to as a \emph{top level
+      binding}.
 
       In Haskell, there is no sharp distinction between a variable and a
       function: a function is just a variable (binder) with a function
-      type. This means that a top level function is just any top level
-      binder with a function type.
+      type. This means that a \emph{top level function} is just any top
+      level binder with a function type. This also means that sometimes
+      top level function will be used when top level binder is really
+      meant.
 
       As an example, consider the following Haskell snippet:
 
@@ -155,7 +183,7 @@ and3 a b c = and (and a b) c
     expressions, pattern matching and guards.
 
     An obvious way to add choice to our language without having to recognize
-    any of Haskell's syntax, would be to add a primivite \quote{\hs{if}}
+    any of Haskell's syntax, would be to add a primitive \quote{\hs{if}}
     function. This function would take three arguments: the condition, the
     value to return when the condition is true and the value to return when
     the condition is false.
@@ -170,13 +198,16 @@ and3 a b c = and (and a b) c
     simply be translated to a conditional assignment, where the conditions use
     equality comparisons against the constructors in the \hs{case} expressions.
 
-    In \in{example}[ex:CaseInv] a simple \hs{case} expression is shown,
-    scrutinizing a boolean value. The corresponding architecture has a
-    comparator to determine which of the constructors is on the \hs{in}
-    input. There is a multiplexer to select the output signal. The two options
-    for the output signals are just constants, but these could have been more
-    complex expressions (in which case also both of them would be working in
-    parallel, regardless of which output would be chosen eventually).
+    In \in{example}[ex:Inv] two versions of an inverter are shown. The first
+    uses a simple \hs{case} expression, scrutinizing a Boolean value.  The
+    corresponding architecture has a comparator to determine which of the
+    constructors is on the \hs{in} input. There is a multiplexer to select the
+    output signal (which is just a conditional assignment in the generated
+    \VHDL). The two options for the output signals are just constants,
+    but these could have been more complex expressions (in which case also
+    both of them would be working in parallel, regardless of which output
+    would be chosen eventually). The \VHDL\ generated for (both versions of)
+    this inverter is shown in \in{example}[ex:InvVHDL].
 
     If we would translate a Boolean to a bit value, we could of course remove
     the comparator and directly feed 'in' into the multiplexer (or even use an
@@ -210,8 +241,9 @@ and3 a b c = and (and a b) c
     specifies a pattern. When the arguments match the pattern, the
     corresponding clause will be used.
 
-    The architecture described by \in{example}[ex:PatternInv] is of course the
-    same one as the one in \in{example}[ex:CaseInv]. The general interpretation
+    \in{Example}[ex:Inv] also shows an inverter that uses pattern matching.
+    The architecture it describes is of course the
+    same one as the description with a case expression. The general interpretation
     of pattern matching is also similar to that of \hs{case} expressions: generate
     hardware for each of the clauses (like each of the clauses of a \hs{case}
     expression) and connect them to the function output through (a number of
@@ -230,7 +262,13 @@ and3 a b c = and (and a b) c
       False -> True
     \stopbuffer
 
-    \startuseMPgraphic{CaseInv}
+    \startbuffer[PatternInv]
+    inv :: Bool -> Bool
+    inv True = False
+    inv False = True
+    \stopbuffer
+
+    \startuseMPgraphic{Inv}
       save in, truecmp, falseout, trueout, out, cmp, mux;
 
       % I/O ports
@@ -263,22 +301,51 @@ and3 a b c = and (and a b) c
       ncline(trueout)(mux) "posB(inpb)";
       ncline(mux)(out) "posA(out)";
     \stopuseMPgraphic
-
-    \placeexample[][ex:CaseInv]{Simple inverter.}
-      \startcombination[2*1]
-        {\typebufferhs{CaseInv}}{Haskell description using a Case expression.}
-        {\boxedgraphic{CaseInv}}{The architecture described by the Haskell description.}
-      \stopcombination
-
-    \startbuffer[PatternInv]
-    inv :: Bool -> Bool
-    inv True = False
-    inv False = True
+    
+    \startbuffer[InvVHDL]
+      entity invComponent_0 is
+           port (\xzAMo2\ : in boolean;
+                 \reszAMuzAMu2\ : out boolean;
+                 clock : in std_logic;
+                 resetn : in std_logic);
+      end entity invComponent_0;
+
+
+      architecture structural of invComponent_0 is
+      begin
+           \reszAMuzAMu2\ <= false when \xzAMo2\ = true else
+                             true;
+      end architecture structural; 
     \stopbuffer
 
-    \placeexample[][ex:PatternInv]{Simple inverter using pattern matching.
-    Describes the same architecture as \in{example}[ex:CaseInv].}
-        {\typebufferhs{PatternInv}}
+    \placeexample[][ex:Inv]{Simple inverter.}{
+      % Use placesidebyside, since nesting combinations doesn't seem to work
+      % here. This does break centering, but well...
+      \placesidebyside
+        % Use 2*2 instead of 1*2 to insert some extra space (\placesidebyside
+        % places stuff very close together)
+        {\startcombination[2*2]
+          {\typebufferhs{CaseInv}}{Haskell description using a Case expression.}
+          {}{}
+          {\typebufferhs{PatternInv}}{Haskell description using Pattern matching expression.}
+          {}{}
+        \stopcombination}
+        % Use a 1*1 combination to add a caption
+        {\startcombination[1*1]
+          {\boxedgraphic{Inv}}{The architecture described by the Haskell descriptions.}
+        \stopcombination}
+      }
+
+%    \placeexample[][ex:Inv]{Simple inverter.}{
+%        \startcombination[2*2]
+%          {\typebufferhs{CaseInv}}{Haskell description using a Case expression.}
+%          {}{}
+%          {\typebufferhs{PatternInv}}{Haskell description using Pattern matching expression.}
+%          {\boxedgraphic{Inv}}{The architecture described by the Haskell description.}
+%        \stopcombination
+%    }
+    \placeexample[][ex:InvVHDL]{\VHDL\ generated for (both versions of) \hs{inv} from \in{example}[ex:Inv]}
+        {\typebuffervhdl{InvVHDL}}
 
   \section{Types}
     Translation of two most basic functional concepts has been
@@ -329,7 +396,7 @@ and3 a b c = and (and a b) c
       \stopdesc
       \startdesc{\hs{SizedWord}, \hs{SizedInt}}
         These are types to represent integers. A \hs{SizedWord} is unsigned,
-        while a \hs{SizedInt} is signed. These types are parameterized by a
+        while a \hs{SizedInt} is signed. These types are parametrized by a
         length type, so you can define an unsigned word of 32 bits wide as
         follows:
         
@@ -351,7 +418,7 @@ and3 a b c = and (and a b) c
         has a fixed length. It has two type parameters: its
         length and the type of the elements contained in it. By putting the
         length parameter in the type, the length of a vector can be determined
-        at compile time, instead of only at runtime for conventional lists.
+        at compile time, instead of only at run-time for conventional lists.
 
         The \hs{Vector} type constructor takes two type arguments: the length
         of the vector and the type of the elements contained in it. The state
@@ -371,12 +438,12 @@ and3 a b c = and (and a b) c
       \stopdesc
       \startdesc{\hs{RangedWord}}
         This is another type to describe integers, but unlike the previous
-        two it has no specific bitwidth, but an upper bound. This means that
+        two it has no specific bit-width, but an upper bound. This means that
         its range is not limited to powers of two, but can be any number.
         A \hs{RangedWord} only has an upper bound, its lower bound is
         implicitly zero. There is a lot of added implementation complexity
         when adding a lower bound and having just an upper bound was enough
-        for the primary purpose of this type: typesafely indexing vectors.
+        for the primary purpose of this type: type-safely indexing vectors.
 
         To define an index for the 8 element vector above, we would do:
 
@@ -398,7 +465,7 @@ and3 a b c = and (and a b) c
 
     \subsection{User-defined types}
       There are three ways to define new types in Haskell: algebraic
-      datatypes with the \hs{data} keyword, type synonyms with the \hs{type}
+      data-types with the \hs{data} keyword, type synonyms with the \hs{type}
       keyword and type renamings with the \hs{newtype} keyword. \GHC\
       offers a few more advanced ways to introduce types (type families,
       existential typing, \small{GADT}s, etc.) which are not standard
@@ -429,7 +496,7 @@ and3 a b c = and (and a b) c
 
         These types are translated to \VHDL\ record types, with one field for
         every field in the constructor. This translation applies to all single
-        constructor algebraic datatypes, including those with just one
+        constructor algebraic data-types, including those with just one
         field (which are technically not a product, but generate a VHDL
         record for implementation simplicity).
       \stopdesc
@@ -437,7 +504,7 @@ and3 a b c = and (and a b) c
         \defref{enumerated types}
         An enumerated type is an algebraic datatype with multiple constructors, but
         none of them have fields. This is essentially a way to get an
-        enum-like type containing alternatives.
+        enumeration-like type containing alternatives.
 
         Note that Haskell's \hs{Bool} type is also defined as an
         enumeration type, but we have a fixed translation for that.
@@ -488,7 +555,7 @@ and3 a b c = and (and a b) c
         Obviously, duplication detection could be used to reuse a
         particular field for another constructor, but this would only
         partially solve the problem. If two fields would be, for
-        example, an array of 8 bits and an 8 bit unsiged word, these are
+        example, an array of 8 bits and an 8 bit unsigned word, these are
         different types and could not be shared. However, in the final
         hardware, both of these types would simply be 8 bit connections,
         so we have a 100\% size increase by not sharing these.
@@ -595,7 +662,7 @@ quadruple n = mul (mul n)
   \in{section}[sec:description:application]. It might mean that a
   partial application is passed around quite a bit (even beyond function
   boundaries), but eventually, the partial application will become
-  completely applied. An example of this principe is given in
+  completely applied. An example of this principle is given in
   \in{section}[sec:normalization:defunctionalization].
 
   \section{Costless specialization}
@@ -612,13 +679,13 @@ quadruple n = mul (mul n)
     machine code has implications for speed (due to less efficient caching)
     and memory usage. For normal compilation, it is therefore important to
     keep the amount of functions limited and maximize the code sharing
-    (though there is a tradeoff between speed and memory usage here).
+    (though there is a trade-off between speed and memory usage here).
 
     When generating hardware, this is hardly an issue. Having more \quote{code
     sharing} does reduce the amount of \small{VHDL} output (Since different
     component instantiations still share the same component), but after
     synthesis, the amount of hardware generated is not affected. This
-    means there is no tradeoff between speed and memory (or rather,
+    means there is no trade-off between speed and memory (or rather,
     chip area) usage.
 
     In particular, if we would duplicate all functions so that there is a
@@ -637,7 +704,7 @@ quadruple n = mul (mul n)
       \defref{specialization}
       Given some function that has a \emph{domain} $D$ (\eg, the set of
       all possible arguments that the function could be applied to), we
-      create a specialized function with exactly the same behaviour, but
+      create a specialized function with exactly the same behavior, but
       with a domain $D' \subset D$. This subset can be chosen in all
       sorts of ways. Any subset is valid for the general definition of
       specialization, but in practice only some of them provide useful
@@ -703,7 +770,7 @@ quadruple n = mul (mul n)
     When generating hardware, polymorphism cannot be easily translated. How
     many wires will you lay down for a value that could have any type? When
     type classes are involved, what hardware components will you lay down for
-    a class method (whose behaviour depends on the type of its arguments)?
+    a class method (whose behavior depends on the type of its arguments)?
     Note that Cλash currently does not allow user-defined type classes,
     but does partly support some of the built-in type classes (like \hs{Num}).
 
@@ -734,10 +801,10 @@ quadruple n = mul (mul n)
     stateless (or, \emph{combinational}) design, every output is  directly and solely dependent on the
     inputs. In a stateful design, the outputs can depend on the history of
     inputs, or the \emph{state}. State is usually stored in \emph{registers},
-    which retain their value during a clockcycle, and are typically updated at
-    the start of every clockcycle. Since the updating of the state is tightly
+    which retain their value during a clock cycle, and are typically updated at
+    the start of every clock cycle. Since the updating of the state is tightly
     coupled (synchronized) to the clock signal, these state updates are often
-    called \emph{synchronous} behaviour.
+    called \emph{synchronous} behavior.
 
     \todo{Sidenote? Registers can contain any (complex) type}
   
@@ -770,7 +837,7 @@ quadruple n = mul (mul n)
 
         Purity is an important property in functional languages, since
         it enables all kinds of mathematical reasoning and
-        optimizattions with pure functions, that are not guaranteed to
+        optimizations with pure functions, that are not guaranteed to
         be correct for impure functions.
 
         An example of a pure function is the square root function
@@ -796,7 +863,7 @@ quadruple n = mul (mul n)
 
       \subsubsection{Stream arguments and results}
         Including the entire history of each input (\eg, the value of that
-        input for each previous clockcycle) is an obvious way to make outputs
+        input for each previous clock cycle) is an obvious way to make outputs
         depend on all previous input. This is easily done by making every
         input a list instead of a single value, containing all previous values
         as well as the current value.
@@ -811,7 +878,7 @@ quadruple n = mul (mul n)
         ForSyDe, ...} Make functions operate on complete streams. This means
         that a function is no longer called on every cycle, but just once. It
         takes stream as inputs instead of values, where each stream contains
-        all the values for every clockcycle since system start. This is easily
+        all the values for every clock cycle since system start. This is easily
         modeled using an (infinite) list, with one element for each clock
         cycle. Since the function is only evaluated once, its output must also
         be a stream. Note that, since we are working with infinite lists and
@@ -820,14 +887,14 @@ quadruple n = mul (mul n)
 
         Since our inputs and outputs are streams, all other (intermediate)
         values must be streams. All of our primitive operators (\eg, addition,
-        substraction, bitwise operations, etc.) must operate on streams as
+        subtraction, bit-wise operations, etc.) must operate on streams as
         well (note that changing a single-element operation to a stream
         operation can done with \hs{map}, \hs{zipwith}, etc.).
 
         This also means that primitive operations from an existing
         language such as Haskell cannot be used directly (including some
         syntax constructs, like \hs{case} expressions and \hs{if}
-        expressions).  This mkes this approach well suited for use in
+        expressions).  This makes this approach well suited for use in
         \small{EDSL}s, since those already impose these same
         limitations. \refdef{EDSL}
 
@@ -938,7 +1005,7 @@ acc in s = (s', out)
 
       \subsubsection{Substates}
         Since a function's state is reflected directly in its type signature,
-        if a function calls other stateful functions (\eg, has subcircuits), it
+        if a function calls other stateful functions (\eg, has sub-circuits), it
         has to somehow know the current state for these called functions. The
         only way to do this, is to put these \emph{substates} inside the
         caller's state. This means that a function's state is the sum of the
@@ -952,9 +1019,8 @@ acc in s = (s', out)
 
         This is the major downside of this approach: the separation between
         interface and implementation is limited. However, since Cλash is not
-        very suitable for separate compilation (see
-        \in{section}[sec:prototype:separate]) this is not a big problem in
-        practice.
+        very suitable for separate compilation this is not a big problem
+        in practice.
 
         Additionally, when using a type synonym for the state type
         of each function, we can still provide explicit type signatures
@@ -963,18 +1029,18 @@ acc in s = (s', out)
         \todo{Example}
     
       \subsubsection{Which arguments and results are stateful?}
-        \fxnote{This section should get some examples}
+        \todo{This section should get some examples}
         We need some way to know which arguments should become input ports and
         which argument(s?) should become the current state (\eg, be bound to
         the register outputs). This does not hold just for the top
-        level function, but also for any subfunction. Or could we perhaps
-        deduce the statefulness of subfunctions by analyzing the flow of data
+        level function, but also for any sub-function. Or could we perhaps
+        deduce the statefulness of sub-functions by analyzing the flow of data
         in the calling functions?
 
-        To explore this matter, the following observeration is interesting: we
-        get completely correct behaviour when we put all state registers in
+        To explore this matter, the following observation is interesting: we
+        get completely correct behavior when we put all state registers in
         the top level entity (or even outside of it). All of the state
-        arguments and results on subfunctions are treated as normal input and
+        arguments and results on sub-functions are treated as normal input and
         output ports. Effectively, a stateful function results in a stateless
         hardware component that has one of its input ports connected to the
         output of a register and one of its output ports connected to the
@@ -983,23 +1049,23 @@ acc in s = (s', out)
         \todo{Example}
 
         Of course, even though the hardware described like this has the
-        correct behaviour, unless the layout tool does smart optimizations,
+        correct behavior, unless the layout tool does smart optimizations,
         there will be a lot of extra wire in the design (since registers will
         not be close to the component that uses them). Also, when working with
         the generated \small{VHDL} code, there will be a lot of extra ports
         just to pass on state values, which can get quite confusing.
 
         To fix this, we can simply \quote{push} the registers down into the
-        subcircuits. When we see a register that is connected directly to a
-        subcircuit, we remove the corresponding input and output port and put
-        the register inside the subcircuit instead. This is slightly less
+        sub-circuits. When we see a register that is connected directly to a
+        sub-circuit, we remove the corresponding input and output port and put
+        the register inside the sub-circuit instead. This is slightly less
         trivial when looking at the Haskell code instead of the resulting
         circuit, but the idea is still the same.
 
         \todo{Example}
 
         However, when applying this technique, we might push registers down
-        too far. When you intend to store a result of a stateless subfunction
+        too far. When you intend to store a result of a stateless sub-function
         in the caller's state and pass the current value of that state
         variable to that same function, the register might get pushed down too
         far. It is impossible to distinguish this case from similar code where
@@ -1017,14 +1083,14 @@ acc in s = (s', out)
         \stopitemize
 
         The first option causes (non-obvious) exceptions in the language
-        intepretation. Also, automatically determining where registers should
+        interpretation. Also, automatically determining where registers should
         end up is easier to implement correctly with explicit annotations, so
         for these reasons we will look at how this annotations could work.
 
         \todo{Sidenote: one or more state arguments?}
 
     \subsection[sec:description:stateann]{Explicit state annotation}
-      To make our stateful descriptions unambigious and easier to translate,
+      To make our stateful descriptions unambiguous and easier to translate,
       we need some way for the developer to describe which arguments and
       results are intended to become stateful.
     
@@ -1066,7 +1132,7 @@ acc in s = (s', out)
   problem for generating hardware.
 
   This is expected for functions that describe infinite recursion. In that
-  case, we cannot generate hardware that shows correct behaviour in a single
+  case, we cannot generate hardware that shows correct behavior in a single
   cycle (at best, we could generate hardware that needs an infinite number of
   cycles to complete).
   
@@ -1098,7 +1164,7 @@ acc in s = (s', out)
 
   This does imply the extra requirement that the base case is detectable at
   compile time. In particular, this means that the decision between the base
-  case and the recursive case must not depend on runtime data.
+  case and the recursive case must not depend on run-time data.
 
   \subsection{List recursion}
   The most common deciding factor in recursion is the length of a list that is
@@ -1116,15 +1182,15 @@ acc in s = (s', out)
       False -> head xs + sum (tail xs)
   \stophaskell
 
-  However, the Haskell typechecker will now use the following reasoning.
+  However, the Haskell type-checker will now use the following reasoning.
   For simplicity, the element type of a vector is left out, all vectors
   are assumed to have the same element type. Below, we write conditions
   on type variables before the \hs{=>} operator. This is not completely
-  valid Haskell syntax, but serves to illustrate the typechecker
+  valid Haskell syntax, but serves to illustrate the type-checker
   reasoning. Also note that a vector can never have a negative length,
   so \hs{Vector n} implicitly means \hs{(n >= 0) => Vector n}.
 
-  \todo{This typechecker disregards the type signature}
+  \todo{This type-checker disregards the type signature}
   \startitemize
   \item tail has the type \hs{(n > 0) => Vector n -> Vector (n - 1)}
   \item This means that xs must have the type \hs{(n > 0) => Vector n}
@@ -1141,10 +1207,10 @@ acc in s = (s', out)
   \stopitemize
 
   As you can see, using a simple \hs{case} expression  at value level causes
-  the type checker to always typecheck both alternatives, which cannot be
-  done. The typechecker is unable to distinguish the two case
+  the type checker to always type-check both alternatives, which cannot be
+  done. The type-checker is unable to distinguish the two case
   alternatives (this is partly possible using \small{GADT}s, but that
-  approach faced other problems \todo{ref christiaan?}).
+  approach faced other problems \cite[baaij09]). 
 
   This is a fundamental problem, that would seem perfectly suited for a
   type class.  Considering that we need to switch between to
@@ -1154,8 +1220,6 @@ acc in s = (s', out)
   them that you need to define a new type class for every recursive
   function you want to define).
 
-  \todo{This should reference Christiaan}
-
   \subsection{General recursion}
   Of course there are other forms of recursion, that do not depend on the
   length (and thus type) of a list. For example, simple recursion using a