Clash Compiler Language User Guide
Welcome to the Clash Compiler User Guide, the official documentation of the Clash Compiler. Clash is an open-source functional hardware description language (HDL) that borrows syntax and semantics from the Haskell programming language. To learn more, we suggest reading the introduction to Clash.
The table of contents in the sidebar (which can be opened in the menu on the top left) allows easy access to different pages in the documentation. You can also use the search function in the top-left corner.
Note
The Clash Compiler and Clash Language User Guide are open-source efforts developed by QBayLogic B.V., volunteers and students. The Clash Team always appreciates feedback and contributions to the project to help improve the development experience.
If you don't understand something, or think something is missing or incorrect in the documentation you can open an issue or pull request in the GitHub repository.
Installing Clash
Check out clash-lang.org/install to install the latest stable release of Clash, or to setup a Clash project.
Introduction to Clash
Functional Hardware
Clash is an open-source functional hardware description language (HDL) that closely mirrors the syntax and semantics of the Haskell programming language. It is used for creating hardware designs, typically for running on field programmable gate arrays (FPGAs) or application-specific integrated circuits (ASICs).
Clash is both a compiler, and a set of libraries for circuit design, that transform high level Haskell descriptions of synchronous, sequential logic into low-level VHDL, Verilog, or SystemVerilog. It provides a unique approach to design of sequential circuits, with a high amount of abstraction power that blurs the line between strictly behavioral and structural synthesis approaches.
Clash aims to modernize the hardware development experience, making it easier to quickly and correctly develop complex circuit designs. This is achieved by making Clash:
Expressive
Clash uses the Haskell type system to its full potential — including modern extensions and techniques — to bring a high level of type safety and expressiveness to hardware design.
This expressive typing makes it easier to develop safe, maintainable hardware. Combinational and sequential logic is separated by type, and global safety invariants such as separating incompatible clock domains are enforced in the type system.
Intuitive
Clash makes it easy to express circuit designs in an intuitive manner, allowing high level structural components to be connected easily in designs. Moreover, unlike most "high level synthesis" tools, this extends to precise control over register placement and pipelining.
Interactive
Unlike traditional HDL tools, Clash has a fully interactive read-eval-print loop (REPL), allowing circuits to be interactively designed and tested.
Performant
Clash reuses parts of the Glasgow Haskell Compiler to provide fast simulation of circuits for development and testing.
Efficient
Clash uses a "whole program synthesis" approach in order to view the entire circuit at once, and optimizes this design before translating to a specific target. This allows meaningful optimizations to be performed on the entire design.
Extensible
Additional primitives and black boxes can be added to Clash in the language of your choice, allowing you to use your own vendor or IP library within projects.
Clash allows seamless interoperability with libraries written in Haskell, including mtl
, lens
and hedgehog
.
This makes it even easier to quickly prototype complex designs.
Intended Audience
Clash is ideal for developers from different backgrounds, although the main intended audiences are
Hardware Engineers
You are a hardware engineer, used to using tools like VHDL and Verilog to implement circuit designs. Clash offers the familiar mixed simulation/synthesis capabilities of these tools, while providing a language with powerful abstractions.
Haskell Programmers
You are a Haskell programmer, looking to start developing hardware. Clash offers the ability to start prototyping and simulating designs in a familiar environment — lowering the learning curve significantly.
Maturity and Support
Clash is a continually evolving tool, having been actively developed since 2009. With the release of Clash 1.0 there has been an increased focus on maintaining API stability between releases, meaning circuit designs written in Clash should continue to work between minor releases. Today, the Clash Compiler is actively developed by QBayLogic B.V., volunteers and students.
Several companies and enthusiasts are already using Clash to develop circuit designs, ranging from small designs on hobbyist boards to larger designs on modern FPGA and ASIC architectures.
While care is taken to thoroughly test the Clash compiler, some bugs may exist. We encourage users to file issues, or contribute pull requests on our GitHub repository.
Meta-information: Web Sites, Mailing Lists, etc.
Mailing list: for updates and questions join the mailing list clash-language+subscribe@googlegroups.com or read the forum
Slack: Invite yourself at fpchat-invite.herokuapp.com. To join #clash, click on "Channels" and search for "clash".
IRC: freenode#clash-lang
Clash Version Numbering Policy
Clash follows the Haskell PVP Specification for its version numbers, for all packages. The main libraries that make up the Clash compiler maintain the same version numbers, making it easy to identify which versions are compatible.
Note
Due to the Clash's tight integration with GHC, updates to the GHC version that Clash uses result in changes to the Clash version. As GHC's internals change frequently, even for minor bumps, it cannot be guaranteed that these changes will not result in Clash changes.
It is recommended (but not required) that downstream Clash packages and published Clash code also follow the PVP specification.
Release Notes
Clash 1.0.1
https://github.com/clash-lang/clash-compiler/releases/tag/v1.0.1
Clash 1.0.0
https://github.com/clash-lang/clash-compiler/releases/tag/v1.0.0
Frequently Asked Questions
Basic Questions
-
Q: How do I install Clash?
A: Check out the
installing
page in the Getting Started section of the manual.
-
Q: Is the name "Clash", "CLaSH", or "CλaSH"?
A: It's Clash.
In its research stages Clash was called "CλaSH", an acronym for the CAES Language for Synchronous Hardware. CAES is a group of the Faculty of Electrical Engineering, Mathematics and Computer Science at the University of Twente. Clash was originally developed by Christaan Baaij and supervisor Jan Kuper. The stylization "CλaSH" is an homage to Haskell, whose official logo has long been the venerable Greek lambda character.
-
Q: Is Clash a "high level synthesis" tool?
A: While clash provides a high level language features, hardware descriptions written in Clash are not decoupled from clock-level timing. Clash does therefore not offer what is generally understood as "high level synthesis". Compared to the big three hardware description languages, VHDL, Verilog, and SystemVerilog, Clash arguably is high-level. It offers many of the powerful abstractions that modern software programming languages offer. In fact, it inherits many of the software industry's bleeding-edge features by virtue of basing its implementation on Haskell.
Clash Support
-
Q: Is Clash production ready?
A: Clash is constantly evolving, and since the 1.0 release there is a focus on maintaining API backwards compatibility. Clash is used successfully in real-world scenarios, and QBayLogic Clash support can help with education and implementation of Clash projects.
-
Q: Will Clash work with my EDA tools?
A: In general, Clash should work well with Xilinx and Intel FPAGs and their EDA tools — as development typically focuses on these vendors. Clash has also been successfully used on Microsemi (formerly Actel) SmartFusion 2 and Lattice Semiconductor iCE40 FPGAs, and some basic IP for these exist.
For most toolchains, the default primitives supplied by Clash should work with minimal effort. If not, it is possible to call your vendor's library manually, or use a tool like Yosys to do mapping. It is also possible to consult QBayLogic Clash support for more assistance.
-
Q: Does Clash support Project IceStorm?
A: The Verilog backend for Clash emits Verilog 2001, which is supported by Yosys. This means it can be placed and packed with arachne-pnr and icestorm. Additionally, Clash has some support for the Lattice Semiconductor iCE40 FPGA.
-
Q: Can Clash be used for ASIC designs, as well as FPGA designs?
Clash can be used for ASIC designs, however the RTL produced by Clash may not be immediately suitable as it is largely platform agnostic. While this is not a problem for FPGAs, it can make developing ASICs more complicated as many ASIC vendors have different proprietary tool flows, with limited information available about their workings.
If you are using Clash to develop for ASIC, and need assistance with getting your toolchain to work, you can contact QBayLogic Clash support for assistance.
Clash and Haskell
-
Q: Is Clash its own programming language, or is it Haskell?
A: Clash is a programming language in its own right, complete with its own executable and standard library. Clash is also related to the Haskell programming language, and may be thought of as a dialect of Haskell for developing hardware. While the surface syntax and typing rules are the same, the semantics change as code progresses through the compilation pipeline.
Due to the shared behavior in the early stages of the compiler, components from GHC (the most common Haskell compiler) are reused in the Clash compiler. This is how Clash achieves such high interoperability with existing Haskell projects.
-
Q: Clash has better inference for type level natural numbers than GHC. How is this possible?
A: Clash's enhanced type checking functionality is due to the use of GHC compiler plugins, which can be used in any Haskell project. To enable these plugins, pass the following compiler flags to GHC:
{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-} {-# OPTIONS_GHC -fplugin GHC.TypeLits.Extra.Solver #-} {-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}
These plugins come from the
ghc-typelits-natnormalise
,ghc-typelits-extra
, andghc-typelits-knownnat
packages respectively, which are all available from Hackage and Stackage.
-
Q: Do I need to know Haskell in order to use Clash?
A: As Clash is deeply integrated with Haskell, it is recommended that users have some familiarity with Haskell, or functional programming in general. Clash uses some advanced features of Haskell, and real-world designs will often want to leverage the existing Haskell ecosystem.
For developers who are particularly familiar with either Haskell or hardware design, Clash should be relatively intuitive to use. Additionally, obvious mistakes with designs will be identified and reported due to the strong type system identifying mistakes at compile-time.
Clash and other HDLs
-
Q: Do I need to know existing RTL/HDL languages in order to use Clash?
A: Clash currently outputs VHDL, Verilog, and SystemVerilog. While it's not necessary to understand these descriptions, you will need to some understanding of vendor tools to actually deploy it.
-
Q: What's the difference between Clash and Lava?
A: Lava dialects (including the modern variant Blarney) are all embedded domain specific languages (EDSLs) inside Haskell. On top of that they use a so-called deep embedding to be able to transform a circuit description into a netlist (to subsequently output that as a VHDL/Verilog file). Clash on the other hand uses "standard" compiler techniques to create a netlist from the Haskell abstract syntax tree (AST). This "standard" compiler technique enables the following features not available in (Haskell-based) EDSLs:
- Clash allows the use of normal Haskell operations such as (==) on both the meta-level (how the program is structured/generated), and the object-level (the functionality of the program).
- Clash allows the use of regular Haskell syntax to model the concept of 'choice' at the object-level (the functionality of the program): if-expressions, guards, case, etc.
- Clash allows programmers to use native Haskell pattern matching.
Basically, with Clash you can use regular Haskell to describe the behavior of the circuit, most importantly all of it's choice-constructs (case-expressions, guards, etc.). With an EDSL you are "limited" by the constructs of the DSL, making your circuit descriptions look less like regular Haskell functions.
-
Q: What's the difference between Clash and Chisel/Spinal/Migen/Hardcaml?
A: The biggest difference between these toolchains and Clash is that Clash exists as a Haskell derivative, with a full synthesizing compiler to RTL — while Chisel/Spinal/Migen/Hardcaml exists as an embedding of hardware semantics inside Scala/Scala/Python/OCaml. Aside from the "host language" differences, this means that Chisel/Spinal/Migen/Hardcaml are conceptually closer to something like Lava/Blarney than to Clash. So within these languages you can only use the host language constructs to structure and compose the constructs of the EDSL, and you can't use host language constructs to describe the behavior of the circuit; i.e. you cannot use the host language's regular if-expression to model the concept of choice, but you have to use e.g. Chisel's when-function.
Aside from the above, there is also a varying degree of native simulation and interactivity. In Clash you can evaluate/simulate any (sub-)component in the interactive interpreter for an immediate and localized design feedback loop. The only EDSLs that have a similar interactive interpreter for fast design feedback are the older variants of Lava. They used a so-called dual-embedding, where the EDSL primitives also contained a normal Haskell function which described their behavior, and so the composition of these primitives could be evaluated as a regular Haskell function.
The other EDSLs all offer simulation, but there is a higher latency to get from a design to a simulation of a design, and they are not as interactive. Blarney emits Verilog, and you can then use a Verilog simulator to simulate the Blarney design. Spinal also emits Verilog, but it then uses Verilator to compile it to an object-file which is loaded back into Scala, allowing you to interact with your Spinal design from within Scala. Chisel is also not interpreted directly, instead, a Chisel description is "lowered" to FIRRTL where that FIRRTL description is then executed inside Scala by the FIRRTL interpreter. Migen works similarly to Chisel as far as the approach to simulation goes, although perhaps more direct: it directly interprets its own deep embedding data structure (its IR) to enable native simulation.
All of this influences the style in which you write circuits and the creative process by which you come to a solution; the effects of this on the quality of results (QoR) and development time are, however, both hard to qualify and hard to quantify. That is, although all of these languages, both the EDSLs and Clash, enable full control over the QoR (i.e. you can get as many registers and as much logic as you intended), the way in which you get there can vary from problem domain to problem domain and person to person. If you have enough time, we encourage to try several of them and see which style is the most natural fit for you; if you're limited on time, we of course recommend that you just go with Clash ;-)
License
Copyright (c) 2012-2016, University of Twente, 2016-2019, Myrtle Software Ltd, 2017-2019, QBayLogic B.V., Google Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Clash as a Language
As Clash reuses parts of the GHC compiler for its frontend, the syntax and semantics should be familiar to Haskell programmers. For people unfamiliar with Haskell, there are many resources to learn the language, such as
Clash does make some use of more advanced features of GHC Haskell, which are exposed by GHC as language extensions. The extensions used by Clash are
- BinaryLiterals
- ConstraintKinds
- DataKinds
- DeriveAnyClass
- DeriveGeneric
- DeriveLift
- DerivingStrategies
- ExplicitForAll
- ExplicitNamespaces
- FlexibleContexts
- FlexibleInstances
- KindSignatures
- MagicHash
- MonoLocalBinds
- NumericUnderscores
- NoImplicitPrelude
- NoStarIsType
- NoStrictData
- NoStrict
- QuasiQuotes
- ScopedTypeVariables
- TemplateHaskellQuotes
- TemplateHaskell
- TypeApplications
- TypeFamilies
- TypeOperators
Warning
Since GHC 8.6, the StarIsType
extension is defined.
This extension is explicitly turned off by Clash, meaning Data.Kind.Type
must be used to refer to Haskell types.
Clash also enables some GHC plugins by default which improve the type inference for type level numbers. The plugins enabled by default are
Users are free to control the language extensions and GHC options with the normal OPTIONS_GHC
and LANGUAGE
pragmas in source files.
For more information, see the GHC User's Guide.
Clash Prelude
Basic Types
The Clash prelude includes many different numeric types, which are used to safely define other types/functions. These include, but may not be limited to
-
Type level natural numbers (
Nat
), which allow numbers to be used in types. Conceptually, this is similar to const generics in C++.It is possible to have term level values which refer to a type level number. This is called
SNat n
(for singleton natural number). These are defined up to 1024 with the prefix "d" (e.g.d256
). -
Unsigned n
andSigned n
numbers with an arbitrary width (given as a type level natural number). These allow fixed-width arithmetic to be used on arbitrary numbers. -
Index n
provides natural numbers up to an arbitrary value (given as a type level natural number). These allow indexing into fixed width structures likeVec n a
.
Another commonly used type is BitVector n
.
This provides a fixed size vector of Bit
values which can be indexed, and used to perform unsigned integer arithmetic.
Any type that can be marshaled to/from a BitVector n
implements the BitPack
class, which defines the conversion.
Note
It is also possible to derive instances of BitPack
using Generic
, by writing deriving (Generic, BitPack)
in the type definition.
This automatically determines how to do the conversion at compile-time.
More generally, there is a Vec n a
type which allows collections of arbitrary values to be used.
These vectors are tagged with their length, to prevent out of bounds access at compile-time.
Warning
The Vec n a
type exports pattern synonyms for inserting at the left and right of a vector.
The types of the Cons
constructor and (:>)
pattern are slightly different, and may behave differently in practice.
The Cons
constructor has a more general type, allowing it to be used in some cases where the pattern cannot be used.
However, this additional power comes at the cost of type inference.
It is recommended that users use the (:>)
pattern by default, and only use Cons
when necessary.
Synthesis Domains
Synchronous circuits have a synthesis domain, which determines the behavior of things which can affect signals in the domain. Domains consist of
- a name, which uniquely refers to the domain
- the clock period in ps
- the active edge of the clock
- whether resets are synchronous (edge-sensitive) or not
- whether the initial (power up) behavior is defined
- whether resets are high or low polarity
The prelude provides some common domains, namely XilinxSystem
and IntelSystem
for the standard configurations of each vendor.
There is also a generic domain, System
, which can be used for vendor-agnostic purposes (e.g., writing a generic test bench).
It is possible to define new synthesis domains for custom hardware using the createDomain
function, which also defines the necessary instances for domains.
A value in a synchronous circuit is wrapped in the Signal dom a
type, which specifies the synthesis domain and the type of value.
Any function which needs access to a domain can use the constraint KnownDomain
to extract configuration.
The default API exposed by the prelude is implicit with regards to clocks, reset lines and enable lines, as these can be determined at compile time.
However, if they are needed the Clash.Explicit
module contains explicit versions of the API which expose these directly in function arguments.
It is also possible to use functions like exposeClockResetEnable
to turn an implicitly defined function to an explicitly defined function.
State Machines
The Clash prelude contains combinators for two classical finite state machines which can be used to define synchronous circuits.
The first of these is mealy
, which encodes a Mealy machine.
This is a machine specified by
- A transition function of type
state -> input -> (state, output)
- An initial state
- An input signal which can change at each cycle
Note
The Mealy machine is similar to the State
monad, which Haskell programmers may already be familiar with.
Practically speaking, the only difference is that this machine also has an input signal which is changed externally to the definition of the machine.
It is also possible to define a Moore machine using the moore
function in the Clash prelude.
This differs from the Mealy machine by providing output based on the previous state (as opposed to the newly calculated state), and is specified by
- A transition function of type
state -> input -> state
- An output function of type
state -> output
- An initial state
- An input signal which can change at each cycle
Sometimes, there may be multiple inputs/outputs needed for a machine.
As machines only input and output a single signal, there is a way to combine and separate multiple signals.
The Bundle
class specifies how to convert between some type which is a signal of a product, and some type which is a product of signals, e.g.
bundle :: (Signal dom a, Signal dom b) -> Signal dom (a, b)
unbundle :: Signal dom (a, b) -> (Signal dom a, Signal dom b)
There are combinators which can automatically perform this bundling and unbundling for you as required, called mealyB
and mooreB
.
The Bundle
class is already defined for many types, including tuples (up to 62 elements), Maybe a
, Either a b
and Vec n a
.
RAM and ROM
The Clash prelude provides the ability to work with synchronous and asynchronous ROM, asynchronous RAM and synchronous Block RAM.
The simplest of these are ROMs, which only allow indexing into a Vec n a
of elements.
ROM is defined using the functions in Clash.Prelude.ROM
.
RAM is more complex, as it allows both reading and writing.
The function to define a RAM takes in a signal for the address to read, and a signal for an optional address to update (bundled with the new value).
At each cycle it outputs the value of the memory address read in the previous cycle.
Asynchronous RAM is defined in Clash.Prelude.RAM
.
An FPGA may include a block RAM, which is a larger memory structure and more suitable for some applications.
Block RAM also has a synchronous read port, allowing memory access to be synchronized to a clock.
Block RAM is used the same way as async RAM, allowing the two to be compared quickly.
Block RAM is defined in Clash.Prelude.BlockRam
.
Undefined Values
When working with hardware designs, there are times when undefined values may be encountered in simulation.
Clash provides a custom exception type, XException
, for cases when an undefined value is encountered.
There are also many utility functions for working with exceptions, such as
errorX
, which throws anXException
isX
andhasX
, which check forXExceptions
when evaluatingmaybeIsX
andmaybeHasX
, which discard information about exceptions
There are also implementations of typical classes in Haskell which have been changed to work with undefined values. Currently these are
ShowX
, which works like theShow
class in Haskell. When an undefined value is encountered an "X" is printed.Show
can still be used, but will throw an exception if an undefined value is encountered.NFDataX
, which works like theNFData
class in thedeepseq
library. This allows evaluating values to normal form in code whenXException
may be present.NFData
can still be used, but will bubble up exceptions ifXException
is encountered.
Clash Compiler Flags
--vhdl
Use the VHDL backend for code generation.
This currently emits VHDL 1993 source which can be consumed by other tools.
--verilog
Use the Verilog backend for code generation.
This currently emits Verilog 2001 source which can be consumed by other tools.
--systemverilog
Use the SystemVerilog backend for code generation.
This currently emits SystemVerilog 2012 source which can be consumed by other tools.
-fclash-debug
Set the debugging mode for the compiler, exposing additional output.
The available options are
DebugNone
to show no debug messagesDebugSilent
to test invariants and error if any are violated. This is implicitly enabled by any debug flag.DebugFinal
to show expressions after they have been completely normalizedDebugCount
to count how often each transformation is appliedDebugName
to show the names of transformations as they are appliedDebugTry
to show names of tried and applied transformationsDebugApplied
to show sub-expressions after they are rewrittenDebugAll
to show all sub-expressions when a rewrite is attempted
Default: DebugNone
Note
This flag exists for backwards compatibility.
It is now possible to set debugging flags individually with
-fclash-debug-invariants
,
-fclash-debug-info
and
-fclash-debug-count-transformations
.
-fclash-debug-invariants
Check invariants while debugging and print warnings/errors which may be useful, such as alerting when unexpected changes occur or when a transformation introduces free variables / shadowing.
-fclash-debug-info
Specify the information to show about individual transformations while debugging.
From least to most information, these are
None
to show no informationFinalTerm
to show the final result of normalizationAppliedName
to show the names of applied transformationsAppliedTerm
to show the result of applied transformationsTryName
to show the names of attempted transformations, as well as the result of any transformations which are appliedTryTerm
to show the names and results of all transformations attempted whether they were applied or not
Default: None
-fclash-debug-count-transformations
Count the transformations that are applied and print a summary at the end of the normalization phase.
-fclash-debug-history[=FILENAME]
Saves all applied rewrites into FILENAME
, for later analysis with the clash-term tool.
When no filename is given it defaults to history.dat
.
-fclash-debug-transformations
List the transformations that are to be debugged.
This is given as a comma-separated list of transformations, e.g.
clash -fclash-debug-transformations inlineNonRep,topLet,appProp
Default: []
-fclash-debug-transformations-from=N
Only print debug output from applied transformation N
and onwards.
clash -fclash-debug-transformations-from=21570
Default: 0
-fclash-debug-transformations-limit=N
Only print debug output for N
applied transformations.
clash -fclash-debug-transformations-limit=12
Default: MAX_INT
-fclash-hdldir
Specify the directory that generated HDL is written into.
For example
clash -fclash-hdldir build/hdl
will create a directory build/hdl
Default: Either vhdl
, verilog
, or systemverilog
depending on the synthesis target.
-fclash-hdlsyn
Specify the HDL synthesis tool which will be used.
Available options are Vivado
, Quartus
and Other
, but some synonyms for these exist (Xilinx
and ISE
are synonyms for Vivado
, Altera
and Intel
are synonyms for Quartus
).
Default: Other
-fclash-no-cache
Don't reuse previously generated output from Clash, instead generating HDL from a clean state.
While this leads to longer builds, it can be useful in development.
Warning
Previously this flag was called -fclash-nocache
, however this is now deprecated.
Default: Cache generated HDL
-fclash-no-check-inaccessible-idirs
Check that all include directories (containing primitives) exist when running Clash.
If any directory does not exist, an error is thrown.
Default: Check directories
-fclash-clear
Remove HDL directories before writing to them (if cache can't be used).
By default, Clash will only write to non-empty directories if it can prove all files in it are generated by a previous run.
This option applies to directories of the various top entities, i.e., the subdirectories made in the directory passed in with -fclash-hdldir
.
Default: Clean before build
-fclash-no-prim-warn
Disable warnings for primitives that are annotated with warnAlways
.
This means warnings from annotations like
{-# ANN f (warnAlways "This primitive is dangerous") #-}
will not be shown when compiling.
Default: Show warnings
-fclash-spec-limit
Change the number of times a function can undergo specialization.
Default: 20
-fclash-inline-limit
Change the number of times a function f
can undergo inlining inside some other function g
.
This prevents the size of g
growing dramatically.
Default: 20
-fclash-inline-function-limit
Set the threshold for function size.
Below this threshold a function is always inlined (if it is not recursive).
Default: 15
-fclash-inline-constant-limit
Set the threshold for constant size.
Below this threshold constants are always inlined.
A value of 0 inlines all constants.
Default: 0
-fclash-evaluator-fuel-limit
Set the threshold for unfolding potentially non-terminating bindings in the evaluator.
A value of 0 only unfolds terminating bindings.
Default: 20
-fclash-intwidth
Set the bit width for the Int/Word/Integer
types in the generated HDL.
Clash simulation is not affected, and neither are BitPack
instances.
The only allowed values are 32 or 64.
Default: Machine word size (WORD_SIZE_IN_BITS
)
-fclash-error-extra
Print additional information with compiler errors if it as available.
If there is extra information and this flag is not enabled, a message will be printed suggesting this flag.
Default: False
-fclash-float-support
Enable support for floating point numbers.
If this is disabled, Clash will not attempt to convert Float and Double values for hardware.
Default: False
-fclash-component-prefix
Prefix the names of generated HDl components with a string.
For example a component foo
would be called xcorp_foo
if run with
clash -fclash-component-prefix "xcorp"
Default: ""
-fclash-old-inline-strategy
The new inlining strategy for Clash inlines all functions which are not marked with NOINLINE
or a synthesize attribute.
The old inlining strategy differed, attempting only to inline functions which were deemed "cheap".
The old inlining strategy may be quicker in practice for some circuits.
Default: False
-fclash-no-escaped-identifiers
Disable extended identifiers, as used in some HDLs like VHDL to allow more flexibility with names.
Clash will only generate basic identifiers if this is used.
Default: Escaped identifiers are allowed
-fclash-lower-case-basic-identifiers
Clash will only generate lower case basic identifiers if this is used.
This affects places where the various HDLs only allow basic identifiers to be used, most notably module and file names.
Default: Disabled
-fclash-compile-ultra
Aggressively run the normalizer, potentially gaining much better runtime performance at the expense of compile time.
Default: False
-fclash-force-undefined{,0,1}
Set the value to use when an undefined value is inserted into generated HDL.
This flag can be suffixed with either 0 or 1 to force use of that bit, or left without a suffix to use a HDL-specific default (e.g. x
in Verilog).
Default: Disabled
-fclash-aggressive-x-optimization
Remove all undefined branches from case expressions, replacing them with another defined value in the expression.
If only one branch is defined, the case expression is elided completely.
If no branches are defined the entire expression is replaced with a call to errorX
.
Implies: -fclash-aggressive-x-optimization-blackboxes
Default: False
-fclash-aggressive-x-optimization-blackboxes
Allow blackboxes to detect undefined values and change their behavior accordingly.
For example, if register
is used in combination with an undefined reset value, it will leave out the reset logic entirely.
This flag is enabled when using -fclash-aggressive-x-optimization
.
Default: False
-fclash-edalize
Generate metadata for use with Edalize.
This generates edam.py files in all top entities with the configuration for building that entity.
Users still need to edit this file to specify the EDA tool to use, and if necessary the device to target (for Quartus, Vivado etc.).
Default: False
-main-is
When using one of --vhdl
, --verilog
, or --systemverilog
, this flag refers to the synthesis target.
For example, running Clash with clash My.Module -main-is top --vhdl
would synthesize My.Module.top
.
-fclash-timescale-precision
Sets the second part of Verilog's timescale 100fs/100fs
.
E.g., setting this flag to 1fs
would make Clash generate Verilog files with timescale 100fs/1fs
as their header.
Default: 100fs
Hacking on the Clash Compiler
Prerequisites
Hacking on Clash requires more dependencies than simply running Clash. The test suite requires having a tool available to synthesize any backend being tested. This means you need:
- ghdl installed to test VHDL
- iverilog installed to test Verilog
- ModelSim installed to test SystemVerilog
- SymbiYosys and Z3 installed to test Verilog and SystemVerilog
Get Clash from source
Get the source code using Git and enter the cloned directory:
git clone git@github.com:clash-lang/clash-compiler.git
# Alternatively, if you haven't setup SSH keys with GitHub:
# git clone https://github.com/clash-lang/clash-compiler.git
cd clash-compiler
To check out a released version, use:
git checkout v1.2.3
To checkout a release branch use:
git checkout 1.2
Note that release branches might contain non-released patches.
Cabal
To use Cabal you need both Cabal and GHC installed on your system. For Linux and MacOS users we recommend using ghcup. Windows users are recommended to use the Haskell Platform.
To run clash use:
cabal v2-run --write-ghc-environment-files=always -- clash
If this fails, make sure you've got an up-to-date package index:
cabal update
Stack
Install Stack and run:
stack run -- clash
Nix
Or use Nix to get a shell with the clash
and clashi
binaries on your PATH:
nix-shell
Subprojects
The Clash compiler consists of different cabal libraries, which together provide a complete compiler. Primarily, this consists of
clash-ghc
The frontend of the compiler, using parts of the GHC frontend. This provides the ability to load modules, translate GHC Core to Clash Core, and implements the
clash
andclashi
executables.A lot of the code in this library is separated by the version of GHC it works with. For example,
src-bin-9.0
is specific to GHC 9.0.x.
clash-lib
The backend of the compiler, exposed as a library. This is the largest library in the project, and includes the various ASTs (e.g. Core, Netlist), normalization, code generation, and primitives / black boxes.
clash-prelude
The standard library for Clash as a language. This includes anything that is used to develop hardware in Clash, such as Signals, Clocks and combinators for common forms of state machine.
The
clash-prelude
library also re-exports parts of the Haskellbase
library, allowing circuit designs to reuse common functions and definitions.
The repository also contains other libraries. These either provide additional functionality which is not required, or are not yet production-ready. These are
clash-cosim
Co-simulation for Clash, allowing Verilog to be run inline as though it were a normal Haskell function. This provides a QuasiQuoter for use in Haskell.
Warning
This library is very experimental, and is not guaranteed to work with the most recent development version of Clash.
clash-term
A development tool for analyzing how the normalizer in
clash-lib
affects the core of a particular design. It allows the result of each different optimizer pass to be seen for debugging purposes.
clash-lib-hedgehog
Hedgehog Generators for
clash-lib
.
clash-prelude-hedgehog
Hedgehog Generators for
clash-prelude
.