2      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~                           ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T UVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c!d!e!f!g!h!i!j!k!l!m!n"o"p"q"r"s"t"uvwxyz{|#}#~##################$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&&&&&'''''''''''''''((((((((0)(C) 2017, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>Safe3W(C) 2012-2016, University of Twente, 2017 , Myrtle Software LtdBSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>SafeIVComponent instantiation hole. First argument indicates which function argument to instantiate. Second argument corresponds to output and input assignments, where the first element is the output assignment, and the subsequent elements are the consecutive input assignments.eThe LHS of the tuple is the name of the signal, while the RHS of the tuple is the type of the signalElements of a blackbox context Constant Component instantiation hole  Output hole; Bool asserts escape marker stripping  Input hole; Bool asserts escape marker stripping  Name hole Literal hole Symbol holeType declaration holeType root holeError value hole&Select element type from a vector typeIHole for the name of the component in which the blackbox is instantiatedAIndex data type hole, the field is the (exclusive) maximum indexSize of a type holeLength of a vector holeDepth of a tree hole*Hole containing a filepath for a data fileGHole marking beginning (True) or end (False) of a generative constructHole indicating whether IntWordInteger are 64-Bit >Hole indicating which synthesis tool we're generating HDL for!*Convert to (True)/from(False) a bit-vector+)A BlackBox Template is a List of Elements))('&%$#" * !   +)+  !"#$%&'()*"  !"#$%&'()*W(C) 2012-2016, University of Twente, 2017 , Myrtle Software LtdBSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>NoneX 1Parse a text as a BlackBoxTemplate, returns a list of errors in case parsing fails runParse :: Text -> (BlackBoxTemplate, [Error LineColPos]) runParse = PCC.parse ((,)  $ pBlackBoxD  */ pEnd) . createStr (LineColPos 0 0 0)7Parse a BlackBoxTemplate (Declarations and Expressions)Parse a single Template Element!Parse the Text part of a Template)Parse a Declaration or Expression elementParse a Declaration#Parse the output tag of Declaration"Parse the input tag of DeclarationParse an Expression elementParse a bracketed text/Parse the expression part of Blackbox TemplatesParse an Expression or Text Parse SigD11#(C) 2012-2016, University of TwenteBSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>Safe%Z2345623456234W(C) 2012-2016, University of Twente, 2016-2017, Myrtle Software LtdBSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None;=]g 7Externally defined primitive8LA primitive that has a template that can be filled out by the backend render9/A primitive that carries additional information:Name of the primitive;-Verilog only: whether the result should be a reg(True) or wire (False); when not specified in the .json" file, the value will default to False (i.e. wire).<VHDL only: add library! declarations for the given names=VHDL only: add use! declarations for the given names>IntelQuartus only: create a 2.qsys/ file from the given template. Defaults to Nothing when not specified in the .json file? Either a  declaration or an  expression template.@Additional informationAPrimitive Definitions 789@=<;>?:A A789:;<=>?:@B7 89:;<=>?:@*#(C) 2015-2016, University of TwenteBSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>Nonemh/Pretty print part of json file related to errorMParse a ByteString according to the given JSON template. Prints failures on stdout, and returns  if parsing fails.Bytestring to parse+Safem,Safe;=n3     6-(C) 2017, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None06p.(C) 2017, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None068r/Safer !"#$%#(C) 2012-2016, University of TwenteBSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None;=DNQVMD(A class that can generate unique numbersEGet a new uniqueF^Create a TH expression that returns the a formatted string containing the name of the module F4 is spliced into, and the line where it was spliced.G$Cache the result of a monadic actionHICache the result of a monadic action in a State 3 transformer layers downISpine-strict cache variant of  mkCachedT3JIRun a State-action using the State that is stored in a higher-layer MonadKFunctorial version of 01LFunctorial version of 02N0Performs trace when first argument evaluates to &OMonadic version of 34PMonadic version of 35Q6Composition of a unary function with a binary functionR)if-then-else as a function on an argumentS&Applicative version of 'GHC.Types.(:)'TSafe indexing, returns a  if the index does not existUBUnsafe indexing, return a custom error message when indexing failsV5Split the second list at the length of the first listX*x y -> floor (logBase x y), x > 1 && y > 0Y,x y -> ceiling (logBase x y), x > 1 && y > 0G%The key the action is associated with)The Lens to the HashMap that is the cacheThe action to cacheH%The key the action is associated with)The Lens to the HashMap that is the cacheThe action to cacheJ+Lens to the State in the higher-layer monadThe State-action to perform!'()*+,-./0DEFGHIJKLMNOPQRSTUVWXYDEZFGHIJKLMNOPQRSTUVWXYDES5W(C) 2012-2016, University of Twente, 2017 , Myrtle Software LtdBSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>Noney\hGenerate a set of primitives that are found in the primitive definition files in the given directories.\/Directories to search for primitive definitions[\[\6P(C) 2015-2016, University of Twente, 2017, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None;=>?L(C) 2017, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None68;=>?<]_`^abcdeftuvwxyz{|bcdefiha]^_`g~}tuvwxyz{|]^_`bcdef P(C) 2012-2016, University of Twente, 2017, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None68>? Type variable Term variableVariables in CoreHWConstructor for type variablesConstructor for term variablesChange the name of a variable  P(C) 2012-2016, University of Twente, 2017, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None 68;=>?L DataCon reference:Syntactical position of the DataCon in the type definitionData ConstructorName of the DataCon+Syntactical position in the type definitionType of the 'DataConmUniversally quantified type-variables, these type variables are also part of the result type of the DataConExistentially quantified type-variables, these type variables are not part of the result of the DataCon, but only of the arguments.Argument typesGiven a DataCon and a list of types, the type variables of the DataCon type are substituted for the list of types. The argument types are returned.NThe list of types should be equal to the number of type variables, otherwise Nothing is returned.  #(C) 2012-2016, University of TwenteBSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None68;=>?TyCon referenceType Constructor The RHS of an Algebraic DatatypeThe DataCons of a TyConThe newtype DataConThe argument type of the newtype DataCon in eta-reduced form, which is just the representation of the TyCon. The TyName's are the type-variables from the corresponding TyCon.Algorithmic DataCons$Function TyCons (e.g. type families)Primitive TyCons'To close the loop on the type hierarchyName of the TyConKind of the TyConNumber of type argumentsDataCon definitions&List of: ([LHS match types], RHS type) Create a Kind out of a TyConName&Does the TyCon look like a tuple TyCon%Get the DataCons belonging to a TyConX(C) 2012-2016, University of Twente, 2016 , Myrtle Software LtdBSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None)1 Builtin Name2 Builtin Name3 Builtin Name4 Builtin Name5 Builtin Kind6 Builtin Kind7 Builtin Kind8 Builtin Kind9 Builtin Type: Builtin Type; Builtin Type< Builtin Type= Builtin Type> Builtin Type? Builtin Type@ Builtin TypeA Builtin TypeB Builtin TypeC Builtin Type(C) 2012-2016, University of Twente, 2016 , Myrtle Software Ltd, 2017 , Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None68;=>? Term Literal Determines the Type of a Literal  P(C) 2012-2016, University of Twente, 2017, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None68;=>?Term referenceDTerm representation in the CoreHW language: System F + LetRec + Case+Patterns in the LHS of a case-decompositionVDatatype pattern, '[TyVar]' bind existentially-quantified type-variables of a DataConLiteral patternDefault patternBinding in a LetRec constructVariable referenceDatatype constructorLiteral PrimitiveTerm-abstractionType-abstraction ApplicationType-applicationRecursive let-bindingECase-expression: subject, type of alternatives, list of alternatives$Cast a term from one type to another P(C) 2012-2016, University of Twente, 2017, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None%=Substitutes types in a typeSubstitutes a type in a typeSubstitutes kinds in a kindSubstitutes a type in a termSubstitutes types in a termSubstitutes a term in a termSubstitutes terms in a term#Substitutes a term in a let-binding (C) 2012-2016, University of Twente, 2016 , Myrtle Software Ltd, 2017 , Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None %68;=>?D&Reference to a KindReference to a TypeThe level above types/Types in CoreHW: function and polymorphic typesMake a Type out of a TyConEither a Kind or a Type Literal TypesType Constants TyCon type  Function type!An easier view on types" Function type# Applied TyCon$Neither of the above% Type variable& Type constant'Polymorphic Type(Type Application) Type literal*An easier view on types+A view on types in which newtypes are transparent, the Signal type is transparent, and type functions are evaluated to WHNF (when possible).Only strips away one "layer".DZInstantiate and Apply the RHS/Original of a NewType with the given list of argument typesReturns Nothing when under-applied,3Make a function type of an argument and result type-DMake a TyCon Application out of a TyCon and a list of argument types.6Split a TyCon Application in a TyCon and its argumentsEIs a type a Superkind?/Determine the kind of a type0Is a type polymorphic?14Split a function type in an argument and result type3^Split a poly-function type in a: list of type-binders and argument types, and the result type4nSplit a poly-function type in a: list of type-binders and argument types, and the result type. Looks through Signal and type functions.5)Is a type a polymorphic or function type?6/Is a type a polymorphic or function type under +?7Is a type a function type?8AApply a function type to an argument type and get the result type9(Substitute the type variable of a type (') with another typeFCSplit a type application in the applied type and the argument types<-The type of GHC.Err.undefined :: forall a . a-(')&% !#"$*+,-./0123456789:;<=>-%&'()!"#$ *+/,-1234.560789:;<=>%&'() !"#$(C) 2013-2016, University of Twente, 2016-2017, Myrtle Software Ltd, 2017 , QBayLogic, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None UEInformation about the generated HDL between (sub)runs of the compilerWjHash of the TopEntity and all its dependencies + (maybe) Hash of the TestBench and all its dependenciesYFThe rendered versions of the types of the input ports of the TopEntity Used when dealing with multiple  TopEntityBs who have different names for types which are structurally equal[GThe rendered versions of the types of the output ports of the TopEntity Used when dealing with multiple  TopEntityBs who have different names for types which are structurally equal\.Names of all the generated components for the  TopEntity7 (does not include the names of the components of the  TestBench accompanying the  TopEntity).oDebug Message VerbositypDon't show debug messagesq&Show completely normalized expressionsr Names of applied transformationss/Show sub-expressions after a successful rewritet8Show all sub-expressions on which a rewrite is attempteduGlobal function bindersBGlobal functions cannot be mutually recursive, only self-recursive#UVWXYZ[\]^_`abcdefghijklmnopqrstu%uopqrst_`abcdefghijklmn]^wvUVWXYZ[\UVWXYZ[\]^_`abcdefghijklmnopqrstd(C) 2012-2016, University of Twente, 2017 , Myrtle Software Ltd, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None6Kd3?}8Context used to fill in the holes of a BlackBox templateResult name and type2Argument names, types, and whether it is a literal&Function arguments (subset of inputs):6( Blackbox Template , Whether the result should be reg or a wire2 (Verilog only) , Partial Blackbox Context ) Bit literalHighLow UndefinedHigh-impedanceLiterals used in an expressionNumber literal Bit literalBoolean literalVector literalString literal'Expression used in RHS of a declarationLiteral expressionDataCon applicationSignal referenceLeft e : tagToEnum, @Right e@: dataToTag&Instantiation of a BlackBox expressionExpression Modifier@Index the expression: (Type of expression,DataCon tag,Field Tag)JSee expression in a DataCon context: (Type of the expression, DataCon tag)>See the expression in the context of a Vector append operation<See the expression in the context of a Tree append operationInternals of a ComponentSignal assignment:Signal to assignAssigned expressionConditional signal assignment:Signal to assignType of the result/alternativesScrutinized expressionType of the scrutineeVList of: (Maybe expression scrutinized expression is compared with,RHS of alternative)"Instantiation of another component%Instantiation of blackbox declarationSignal declarationRepresentable hardware types Empty type.  Just Size for "empty" Vectors so we can still have primitives that can traverse e.g. Vectors of unit and know the lenght of that vector. String type Boolean typeBit typeBitVector of a specified size9Unsigned integer with specified (exclusive) upper bounder"Signed integer of a specified size$Unsigned integer of a specified size Vector type RTree type$Sum type: Name and Constructor names"Product type: Name and field types=Sum-of-Product type: Name and Constructor names + field types)Clock type with specified name and periodBReset type corresponding to clock with a specified name and period?Size indication of a type (e.g. bit-size or number of elements)!Component: base unit of a NetlistName of the component Input ports Output portsInternal declarationsSignal referenceState of the NetlistMonadGlobal bindersNumber of signal declarationsCached componentsPrimitive Definitions#Hardcoded Type -> HWType translator TyCon cache}Monad that caches generated components (StateT) and remembers hidden inputs of components that are being generated (WriterT)j}~w}~ }~d(C) 2015-2016, University of Twente, 2017 , Myrtle Software Ltd, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None^S5Initial state for state monad"What HDL is the backend generating&Location for the primitive definitionsmName of backend, used for directory to put output files in. Should be | constant function / ignore argument."File extension for target langauge !Get the set of types out of state $Generate HDL for a Netlist component HGenerate a HDL package containing type definitions for the given HWTypes -Convert a Netlist HWType to a target HDL type <Convert a Netlist HWType to an HDL error value for that type9Convert a Netlist HWType to the root of a target HDL typeHCreate a signal declaration from an identifier (Text) and Netlist HWType*Create a generative block statement marker4Turn a Netlist Declaration to a HDL concurrent block/Turn a Netlist expression into a HDL expressionBit-width of IntWordIntegerConvert to a bit-vectorConvert from a bit-vector'Synthesis tool we're generating HDL for mkIdentifier mkIdentifier setModName setSrcSpan getSrcSpanBlock of declarationsunextend/unescape identifier!+Is a type used for internal or external use" Internal use#.External use, field indicates the library name%dTry to merge nested modifiers into a single modifier, needed by the VHDL and SystemVerilog backend.&]Replace a normal HDL template placeholder with an unescaped/unextended template placeholder.Needed when the the place-holder is filled with an escaped/extended identifier inside an escaped/extended identifier and we want to strip the escape /extension markers. Otherwise we end up with illegal identifiers.$      !"#$%&$$!"#      %&      !"##(C) 2012-2016, University of TwenteBSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>NoneX.'Gives the free type-variables in a Type/'Gives the free term-variables of a Term0'Gives the free type-variables of a Term./0./0X(C) 2012-2016, University of Twente, 2016 , Myrtle Software LtdBSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None%;=\1#Pretty printing Show-like typeclass4 Print a Pretty thing to a String12341234GHIJKLMN123#(C) 2012-2016, University of TwenteBSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None%gEKind environment/contextFType environment/contextGDetermine the type of a termH>Split a (Type)Application in the applied term and it argumentsIHSplit a (Type)Abstraction in the bound variables and the abstracted termJGGet the result type of a polymorphic function given a list of argumentsK6Get the list of term-binders out of a DataType patternLMake a type variableMMake a term variableN6Abstract a term over a list of term and type variablesO-Abstract a term over a list of term variablesP-Abstract a term over a list of type variablesQ)Apply a list of types and terms to a termRApply a list of terms to a termSApply a list of types to a termT!Does a term have a function type?U0Does a term have a function or polymorphic type?VIs a term a term-abstraction?W"Is a term a recursive let-binding?XIs a term a variable reference?Y!Is a term a datatype constructor?ZIs a term a primitive?[,Make variable reference out of term variable\0Make a term variable out of a variable reference^$Create a vector of supplied elements_&Append elements to the supplied vector`Create let-bindings with case-statements that select elements out of a vector. Returns both the variables to which element-selections are bound and the let-bindingsaCreate let-bindings with case-statements that select elements out of a tree. Returns both the variables to which element-selections are bound and the let-bindingsb$Create a vector of supplied elementsc*Determine whether a type is isomorphic to Clash.Signal.Internal.Signal' It is i.e.: Signal' clk a(Signal' clk a, Signal' clk b)Vec n (Signal' clk a)data Wrap = W (Signal clk' Int)etc.^The Nil constructorThe Cons (:>) constructor Element typeLength of the vectorElements to put in the vector_The Cons (:>) constructor Element type$The vector to append the elements toLength of the vectorElements to append`The Cons (:>) constructorThe element type*Char to append to the bound variable namesLength of the vector The vectoraThe LR constructorThe BR constructorThe element type*Char to append to the bound variable namesDepth of the treeThe treebThe LR constructorThe BR constructor Element typeDepth of the treeElements to put in the tree!EFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcde!FEGHIJKLMNOPQRSTUVWXYZ[\]^_`abcded(C) 2012-2016, University of Twente, 2017 , Google Inc., Myrtle Software LtdBSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None%<NiSplit a normalized term into: a list of arguments, a list of let-bindings, and a variable reference that is the body of the let-binding. Returns a String containing the error is the term was not in a normalized form.jConverts a Core type to a HWType given a function that translates certain builtin types. Errors if the Core type is not translatable.kKConverts a Core type to a HWType within the NetlistMonad; errors on failurel:Converts a Core type to a HWType within the NetlistMonad;  on failurem@Returns the name and period of the clock corresponding to a typenConverts a Core type to a HWType given a function that translates certain builtin types. Returns a string containing the error message when the Core type is not translatable.oRConverts an algebraic Core type (split into a TyCon and its argument) to a HWType.p/Simple check if a TyCon is recursively defined.qnDetermines if a Core type is translatable to a HWType given a function that translates certain builtin types.r Determines the bitsize of a types3Determines the bitsize of the constructor of a typet(Gives the length of length-indexed typesu}Gives the HWType corresponding to a term. Returns an error if the term has a Core type that is not translatable to a HWType.v2Gives the HWType corresponding to a term. Returns C if the term has a Core type that is not translatable to a HWType.wLUniquely rename all the variables and their references in a normalized term|\Make a set of IDs unique; also returns a substitution from old ID to new updated unique ID.~Preserve the Netlist _varEnv and  when executing a monadic action$Create a Vector chain for a list of s#Create a RTree chain for a list of sGenerate output port mappingsIInstantiate a TopEntity, and add the proper type-conversions where needed)Convert between BitVector for an argument(Convert between BitVector for the result&Add to/from-BitVector conversion logic.Generate input port mappings for the TopEntity/Generate output port mappings for the TopEntity m TyCon cacheo#Hardcoded Type -> HWType translator TyCon cache9String representation of the Core type for error messages Keep Void The TyConIts applied argumentsqAllow zero-bit thingsString considered representable|Existing substitutionIDs to make unique!(Unique IDs, update substitution)Name of the TopEntity component(maybe) a corresponding  TopEntity annotationa corresponding Manifest=The name and type of the signal to which to assign the result The arguments(maybe) Name of the _TopEntity_Either: * A normal" argument * An argument with a PortName(mabye) Name of the _TopEntity_Either: * A normal result * A result with a PortName!We only need it for certain typesNothing: No _given_ TopEntity, no need for conversion, this happens when we have a _TestBench_, but no _TopEntity_ annotation.nJust Nothing: Converting to/from a BitVector for one of the internally defined types.fJust (Just top): Converting to/from a BitVector for one of the types defined by top.True: convert to a BitVectorFalse: convert from a BitVector>The expression on top of which we have to add conversion logic(maybe) Name of the _TopEntity_Rendered input port names and types (maybe) The PortName+ of a _TopEntity_ annotation for this input(maybe) Name of the _TopEntity_Rendered output port names and types (maybe) The PortName, of a _TopEntity_ annotation for this output,fghijklmnopqrstuvwxyz{|}~,fghijklmnopqrstuvwxyz{|}~X(C) 2012-2016, University of Twente, 2016-2017, Myrtle Software Ltd,BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None%<]r!Determine if the number of normalliteralqfunction inputs of a blackbox context at least matches the number of argument that is expected by the template.uUpdate all the symbol references in a template, and increment the symbol counter for every newly encountered symbol.XRender a blackbox given a certain context. Returns a filled out template and a list of hidden9 inputs that must be added to the encompassing component.Assign Var holes in the context of a primitive HDL template that is passed as an argument of a higher-order HDL template. For the general case, use This functions errors when the Var{ hole cannot be filled with a variable, as it is (currently) impossible to create unique names this late in the pipeline. Render a single template elementFill out the template corresponding to an output/input assignment of a component instantiation, and turn it into a single identifier so it can be used for a new blackbox context.pGive a context and a tagged hole (of a template), returns part of the context that matches the tag of the hole.Blackbox to verifyTemplate to check against Context used to fill in the holeBlackbox templateP(C) 2015-2016, University of Twente, 2017, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None%LN]w State for the O monad:P!Depth of current generative blockQIntWordInteger bit-widthR%Generate VHDL for a Netlist componentS6Convert a Netlist HWType to the root of a Verilog typeT=Convert a Netlist HWType to an error VHDL value for that typeU>Turn a Netlist Declaration to a SystemVerilog concurrent blockVQCalculate the beginning and end index into a variable, to get the desired field.W9Turn a Netlist expression into a SystemVerilog expressionV/Offset, only used when we have nested modifiersWEnclose in parenthesis?Expr to convertXPYZ[\Q]P(C) 2015-2016, University of Twente, 2017, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None%LNq State for the 78 monad:^Previously encountered HWTypes_Generated product types`1Cache for previously generated product type namesaIntWordInteger bit-widthb3For which HDL synthesis tool are we generating VHDLc%Generate VHDL for a Netlist componentdIGenerate a VHDL package containing type definitions for the given HWTypese'Convert a Netlist HWType to a VHDL typef3Convert a Netlist HWType to the root of a VHDL typeg=Convert a Netlist HWType to an error VHDL value for that typeh5Turn a Netlist Declaration to a VHDL concurrent blocki0Turn a Netlist expression into a VHDL expressioniEnclose in parenthesis?Expr to convert j^_`klmnoabP(C) 2015-2016, University of Twente, 2017, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None%LN] State for the p monad:qPreviously encountered HWTypesrProduct type counters1Cache for previously generated product type namest!Depth of current generative blockuIntWordInteger bit-widthv%Generate VHDL for a Netlist componentwRGenerate a SystemVerilog package containing type definitions for the given HWTypesx6Convert a Netlist HWType to the root of a Verilog typey=Convert a Netlist HWType to an error VHDL value for that typez>Turn a Netlist Declaration to a SystemVerilog concurrent block{9Turn a Netlist expression into a SystemVerilog expression{Enclose in parenthesis?Expr to convert |qrst}~u(C) 2017, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None%WEFunction that can evaluator primitives, i.e., perform delta-reductionState of the evaluator FunctionsType abstractionsData constructorsLiteralspClash's number types are represented by their "fromInteger#" primitive function. So some primitives are values. The stackThe heap6Evaluate to WHNF starting with an empty Heap and Stack1Evaluate to WHNF given an existing Heap and Stack<Are we in a context where special primitives must be forced.&See [Note: forcing special primitives]9Completely unwind the stack to get back the complete term!Small-step operational semantics.#Force the evaluation of a variable.Unwind the stack by 1'Update the Heap with the evaluated termApply a value to a functionInstantiate a type-abstraction"Evaluation of primitive operationsEvaluate a case-expression!Allocate let-bindings on the heap6Create a unique name and substitution for a let-binder'Create a name that's unique in the heapName of the primitiveType of the primitive Applied typesApplied values The current value 6The remaining terms which must be evaluated to a value)*(C) 2012-2016, University of Twente, 2016 , Myrtle Software Ltd, 2017 , Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None;=>?K&State of a rewriting session!Number of applied transformationsGlobal bindersSupply of unique numbers&Function which is currently normalized Used for Additional stateContext in which a term appears#Function position of an application#Argument position of an application'Function position of a type application)RHS of a Let-binder with the sibling LHS')Body of a Let-binding with the bound LHS'2Body of a lambda-term with the abstracted variable:Body of a TyLambda-term with the abstracted type-variableMRHS of a case-alternative with the variables bound by the pattern on the LHSSubject of a case-decompositionBody of a Cast,Read-only environment of a rewriting session(Lvl at which we print debugging messages"Hardcode Type -> HWType translator TyCon cacheTuple TyCon cache&Hardcoded evaluator (delta-reduction)}&Zero bit wide things are representable)Functions that are considered TopEntitiesA  action in the context of the =Monadic action that transforms a term given a certain contextMonad that keeps track how many transformations have been applied and can generate fresh variables and unique identifiers. In addition, it keeps track if a transformation/rewrite has been successfully applied..7      (C) 2012-2016, University of Twente, 2016 , Myrtle Software Ltd, 2017 , Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None%QVZdLift an action working in the  state to the 1Record if a transformation is succesfully applied"Perform a transformation on a Term,Evaluate a RewriteSession to its inner monad7Notify that a transformation has changed the expression^Identity function that additionally notifies that a transformation has changed the expression>Create a type and kind context out of a transformation contextaCreate a complete type and kind context out of the global binders and the transformation context3Make a new binder and variable reference for a termDMake a new binder and variable reference for either a term or a typeCMake a new, unique, identifier and corresponding variable reference@Inline the binders in a let-binding that have a certain property RDetermine whether a binder is a join-point created for a complex case expression.lA join-point is when a local function only occurs in tail-call positions, and when it does, more than once.!GCount the number of (only) tail calls of a function in an expression. B indicates that the function was used in a non-tail call position."6Determines whether a function has the following shape: \(w :: Void) -> f a b c8i.e. is a wrapper around a (partially) applied function f!, where the introduced argument w is not used by f#Substitute the RHS of the first set of Let-binders for references to the first set of Let-binders in: the second set of Let-binders and the additional term$Calculate the localb free variable of an expression: the free variables that are not bound in the global environment.&Create a global function for a Let-binding and return a Let-binding where the RHS is a reference to the new global function applied to the free variables of the original RHS',Make a global function for a name-term tuple(+Add a function to the set of global binders)@Create a new name out of the given name, but with another unique*=Test whether a term is a variable reference to a local binder+5Determine if a term cannot be represented in hardware,5Determine if a type cannot be represented in hardware-1Is the Context a Lambda/Term-abstraction context?.+Make a binder that should not be referenced/NMake a case-decomposition that extracts a field out of a (Sum-of-)Product type0)Specialise an application on its argument1)Specialise an application on its argument4=Create binders and variable references for free variables in specArgName of the transformationTransformation to be appliedName of the transformationTransformation to performTerm to transform TyCon cacheName of the new binder Term to bind TyCon cacheName of the new binderType or Term to bindName of the identifier Property test  of the local binder'Expression in which the binder is bound!Function to checkExpression to check it in#Let-binders to substitute*Let-binders where substitution takes place)Expression where substitution takes place% Property testTest whether to lift or inline True: inline False: lift'Name of the functionTerm bound to the function6Name with a proper unique and the type of the function+String representable,String representable/#Name of the caller of this function TyCon cacheSubject of the case-composition0"Lens into previous specialisations$Lens into the specialisation history"Lens into the specialisation limit1"Lens into previous specialisations Lens into specialisation history"Lens into the specialisation limit Original term@Function part of the term, split into root and applied argumentsArgument to specialize on# !"#$%&'()*+,-./01234# !"#$%&'()*+,-./01234#(C) 2012-2016, University of TwenteBSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>NoneVs 51Apply a transformation on the subtrees of an term6'Apply two transformations in succession7JApply two transformations in succession, and perform a deepseq in between.8-Apply a transformation in a topdown traversal9OApply a transformation in a topdown traversal. Doesn't freshen bound variables:.Apply a transformation in a bottomup traversal;PApply a transformation in a bottomup traversal. Doesn't freshen bound variables<?Only apply the second transformation if the first one succeeds.=<Only apply the second transformation if the first one fails.>.Keep applying a transformation until it fails.@<Only traverse downwards when the assertion evaluates to true5/Freshen variable references in abstracted terms+The transformation to apply to the subtrees 56789:;<=>?@ 56789:;<=>?@6676<5=5 O(C) 2012-2016, University of Twente, 2017, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>NoneA State of the TCGlobal bindersD*Cache of previously specialised functions:NKey: (name of the original function, argument position, specialised term/type)AElem: (name of specialised function,type of specialised function)E2Cache of how many times a function was specializedFNumber of time a function f can be specializedG,Cache of function where inlining took place:'Key: function where inlining took place=Elem: (functions which were inlined, number of times inlined)HNumber of times a function f can be inlined in a function gIKSize of a function below which it is always inlined if it is not recursiveJASize of a constant below which it is always inlined; 0 = no limitKPrimitive DefinitionsL8Map telling whether a components is recursively defined.NNB: there are only no mutually-recursive component, only self-recursive ones.MDescription of a Term' in terms of the type "components" the Term has.%Is used as a performance/size metric.ONumber of functionsPNumber of primitivesQ!Number of selections/multiplexersRA  Transform action in the context of the  and TS3RewriteSession with extra Normalisation informationT?State monad that stores specialisation and inlining information!ABLJIHGFEDCKMNQPORSTUVWXYZ[\]^`ab!ABCDEFGHIJKL^]\[ZYXWVUTSRMNOPQba`A BCDEFGHIJKLMNOPQ!#(C) 2012-2016, University of TwenteBSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None"#]3 c?A call graph counts the number of occurrences that a functions g is used in f.dADetermine if a function is already inlined in the context of the  NetlistMonadf(Specialize under the Normalization MonadgDetermine if a term is closedh)Determine if a term represents a constantj;Assert whether a name is a reference to a recursive binder.k=Create a call graph for a set of global binders, given a rootlFGive a "performance/size" classification of a function in normal form.m;Determine whether a function adds a lot of hardware or not.MIt is considered expensive when it has 2 or more of the following components: functions primitivesselections (multiplexers)dFunction we want to inline1Function in which we want to perform the inliningeFunction we want to inline1Function in which we want to perform the inlining cdefghijklm defghijcklm"(C) 2012-2016, University of Twente, 2016-2017, Myrtle Software Ltd, 2017 , Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None"#%Nn2Generate the context for a BlackBox instantiation.rCreate an template instantiation text and a partial blackbox content for an argument term, given that the term is a function. Errors if the term is not a functionn5Identifier binding the primitive/blackbox application/Arguments of the primitive/blackbox applicationpLHS of the original let-binderq&Put BlackBox expression in parenthesis(Treat BlackBox expression as declarationId to assign the result torBIdentifier binding the encompassing primitive/blackbox applicationThe function argument termnopqrstnopqrst(C) 2012-2016, University of Twente, 2016-2017, Myrtle Software Ltd, 2017 , Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None"#%N( 'xGenerate a list of Declarations for a let-binder, return an empty list if the bound expression is represented by 0 bits)WGenerate a declaration that selects an alternative based on the value of the scrutinee*GGenerate an expression that projects a field out of a data-constructor.6Works for both product types, as sum-of-product types.+UGenerate an expression for a DataCon application occurring on the RHS of a let-binder,FGenerate an expression for a term occurring on the RHS of a let-binder-3Generate a component for a given function (caching)uEGenerate a hierarchical netlist out of a set of global binders with  topEntity at the top.v0Run a NetlistMonad action in a given environmentx)Generate a component for a given functiony0Generate a list of Declarations for a let-binderzXGenerate a list of Declarations for a let-binder where the RHS is a function application 'LHS of the let-binderRHS of the let-binder*)Projection must bind to a simple variable<The signal to which the projection is (potentially) assigned'The subject/scrutinee of the projectionThe type of the resultThe field to be projected+#HWType of the LHS of the let-binderId to assign the result toApplied DataConDataCon Arguments@Returned expression and a list of generate BlackBox declarations,(Treat BlackBox expression as declarationId to assign the result to!Type of the LHS of the let-binder Term to convert to an expression@Returned expression and a list of generate BlackBox declarations-Name of the functionu Global bindersAll the TopEntitiesPrimitive definitions TyCon cache#Hardcoded Type -> HWType translatorSet of collected data-filesIntWordInteger bit-widthvalid identifiersextend valid identifiers Seen components HDL dir  Name of the  topEntityv Global bindersTopEntity annotationsPrimitive Definitions TyCon cache"Hardcode Type -> HWType translatorSet of collected data-filesIntWordInteger bit-widthvalid identifiersextend valid identifiers Seen components HDL dir  Action to runxName of the functionCorresponding termyLHS of the let-binderRHS of the let-binderzLHS of the let-binderName of the applied functionFunction arguments'()*+,-uvwxyz{uvw-x('y)z{,*+#W(C) 2015-2016, University of Twente, 2016 , Myrtle Software LtdBSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None% |Replace an application of the Clash.Sized.Vector.zipWith) primitive on vectors of a known length n3, by the fully unrolled recursive "definition" of Clash.Sized.Vector.zipWith}Replace an application of the Clash.Sized.Vector.map) primitive on vectors of a known length n3, by the fully unrolled recursive "definition" of Clash.Sized.Vector.map~Replace an application of the Clash.Sized.Vector.imap) primitive on vectors of a known length n3, by the fully unrolled recursive "definition" of Clash.Sized.Vector.imapReplace an application of the Clash.Sized.Vector.traverse#) primitive on vectors of a known length n3, by the fully unrolled recursive "definition" of Clash.Sized.Vector.traverse#Create the traversable vectore.g. for a length '2' input vector, we get *(:>) <$> x0 <*> ((:>) <$> x1 <*> pure Nil)Replace an application of the Clash.Sized.Vector.foldr) primitive on vectors of a known length n3, by the fully unrolled recursive "definition" of Clash.Sized.Vector.foldrReplace an application of the Clash.Sized.Vector.fold) primitive on vectors of a known length n3, by the fully unrolled recursive "definition" of Clash.Sized.Vector.foldReplace an application of the Clash.Sized.Vector.dfold) primitive on vectors of a known length n3, by the fully unrolled recursive "definition" of Clash.Sized.Vector.dfoldReplace an application of the Clash.Sized.Vector.head) primitive on vectors of a known length n4, by a projection of the first element of a vector.Replace an application of the Clash.Sized.Vector.tail) primitive on vectors of a known length n+, by a projection of the tail of a vector.Replace an application of the Clash.Sized.Vector.last) primitive on vectors of a known length n3, by a projection of the last element of a vector.Replace an application of the Clash.Sized.Vector.init) primitive on vectors of a known length n+, by a projection of the init of a vector.Replace an application of the Clash.Sized.Vector.(++)) primitive on vectors of a known length n3, by the fully unrolled recursive "definition" of Clash.Sized.Vector.(++)Replace an application of the Clash.Sized.Vector.unconcat) primitive on vectors of a known length n3, by the fully unrolled recursive "definition" of Clash.Sized.Vector.unconcatReplace an application of the Clash.Sized.Vector.transpose) primitive on vectors of a known length n3, by the fully unrolled recursive "definition" of Clash.Sized.Vector.transposeReplace an application of the Clash.Sized.Vector.dtfold) primitive on vectors of a known length n3, by the fully unrolled recursive "definition" of Clash.Sized.Vector.dtfoldReplace an application of the Clash.Sized.RTree.tdfold& primitive on trees of a known depth n3, by the fully unrolled recursive "definition" of Clash.Sized.RTree.tdfold|Length of the vector(s)Type of the lhs of the functionType of the rhs of the function"Type of the result of the functionThe zipWith'd functionsThe 1st vector argumentThe 2nd vector argument}Length of the vectorArgument type of the functionResult type of the functionThe map'd functionThe map'd over vector~Length of the vectorArgument type of the functionResult type of the functionThe imap'd functionThe imap'd over vectorLength of the vector#Element type of the argument vectorThe type of the applicative!Element type of the result vectorThe  Applicative dictionaryThe function to traverse withThe argument vector Vec tconNil conCons con( term) term termb tyLength of the vectorElements of the vectorLength of the vector#Element type of the argument vectorThe function to fold withThe starting valueThe argument vectorLength of the vector#Element type of the argument vectorThe function to fold withThe argument vectorLength of the vector#Element type of the argument vectorFunction to fold withStarting valueThe vector to foldLength of the vectorElement type of the vectorThe argument vectorLength of the vectorElement type of the vectorThe argument vectorLength of the vectorElement type of the vectorThe argument vectorLength of the vectorElement type of the vectorThe argument vectorLength of the LHS argLenght of the RHS argElement type of the vectorsThe LHS argumentThe RHS argumentLength of the result vector+Length of the elements of the result vector Element typeArgument vectorLength of the result vector+Length of the elements of the result vector Element typeArgument vectorLength of the vector#Element type of the argument vector!Function to convert elements with!Function to combine branches withThe vector to foldDepth of the tree!Element type of the argument tree!Function to convert elements with!Function to combine branches withThe tree to foldDepth of the tree Element type Result typeElement|}~|}~$#(C) 2015-2016, University of TwenteBSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None%35LNXI  Test if a  collected from an expression indicates that application of a global binder is disjoint: occur in separate branches of a case-expression.7Test if all elements in a list are equal to each other.Collect s for (potentially) disjoint applications of globals out of an expression. Also substitute truly disjoint applications of globals by a reference to a lifted out application.Collect s for (potentially) disjoint applications of globals out of a list of application arguments. Also substitute truly disjoint applications of globals by a reference to a lifted out application.Collect s for (potentially) disjoint applications of globals out of a list of alternatives. Also substitute truly disjoint applications of globals by a reference to a lifted out application.Collect s for (potentially) disjoint applications of globals out of a list of let-bindings. Also substitute truly disjoint applications of globals by a reference to a lifted out application.Given a case-tree corresponding to a disjoint interesting "term-in-a- function-position", return a let-expression: where the let-binding holds a case-expression selecting between the uncommon arguments of the case-tree, and the body is an application of the term applied to the common arguments of the case tree, and projections of let-binding corresponding to the uncommon argument positions.{Create a single selector for all the representable uncommon arguments by selecting between tuples. This selector is only (j) created when the number of representable uncommmon arguments is larger than one, otherwise it is not ().It also returns:<For all the non-representable uncommon arguments: a selectorFor all the representable uncommon arguments: a projection out of the tuple created by the larger selector. If this larger selector does not exist, a single selector is created for the single representable uncommon argument.aCreate a list of arguments given a map of positions to common arguments, and a list of argumentsWCreate a case-expression that selects between the uncommon arguments given a case-tree_Determine if a term in a function position is interesting to lift out of of a case-expression.]This holds for all global functions, and certain primitives. Currently those primitives are:$All non-power-of-two multiplications<All division-like operations with a non-power-of-two divisor SSubstitution of (applications of) a global binder by a reference to a lifted term.#List of already seen global bindersThe expressionSSubstitution of (applications of) a global binder by a reference to a lifted term.#List of already seen global bindersThe list of argumentsSSubstitution of (applications of) a global binder by a reference to a lifted term.#List of already seen global bindersThe subject termThe list of alternativesSSubstitution of (applications of) a global binder by a reference to a lifted term.#List of already seen global bindersThe list let-bindingsCurrent free variables.5Case-tree of arguments belonging to the applied term.Types of the argumentsCurrent position$map from position to common argument$(projections for) uncommon argumentsType of the alternatives"DataCon to pack multiple argumentsTypes of the argumentsCaseTree of argumentsin scope EvaluatorTerm in function position Arguments%(C) 2012-2016, University of Twente, 2016-2017, Myrtle Software Ltd, 2017 , Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None%]"Specialize functions on their type8Specialize functions on their non-representable argument@Lift the let-bindings out of the subject of a Case-decompositionVMove a Case-decomposition from the subject of a Case-decomposition to the alternatives\Inline function with a non-representable result if it's the subject of a Case-decompositionSpecialize a Case-decomposition (replace by the RHS of an alternative) if the subject is (an application of) a DataCon; or if there is only a single alternative that doesn't reference variables bound by the pattern.lBring an application of a DataCon or Primitive in ANF, when the argument is is considered non-representablekEnsure that top-level lambda's eventually bind a let-expression of which the body is a variable-reference.Remove unused let-bindingsxInline let-bindings when the RHS is either a local variable reference or is constant (except clock or reset generators)/Push a cast over a case into it's alternatives.(Push a cast over a Letrec into it's body:Push cast over an argument to a funtion into that function@This is done by specializing on the casted argument. Example: ) y = f (cast a) where f x = g x  transforms to: 6 y = f' a where f' x' = (x -> g x) (cast x') &Only inline casts that just contain a G, because these are guaranteed work-free. These are the result of the  transformation.TEliminate two back to back casts where the type going in and coming out are the same 0 (cast :: b -> a) $ (cast :: a -> b) x ==> x DMake a cast work-free by splitting the work of to a separate binding 9let x = cast (f a b) ==> let x = cast x' x' = f a b UInline work-free functions, i.e. fully applied functions that evaluate to a constantInline small functionseSpecialise functions on arguments which are constant, except when they are clock or reset generators7Propagate arguments of application inwards; except for ' where the argument becomes let-bound.3Flatten ridiculous case-statements generated by GHC+For case-statements in haskell of the form: Rf :: Unsigned 4 -> Unsigned 4 f x = case x of 0 -> 3 1 -> 2 2 -> 1 3 -> 0 #GHC generates Core that looks like: f = (x :: Unsigned 4) -> case x == fromInteger 3 of False -> case x == fromInteger 2 of False -> case x == fromInteger 1 of False -> case x == fromInteger 0 of False -> error "incomplete case" True -> fromInteger 3 True -> fromInteger 2 True -> fromInteger 1 True -> fromInteger 0 ]Which would result in a priority decoder circuit where a normal decoder circuit was desired.;This transformation transforms the above Core to the saner: f = (x :: Unsigned 4) -> case x of _ -> error "incomplete case" 0 -> fromInteger 3 1 -> fromInteger 2 2 -> fromInteger 1 3 -> fromInteger 0 lTurn an expression into a modified ANF-form. As opposed to standard ANF, constants do not become let-bound.9Eta-expand top-level lambda's (DON'T use in a traversal!)Turn a normalized recursive function, where the recursive calls only pass along the unchanged original arguments, into let-recursive function. This means that all recursive calls are replaced by the same variable reference as found in the body of the top-level let-expression.+Inline a function with functional argumentsDSimplified CSE, only works on let-bindings, works from top to bottomReplace primitives by their "definition" if they would lead to let-bindings with a non-representable type when a function is in ANF. This happens for example when Clash.Size.Vector.map consumes or produces a vector of non-representable elements.Basically what this transformation does is replace a primitive the completely unrolled recursive definition that it represents. e.g. 8zipWith ($) (xs :: Vec 2 (Int -> Int)) (ys :: Vec 2 Int)is replaced by: let (x0 :: (Int -> Int)) = case xs of (:>) _ x xr -> x (xr0 :: Vec 1 (Int -> Int)) = case xs of (:>) _ x xr -> xr (x1 :: (Int -> Int)( = case xr0 of (:>) _ x xr -> x (y0 :: Int) = case ys of (:>) _ y yr -> y (yr0 :: Vec 1 Int) = case ys of (:>) _ y yr -> xr (y1 :: Int = case yr0 of (:>) _ y yr -> y in (($) x0 y0 :> ($) x1 y1 :> Nil)3Currently, it only handles the following functions: Clash.Sized.Vector.mapClash.Sized.Vector.zipWithClash.Sized.Vector.traverse#Clash.Sized.Vector.foldrClash.Sized.Vector.foldClash.Sized.Vector.dfoldClash.Sized.Vector.(++)Clash.Sized.Vector.headClash.Sized.Vector.tailClash.Sized.Vector.unconcatClash.Sized.Vector.transposeClash.Sized.Vector.replicateClash.Sized.Vector.dtfoldaThis transformation lifts applications of global binders out of alternatives of case-statements.e.g. It converts: /case x of A -> f 3 y B -> f x x C -> h x into: let f_arg0 = case x of {A -> 3; B -> x} f_arg1 = case x of {A -> y; B -> x} f_out = f f_arg0 f_arg1 in case x of A -> f_out B -> f_out C -> h x TGiven a function in the desired normal form, inline all the following let-bindings:Let-bindings with an internal name that is only used once, where it binds: * a primitive that will be translated to an HDL expression (as opposed to a HDL declaration) * a projection case-expression (1 alternative) * a data constructorFlatten's letrecs after 0 sometimes exposes additional possibilities for {, which then introduces let-bindings in what should be ANF. This transformation flattens those nested let-bindings again.1NB: must only be called in the cleaning up phase.!!&#(C) 2012-2016, University of TwenteBSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>NoneNormalisation transformation+Topdown traversal, stops upon first success'(C) 2012-2016, University of Twente, 2016 , Myrtle Software Ltd, 2017 , Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>None%ٚ-Run a NormalizeSession in a given environment7Rewrite a term according to the provided transformationiCheck whether the normalized bindings are non-recursive. Errors when one of the components is recursive.`Perform general "clean up" of the normalized (non-recursive) function hierarchy. This includes:6Inlining functions that simply "wrap" another functionClash's clock and reset domain annotations prevent most accidental meta-stability situations. That is, unless the developer uses the functions marked "unsafe", the type system will prevent things like illegal clock domain crossing, or improper use of asynchronous resets.oHowever, this all depends on clock and resets being unique. With explicit clocks and resets, it is possible to have multiple clock and reset arguments that are annotated with the same domain. If these arguments aren't connected to the same source, we can still get metastability due to either illegal clock domain crossing, or improper use of asynchronous resets.The following situations are reported: * There are 2 or more clock arguments in scope that have the same clock domain annotation. * There are 2 or more reset arguments in scope that have the same reset domain annotation, and at least one of them is an asynchronous reset.  Level of debug messages to print UniqueSupplyGlobal Binders#Hardcoded Type -> HWType translator TyCon cacheTuple TyCon cache%Hardcoded evaluator (delta-reduction)Primitive Definitions=Map telling whether a components is part of a recursive group  topEntities NormalizeSession to runTransformation to applyTerm to transformList of normalized bindersVisitedGlobal bindersRoot of the call graph((C) 2012-2016, University of Twente, 2016-2017, Myrtle Software Ltd, 2017 , QBayLogic, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij <christiaan.baaij@gmail.com>NoneNVZ7Create a set of target HDL files for a set of functions(Pretty print Components to HDL DocumentsPrepares the directory for writing HDL files. This means creating the dir if it does not exist and removing all existing .hdl files from it.(Writes a HDL file to the given directory/Get all the terms corresponding to a call graphNormalize a complete hierarchySet of functions Primitive / BlackBox Definitions TyCon cacheTuple TyCon cache Hardcoded  ->  translator%Hardcoded evaluator (delta-reduction)HtopEntity bndr + (maybe) TopEntity annotation + (maybe) testBench bndr5Debug information level for the normalization processBackendModule hierarchy rootList of components Top component^Name of the manifest file + Either: * Left manifest: Only write/update the hashes of the manifest/ * Right manifest: Update all fields of the manifest<The pretty-printed HDL documents + The update manifest fileRemove existing HDL files File extension of the HDL files. All bindingsRoot of the call graph  All bindingsBlackBox HDL templates TyCon cacheTuple TyCon cache Hardcoded  ->  translator%Hardcoded evaluator (delta-reduction) TopEntities5Debug information level for the normalization process Unique supply root of the hierarchy9:;9:<=>?@ABCCDEFGHIJKLMNOPQRSTUVWXYZ[@\]^_`abcdefghijklmnopqrsrtuvwxyz{|}~              K                      !"#$ % & ' ( ) * + K ,  - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D EFGHIJKLM N O P Q R  S T U V W X R Y Z O [ \ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~       JT  !    !"#$%&'t()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~78x*      " !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOP Q Q R S T U V W X Y  Z [ [ \ ] ^ _ ` a b c d e f  g h i j k l m n!o!p!q!r!s!t!u!v!w!x!y"z"{"|"}"~""####################$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&&&&&'''''''''''''''((((((((****,,,,,,, , , , , ,,,,,,,,,,,,,,,,,,,, ,!,",#,$,%,&,',(,),*,+/,/-/.///0/1/2/3456789:;<=<>01020?@ABCDEFGHIJKLMNOPQRST U V WXYZ[\]^_`abcdefghijklmnolpqrsteguivwjxmnoabqcdeguhyijklz{|}$~$$$$$$$$$$$%clash-lib-0.99-CApG5XjEMCZFUVyS8kIjXvClash.Core.NameClash.Driver.Types Clash.UtilClash.Netlist.BlackBox.TypesClash.Netlist.BlackBox.ParserClash.Netlist.IdClash.Primitives.TypesClash.Primitives.UtilClash.Core.TyConClash.Core.TermClash.Core.TypeClash.Core.VarClash.Core.DataConClash.Core.TysPrimClash.Core.LiteralClash.Core.SubstClash.Netlist.Types Clash.Backend Clash.NetlistClash.Core.FreeVarsClash.Core.PrettyClash.Core.UtilClash.Netlist.UtilClash.Netlist.BlackBox.UtilClash.Backend.VerilogClash.Backend.VHDLClash.Backend.SystemVerilogClash.Core.EvaluatorClash.Rewrite.TypesClash.Rewrite.UtilClash.Rewrite.CombinatorsClash.Normalize.TypesClash.Normalize.UtilClash.Netlist.BlackBox#Clash.Normalize.PrimitiveReductionsClash.Normalize.DECClash.Normalize.TransformationsClash.Normalize.StrategyClash.Normalize Clash.Driver!Clash.Annotations.TopEntity.ExtraData.Aeson.ExtraData.Semigroup.Monad.ExtraData.Text.Prettyprint.Doc.ExtraGHC.BasicTypes.ExtraGHC.SrcLoc.ExtraPaths_clash_lib Control.Arrowfirstsecond Data.List partition mapAccumL&Unbound.Generics.LocallyNameless.ExtraClash.Netlist.VHDLVHDLMghcSrcLoc noSrcSpanSrcSpan"lens-4.16.1-FxuhmFSRQ1UI2TaNU59f9pControl.Lens.TH makeLensesHdlSynVivadoOtherDeclElementCDOINLVarSymTypTypMErrTypElemCompName IncludeName IndexTypeSizeLengthDepthFilePathGenIFAndIW64BVIsLitIsVarIsGatedIsSyncStrCmp OutputWireRegVarsGenSymSigDBlackBoxTemplate $fEqHdlSyn $fShowHdlSyn $fReadHdlSyn $fShowElement $fShowDeclrunParseIdTypeBasicExtended mkBasicId'stripDollarPrefixes PrimitiveBlackBoxname outputReglibraryimportsincludetemplateprimTypePrimMap$fFromJSONPrimitive$fShowPrimitive MonadUnique getUniqueMcurLoc makeCached makeCachedT3 makeCachedT3S liftStatefirstMsecondMcombineMtraceIf partitionM mapAccumLMdot ifThenElse<:> indexMaybe indexNote splitAtListclashLibVersionflogBaseclogBase$fMonadUniqueStateTparsePrimitivegeneratePrimMapNameSortUserSystemInternalOccNameNamenameSortnameOccnameLoc $fAlphaName $fOrdName$fEqName $fEqNameSort $fOrdNameSort$fShowNameSort$fGenericNameSort$fNFDataNameSort$fHashableNameSort $fShowName $fGenericName $fNFDataName$fHashableName name2String name2Integerstring2OccNamestring2SystemNamestring2InternalName makeOccNamemakeSystemName coerceName appendToName $fSubstbName$fAlphaNameSort TyConOccName TyConNameTyConTmNameTerm KiOccNameKiName TyOccNameTyNameKindType mkTyConTyTyVarIdvarNamevarKindvarType modifyVarName$fSubstTypeVar$fSubstTermVar $fAlphaVar$fEqVar $fShowVar $fGenericVar $fNFDataVar $fHashableVarDcNameConTagDataConMkDatadcNamedcTagdcType dcUnivTyVars dcExtTyVarsdcArgTysdataConInstArgTys$fSubstaDataCon$fAlphaDataCon $fOrdDataCon $fEqDataCon $fShowDataCon$fGenericDataCon$fNFDataDataCon$fHashableDataCon AlgTyConRhs DataTyConNewTyCondataConsdataCon ntEtadRhsTyConMapAlgTyConFunTyCon PrimTyConSuperKindTyCon tyConName tyConKind tyConArityalgTcRhs tyConSubst mkKindTyConisTupleTyConLike tyConDataCons $fAlphaTyCon $fOrdTyCon $fEqTyCon $fShowTyCon$fShowAlgTyConRhs$fGenericAlgTyConRhs$fNFDataAlgTyConRhs$fAlphaAlgTyConRhs$fGenericTyCon $fNFDataTyConliftedTypeKind typeNatKindtypeSymbolKind intPrimTy integerPrimTy charPrimTy stringPrimTy voidPrimTy wordPrimTy int64PrimTy word64PrimTy floatPrimTy doublePrimTy naturalPrimTy tysPrimMapLiteralIntegerLiteral IntLiteral WordLiteral Int64Literal Word64Literal StringLiteral FloatLiteral DoubleLiteral CharLiteralNaturalLiteral literalType$fSubstaLiteral$fAlphaLiteral $fEqLiteral $fOrdLiteral $fShowLiteral$fGenericLiteral$fNFDataLiteral$fHashableLiteralAltPatDataPatLitPat DefaultPat LetBinding TmOccNameDataPrimLamTyLamAppTyAppLetrecCaseCast$fSubstTypeTerm$fSubstTermTerm$fSubstTermPat$fSubstTypePat $fAlphaTerm $fOrdTerm$fEqTerm$fEqPat $fShowPat $fGenericPat $fNFDataPat $fAlphaPat $fHashablePat $fShowTerm $fGenericTerm $fNFDataTerm$fHashableTermsubstTyssubstTy substKindWith substTyInTm substTysinTmsubstTmsubstTms substBndr KindOrTypeLitTyNumTySymTyConstTyArrowTypeViewFunTyTyConApp OtherTypeVarTyForAllTyAppTytyViewcoreViewmkFunTy mkTyConAppsplitTyConAppMtypeKindisPolyTy splitFunTy splitFunTyssplitFunForallTysplitCoreFunForallTy isPolyFunTyisPolyFunCoreTyisFunTy applyFunTyapplyTy findFunSubstreduceTypeFamily undefinedTy isIntegerTy normalizeType $fSubstaLitTy $fOrdType$fEqType$fSubstTypeType$fSubstTermType$fSubstaConstTy $fAlphaType $fShowLitTy$fGenericLitTy $fNFDataLitTy $fAlphaLitTy$fHashableLitTy $fShowType $fGenericType $fNFDataType$fHashableType $fShowConstTy$fGenericConstTy$fNFDataConstTy$fAlphaConstTy$fHashableConstTy$fShowTypeViewManifest manifestHash portInNames portInTypes portOutNames portOutTypescomponentNamesClashException ClashOptsopt_inlineLimit opt_specLimitopt_inlineFunctionLimitopt_inlineConstantLimit opt_dbgLevel opt_cachehdl opt_cleanhdl opt_intWidth opt_hdlDir opt_hdlSynopt_errorExtraopt_floatSupport opt_allowZeroopt_importPaths DebugLevel DebugNone DebugFinal DebugName DebugAppliedDebugAll BindingMap$fExceptionClashException$fShowClashException$fEqDebugLevel$fOrdDebugLevel$fReadDebugLevel$fShowManifest$fReadManifestBlackBoxContextContextbbResultbbInputs bbFunctions bbQsysIncNameBitHUZNumLitBitLitBoolLitVecLit StringLitExpr IdentifierDataTag BlackBoxEConvBVModifierIndexedDC VecAppend RTreeAppendNested PortDirectionInOut WireOrRegWireReg Declaration AssignmentCondAssignmentInstDecl BlackBoxDNetDecl'HWTypeVoidStringBool BitVectorIndexSignedUnsignedVectorRTreeSumProductSPClockReset Component componentNameinputsoutputs declarations NetlistState _bindings _varCount _components _primitives_typeTranslator_tcCache _curCompNm _dataFiles _intWidth_mkIdentifierFn_extendIdentifierFn_seenIds _seenComps_componentNames_topEntityAnns_hdlDir NetlistMonad runNetlistNetDeclemptyBBContext$fHashableResetKind$fHashableClockKind$fNFDataHWType$fHashableHWType$fNFDataWireOrReg$fNFDataDeclaration$fNFDataComponent $fEqHWType $fOrdHWType $fShowHWType$fGenericHWType$fShowWireOrReg$fGenericWireOrReg$fShowPortDirection$fShowModifier$fEqBit $fShowBit$fShowBlackBoxContext $fShowExpr$fShowDeclaration$fShowComponent$fFunctorNetlistMonad$fMonadNetlistMonad$fApplicativeNetlistMonad$fMonadStateNetlistMonad$fFreshNetlistMonad$fMonadIONetlistMonadbindings components curCompNm dataFilesextendIdentifierFnhdlDirintWidthmkIdentifierFn primitives seenCompsseenIdstcCache topEntityAnnstypeTranslatorvarCountBackend initBackendhdlKindprimDirs extension extractTypesgenHDL mkTyPackagehdlTypehdlTypeErrValue hdlTypeMarkhdlSiggenStmtinstexpriwWidthtoBVfromBVhdlSyn mkIdentifierextendIdentifier setModName setSrcSpan getSrcSpan blockDeclunextend addInclude addLibraries addImportsUsageExternalModNamenestMescapeTemplatemkDeclarations mkNetDecl mkSelection mkProjectionmkDcApplicationmkExpr genComponent typeFreeVars termFreeIdstermFreeTyVarsPrettypprpprPrecshowDoc$fPrettyLiteral$fPrettyDataCon $fPrettyVar $fPrettyTerm $fPrettyLitTy $fPrettyTyCon $fPrettyVar0 $fPrettyType $fPrettyText $fPretty(,) $fPretty[] $fPrettyName $fPrettyName0 $fPrettyPat $fEqTypePrec $fOrdTypePrecDeltaGammatermType collectArgs collectBndrsapplyTypeToArgspatIdsmkTyVarmkId mkAbstractionmkTyLamsmkLamsmkAppsmkTmAppsmkTyAppsisFun isPolyFunisLamisLetisVarisConisPrimidToVarvarToIdtermSizemkVec appendToVec extractElems extractTElemsmkRTree isSignalTypeisClockOrReset tyNatSizeisVoidsplitNormalizedunsafeCoreTypeToHWTypeunsafeCoreTypeToHWTypeMcoreTypeToHWTypeMsynchronizedClkcoreTypeToHWTypemkADT isRecursiveTyrepresentableTypetypeSizeconSize typeLength termHWType termHWTypeMmkUniqueNormalizedmkUniqueArgumentsmkUniqueResultidToPortrepNamemkUniquemkUniqueIdentifierpreserveVarEnv dcToLiteral extendPorts appendNumberportNameappendIdentifieruniquePortNamemkInput filterVoid mkVectorChain mkRTreeChaingenComponentNamemkOutputmkTopUnWrapperargBVresBVdoConv mkTopInput mkTopOutputconcatPortDecls3verifyBlackBoxContextextractLiteralssetSym setCompNamefindAndSetDataFilesrenderFilePathrenderTemplaterenderBlackBox setSimpleVar renderElem parseFailidToExprlineToIdentifier lineToType renderTag exprToTextprettyBlackBox prettyElem usedArguments VerilogState$fBackendVerilogState VHDLState$fBackendVHDLStateSystemVerilogState$fBackendSystemVerilogState PrimEvaluatorStateValueLambdaTyLambdaLitPrimVal StackFrameUpdateApply Instantiate PrimApply ScrutiniseStackPureHeapHeapwhnf'whnfisScrut unwindStackstep newLetBindingnewLetBindings'mkAbstrforceunwindupdate valToTermtoVartoTypeapply instantiateprimop scrutinisematchLitsubstAltallocateletSubst uniqueInHeap$fPrettyStackFrame $fShowHeap $fShowValue$fShowStackFrame RewriteState_transformCounter _uniqSupply_curFun _nameCounter_extra CoreContextAppFunAppArgTyAppCLetBodyLamBody TyLamBodyCaseAlt CaseScrutCastBody$fEqCoreContext$fShowCoreContext RewriteEnv _dbgLevel _tupleTcCache _evaluator _allowZero _topEntitiescurFunextra nameCountertransformCounter uniqSupplyRewrite Transform RewriteMonadRrunR allowZerodbgLevel evaluator topEntities tupleTcCache$fMonadFixRewriteMonad#$fMonadReaderRewriteEnvRewriteMonad$fMonadWriterAnyRewriteMonad$fMonadUniqueRewriteMonad$fFreshRewriteMonad$$fMonadStateRewriteStateRewriteMonad$fMonadRewriteMonad$fApplicativeRewriteMonad$fFunctorRewriteMonad zoomExtra runRewriterunRewriteSession setChangedchanged contextEnvclosestLetBinder mkDerivedNamemkEnv mkTmBinderFor mkBinderFor mkInternalVar inlineBinders isJoinPointIn tailCalls isVoidWrappersubstituteBinders localFreeIdsinlineOrLiftBinders liftBinding mkFunction addGlobalBindcloneVar isLocalVarisUntranslatableisUntranslatableTypeisLambdaBodyCtxmkWildValBindermkSelectorCase specialise specialise'normalizeTermTypes normalizeIdspecArgBndrsAndVarsallR>->>-!->topdownRunsafeTopdownR bottomupRunsafeBottomupR!->>-!repeatRwhenR bottomupWhenRNormalizeState _normalized_specialisationCache_specialisationHistory_specialisationLimit_inlineHistory _inlineLimit_inlineFunctionLimit_inlineConstantLimit_recursiveComponentsTermClassification _function _primitive _selection NormRewriteNormalizeSessionNormalizeMonadinlineConstantLimitinlineFunctionLimit inlineHistory inlineLimit normalizedrecursiveComponentsspecialisationCachespecialisationHistoryspecialisationLimit$fShowTermClassificationfunction primitive selection CallGraphalreadyInlined addNewInlinespecializeNormisClosed isConstantisConstantNotClockResetisRecursiveBndr callGraphclassifyFunctionisCheapFunctionmkBlackBoxContextprepareBlackBox mkArgument mkPrimitive mkFunInputinstantiateCompNamecollectFilePaths genNetlistrunNetlistMonadgenNames genComponentTmkDeclarations'mkFunApp toSimpleVar reduceZipWith reduceMap reduceImapreduceTraverse mkTravVec reduceFoldr reduceFold reduceDFold reduceHead reduceTail reduceLast reduceInit reduceAppendreduceUnconcatreduceTransposereduceReplicate reduceDTFold reduceTFoldreduceTReplicate buildSNat isDisjointcollectGlobalsmkDisjointGroup $fEqCaseTree$fShowCaseTree$fFunctorCaseTree$fFoldableCaseTreeinlineOrLiftNonReptypeSpec nonRepSpeccaseLetcaseCase inlineNonRepcaseCon nonRepANFtopLetdeadCoderemoveUnusedExprbindConstantVarcaseCastletCast argCastSpec inlineCasteliminateCastCast splitCastWorkinlineWorkFree inlineSmall constantSpecappPropcaseFlatmakeANFetaExpansionTL recToLetRecinlineHO simpleCSE reduceConstreduceNonRepPrimdisjointExpressionConsolidation inlineCleanup flattenLet normalizationconstantPropgation topdownSucR innerMost applyManyCallTreeCLeafCBranchrunNormalization normalize normalize' rewriteExprcheckNonRecursive cleanupGraph mkCallTree stripArgs flattenNodeflattenCallTreecallTreeToListclockResetErrors generateHDL createHDL prepareDirwriteHDL copyDataFilescallGraphBindingsnormalizeEntity pBlackBoxDpElementpTextpTagDpDeclpOutputpInputpTagE brackets' pBlackBoxEpElemEpSigD genLineErr decodeOrErrbaseGHC.BaseNothingreplaceCommonEscapes genLineErr'%reducers-3.12.2-I9xH7Apoj90wo6pY6NNV4Data.Semigroup.MonadAction getActionMongetMon,prettyprinter-1.2.0.1-7ZuCLms8xajGeu88e33QHe%Data.Text.Prettyprint.Doc.Render.Text renderLazy"Data.Text.Prettyprint.Doc.Internal layoutCompact layoutPretty PageWidthAvailablePerLine Unbounded LayoutOptionslayoutPageWidthDoc layoutOneLine renderOneLineintintegercharlbracerbracecolonsemiequalscommalparenrparenspacebracketsbracestupled<+>vcathcatnestindentparensemptyDoc punctuate encloseSeplineline'softline softline'prettystringsquotesdquotesalignvsepisEmptyfillcolumnnestingversion getBinDir getLibDir getDynLibDir getDataDir getLibexecDir getSysconfDirgetDataFileNameghc-prim GHC.TypesTrue Applicativepure<*> Data.Functor<$> Control.Monad<=<>=>*** Data.FunctionontySuperKindTyConNameliftedTypeKindTyConNametypeNatKindTyConNametypeSymbolKindTyConName tySuperKindtcliftedTypeKindtc typeNatKindtctypeSymbolKindtc intPrimTc integerPrimTc charPrimTc stringPrimTc voidPrimTc wordPrimTc int64PrimTc word64PrimTc floatPrimTc doublePrimTc naturalPrimTcnewTyConInstRhs isSuperKind splitTyAppMTypePrecTopPrecFunPrec TyConPrec BindingSite LambdaBindCaseBindLetBindVerilogM _genDepth genVerilogverilogTypeMarkverilogTypeErrValueinst_modifierexpr__idSeen_srcSpan _includes_imports_hdlsyn_tyCache_tySeen _nameCachegenVHDL mkTyPackage_vhdlType vhdlTypeMarkvhdlTypeErrValue_modNm _libraries _packagesSystemVerilogM_oports-unbound-generics-0.3.2-AgAkSv9sH94GGXlo1MkbDn&Unbound.Generics.LocallyNameless.FreshFreshfmapCaseTreeallEqualcollectGlobalsArgscollectGlobalsAltscollectGlobalsLbsdisJointSelProjJustmkDJArgsgenCaseinterestingToLiftLeafLBBranch