### Quick Start with Scala CLI Source: https://context7.com/chipsalliance/chisel/llms.txt Use Scala CLI to quickly run a Chisel example. Download the example script and execute it. ```bash curl -O -L https://github.com/chipsalliance/chisel/releases/latest/download/chisel-example.scala scala-cli chisel-example.scala ``` -------------------------------- ### Install Website Dependencies Source: https://github.com/chipsalliance/chisel/blob/main/website/README.md Run this command to install all necessary dependencies for building the website. Ensure you have a Chisel installation, Node.js, and npm. ```makefile make install ``` -------------------------------- ### Install SBT with Scoop on Windows Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/installation.md Install SBT using the Scoop package manager on Windows. ```sh scoop install sbt ``` -------------------------------- ### Download Chisel Scala CLI Example Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/installation.md Use this command to download the Chisel Scala CLI example file. ```bash curl -O -L https://github.com/chipsalliance/chisel/releases/latest/download/chisel-example.scala ``` -------------------------------- ### Install Verilator and SBT on macOS Source: https://github.com/chipsalliance/chisel/blob/main/SETUP.md Use Homebrew to install Verilator and SBT. Ensure Homebrew is installed first. ```bash brew install sbt verilator ``` -------------------------------- ### Install FileCheck using apt Source: https://github.com/chipsalliance/chisel/blob/main/SETUP.md Installs FileCheck by installing the 'llvm-tools' package and adding its bin directory to the PATH. This method is suitable for systems with apt package manager. ```bash sudo apt-get install llvm-12-tools export PATH=$PATH:/usr/lib/llvm-12/bin ``` -------------------------------- ### Install SBT Manually on Linux Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/installation.md Download and extract the SBT tarball for manual installation on Linux. ```sh curl -s -L https://github.com/sbt/sbt/releases/download/v1.9.7/sbt-1.9.7.tgz | tar xvz ``` ```sh sudo mv sbt/bin/sbt /usr/local/bin/ ``` -------------------------------- ### Install JVM on Ubuntu Source: https://github.com/chipsalliance/chisel/blob/main/SETUP.md Installs the default Java Development Kit on Ubuntu systems. This is a prerequisite for running SBT. ```bash sudo apt-get install default-jdk ``` -------------------------------- ### Install Temurin JDK 17 on Windows with Scoop Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/installation.md Install Temurin JDK 17 using Scoop on Windows. ```bash scoop install temurin17-jdk ``` -------------------------------- ### Build and Install Verilator from Source Source: https://github.com/chipsalliance/chisel/blob/main/SETUP.md Configures, builds, and installs Verilator from its source code. Ensure VERILATOR_ROOT is unset before running autoconf. ```bash unset VERILATOR_ROOT # For bash, unsetenv for csh autoconf # Create ./configure script ./configure make sudo make install ``` -------------------------------- ### Compile and Run Chisel Example with Scala CLI Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/installation.md Execute the downloaded Chisel Scala CLI example to compile and run it. ```bash scala-cli chisel-example.scala ``` -------------------------------- ### Install SBT for Windows Source: https://github.com/chipsalliance/chisel/blob/main/SETUP.md Provides a link to download and install SBT for Windows. Verilator is not natively supported on Windows but can be used via WSL or Cygwin. ```html Download and install sbt for Windows ``` -------------------------------- ### Chisel Build Setup with SBT Source: https://context7.com/chipsalliance/chisel/llms.txt Configure your project's build.sbt file to include Chisel and its compiler plugin. Ensure Java 17+ is installed. ```scala scalaVersion := "2.13.16" val chiselVersion = "7.2.0" libraryDependencies += "org.chipsalliance" %% "chisel" % chiselVersion addCompilerPlugin("org.chipsalliance" % "chisel-plugin" % chiselVersion cross CrossVersion.full) ``` -------------------------------- ### Install Verilator Prerequisites on Ubuntu Source: https://github.com/chipsalliance/chisel/blob/main/SETUP.md Installs essential build tools and compilers required for compiling Verilator from source on Ubuntu. ```bash sudo apt-get install git make autoconf g++ flex bison ``` -------------------------------- ### Serve Website Locally Source: https://github.com/chipsalliance/chisel/blob/main/website/README.md Starts a local server to view the built website and preview changes. This is useful for development and testing. ```makefile make serve ``` -------------------------------- ### Install LLVM lit with pip3 Source: https://github.com/chipsalliance/chisel/blob/main/CONTRIBUTING.md Install the LLVM lit testing tool using pip3. Ensure your PATH environment variable is updated to include the installation directory if necessary. ```shell pip3 install lit ``` -------------------------------- ### Install Mill with Scoop on Windows Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/installation.md Install Mill using the Scoop package manager on Windows. ```sh scoop install mill ``` -------------------------------- ### Re-run Simulation Example (Chisel-testers) Source: https://github.com/chipsalliance/chisel/wiki/release-notes-17-03-23 Example demonstrating how to re-run a simulation without rebuilding the design, utilizing Verilator integration in Chisel-testers. ```scala val result = tester.poke(dut.io.a, 100).step().poke(dut.io.b, 100).step().peek(dut.io.result) ``` -------------------------------- ### Install firtool on macOS Source: https://github.com/chipsalliance/chisel/blob/main/SETUP.md Download and extract the firtool binary. Add the 'bin' directory to your PATH. ```bash wget -q -O - https://github.com/llvm/circt/releases/download/firtool-1.56.1/circt-full-shared-macos-x64.tar.gz | tar -zx ``` ```bash export PATH=$PATH:$PWD/firtool-1.56.1/bin ``` ```bash mv firtool-1.56.1/bin/firtool /usr/local/bin/ ``` -------------------------------- ### Install SBT with MacPorts Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/installation.md Install SBT using the MacPorts package manager on macOS. ```sh sudo port install sbt ``` -------------------------------- ### Install Verilator with APT on Linux Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/installation.md Install Verilator using the APT package manager on Linux. Note that this may install an older version. ```sh apt install -y verilator ``` -------------------------------- ### Install Temurin JDK 17 on Ubuntu Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/installation.md Commands to add the Eclipse Adoptium repository and install Temurin JDK 17 on Ubuntu systems. ```bash # Ensure the necessary packages are present: apt install -y wget gpg apt-transport-https # Download the Eclipse Adoptium GPG key: wget -qO - https://packages.adoptium.net/artifactory/api/gpg/key/public | gpg --dearmor | tee /etc/apt/trusted.gpg.d/adoptium.gpg > /dev/null # Configure the Eclipse Adoptium apt repository echo "deb https://packages.adoptium.net/artifactory/deb $(awk -F= '/^VERSION_CODENAME/{print$2}' /etc/os-release) main" | tee /etc/apt/sources.list.d/adoptium.list # Update the apt packages apt update # Install apt install temurin-17-jdk ``` -------------------------------- ### Install Verilator and SBT on Arch Linux Source: https://github.com/chipsalliance/chisel/blob/main/SETUP.md Installs Verilator and SBT using the pacman package manager on Arch Linux systems. ```bash pacman -Sy verilator sbt ``` -------------------------------- ### Install SBT with Homebrew on macOS Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/installation.md Install SBT using the Homebrew package manager on macOS. ```sh brew install sbt ``` -------------------------------- ### Download and Install FileCheck Binary Source: https://github.com/chipsalliance/chisel/blob/main/SETUP.md Downloads a pre-compiled FileCheck binary, makes it executable, and adds its directory to the PATH. This is an alternative to package manager installation. ```bash mkdir filecheck cd filecheck wget -q https://github.com/jackkoenig/FileCheck/releases/download/FileCheck-16.0.6/FileCheck-linux-x64 mv FileCheck-linux-x64 FileCheck chmod +x FileCheck export PATH=$PATH:$PWD ``` -------------------------------- ### ScalaDoc Comment Examples Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/developers/style.md Use ScalaDoc for documentation. Examples show multi-line and single-line formats. ```java /** Multiple lines of ScalaDoc text are written here, * wrapped normally... */ public int method(String p1) { ... } ``` ```java /** An especially short bit of Javadoc. */ ``` -------------------------------- ### Install Temurin JDK 17 on MacOS with Homebrew Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/installation.md Install Temurin JDK 17 using Homebrew on macOS. ```bash brew install temurin@17 ``` -------------------------------- ### Create ROM with Array Initialization Source: https://github.com/chipsalliance/chisel/wiki/Memories Example of creating a ROM initialized with specific values and accessing it using a counter. ```scala val m = VecInit(Array(1.U, 2.U, 4.U, 8.U)) val r = m(counter(m.length.U)) ``` -------------------------------- ### Install FileCheck on macOS Source: https://github.com/chipsalliance/chisel/blob/main/SETUP.md Download, make executable, and add FileCheck to your PATH. Alternatively, move it to a standard location. ```bash mkdir filecheck cd filecheck wget -q https://github.com/jackkoenig/FileCheck/releases/download/FileCheck-16.0.6/FileCheck-macos-x64 mv FileCheck-macos-x64 FileCheck chmod +x FileCheck export PATH=$PATH:$PWD ``` ```bash mv FileCheck /usr/local/bin ``` -------------------------------- ### Verilog Source Locator Example Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/explanations/source-locators.md This demonstrates the format of source locators added to Verilog wire declarations. ```verilog wire [2:0] w; // @[src/main/scala/MyProject/MyFile.scala 1210:21] ``` -------------------------------- ### Install Temurin JDK 17 on MacOS with MacPorts Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/installation.md Install Temurin JDK 17 using MacPorts on macOS. ```bash sudo port install openjdk17-temurin ``` -------------------------------- ### Verilog Output for Flipped Bundle Example Source: https://github.com/chipsalliance/chisel/wiki/Bundles-and-Vecs This Verilog code is generated from the `MyModule` example demonstrating the use of `Flipped()` for bidirectional interfaces. ```verilog module MyModule( // @[:@3.2] input normalBundle_a, // @[:@4.4] output normalBundle_b, // @[:@4.4] output flippedBundle_a, // @[:@5.4] input flippedBundle_b // @[:@5.4] ); assign normalBundle_b = normalBundle_a; assign flippedBundle_a = flippedBundle_b; endmodule ``` -------------------------------- ### Install Mill Wrapper Script Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/installation.md Download and make the Mill wrapper script executable for Linux and macOS. ```sh curl -L https://raw.githubusercontent.com/lefou/millw/0.4.11/millw > mill && chmod +x mill ``` ```sh sudo mv mill /usr/local/bin/ ``` -------------------------------- ### Last Assignment to Wire Takes Effect (Example 2 - Equivalent) Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/explanations/combinational-circuits.md This is the equivalent circuit to the previous example, showing that only the final assignment to the wire is effective. ```scala val myNode = Wire(UInt(8.W)) myNode := 0.U ``` -------------------------------- ### ChiselSim Example for MyModule Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/appendix/migrating-from-chiseltest.md Modern ChiselSim specification for MyModule using EphemeralSimulator. ```scala import chisel3._ import chisel3.simulator.EphemeralSimulator._ import org.scalatest.flatspec.AnyFlatSpec class MyModuleSpec extends AnyFlatSpec { behavior of "MyModule" it should "do something" in { simulate(new MyModule) { c => c.io.in.poke(0.U) c.clock.step() c.io.out.expect(0.U) c.io.in.poke(42.U) c.clock.step() c.io.out.expect(42.U) println("Last output value : " + c.io.out.peek().litValue) } } } ``` -------------------------------- ### Generate Verilog for Flipped Bundle Example Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/explanations/bundles-and-vecs.md This Verilog output demonstrates the effect of Flipped() on Bundle field directions. ```verilog chisel3.docs.emitSystemVerilog(new MyFlippedModule()) ``` -------------------------------- ### Chisel Module Definition and Hierarchy Source: https://context7.com/chipsalliance/chisel/llms.txt Define a basic Chisel module (Adder) and a hierarchical module (DualAdder) that instantiates it. The example also shows how to emit SystemVerilog. ```scala import chisel3._ import circt.stage.ChiselStage class Adder extends Module { val io = IO(new Bundle { val a = Input(UInt(8.W)) val b = Input(UInt(8.W)) val sum = Output(UInt(9.W)) // 1 bit wider to capture carry }) io.sum := io.a +& io.b // +& is expanding add } // Hierarchy: instantiate a submodule class DualAdder extends Module { val io = IO(new Bundle { val a1 = Input(UInt(8.W)); val b1 = Input(UInt(8.W)) val a2 = Input(UInt(8.W)); val b2 = Input(UInt(8.W)) val sum1 = Output(UInt(9.W)); val sum2 = Output(UInt(9.W)) }) val adder1 = Module(new Adder) adder1.io.a := io.a1; adder1.io.b := io.b1; io.sum1 := adder1.io.sum val adder2 = Module(new Adder) adder2.io.a := io.a2; adder2.io.b := io.b2; io.sum2 := adder2.io.sum } // Emit SystemVerilog val sv = ChiselStage.emitSystemVerilog(new DualAdder) println(sv) ``` -------------------------------- ### Module Instantiation (Verilog-like) Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/developers/style.md Instantiate modules using 'Module(new MyMod())' and then hook up their IO. ```scala val myMod = Module(new MyMod()) myMod.io <> hookUp ``` -------------------------------- ### Install Verilator with Homebrew on macOS Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/installation.md Install Verilator using the Homebrew package manager on macOS. ```sh brew install verilator ``` -------------------------------- ### Install Verilator with MacPorts on macOS Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/installation.md Install Verilator using the MacPorts package manager on macOS. ```sh sudo port install verilator ``` -------------------------------- ### Instantiate Xilinx IBUFDS with Parameters in BlackBox Source: https://github.com/chipsalliance/chisel/wiki/BlackBoxes Demonstrates how to instantiate a Xilinx IBUFDS using BlackBox and pass Verilog parameters. Requires importing chisel.experimental._. ```scala import chisel3._ import chisel3.util._ import chisel3.experimental._ // To enable experimental features class IBUFDS extends BlackBox(Map("DIFF_TERM" -> "TRUE", "IOSTANDARD" -> "DEFAULT")) { val io = IO(new Bundle { val O = Output(Clock()) val I = Input(Clock()) val IB = Input(Clock()) }) } ``` -------------------------------- ### Define and Use Read-Write Probes Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/explanations/probes.md Demonstrates the creation of read-write probe types and values, and their usage with IO ports and wires. Includes examples of `define` and standard connection operators. ```scala import chisel3._ import chisel3.probe.{RWProbe, RWProbeValue, force, forceInitial, read, release, releaseInitial} class Bar extends RawModule { val a_port = IO(RWProbe(Bool())) val b_port = IO(RWProbe(UInt(8.W))) private val a = WireInit(Bool(), true.B) a_port :<= RWProbeValue(a) private val b = WireInit(UInt(8.W), 0.U) b_port :<= RWProbeValue(b) } class Foo extends Module { val cond = IO(Input(Bool())) private val bar = Module(new Bar) // Example usage of forceInitial/releaseInitial: forceInitial(bar.a_port, false.B) releaseInitial(bar.a_port) // Example usage of force/release: when (cond) { force(bar.b_port, 42.U) }.otherwise { release(bar.b_port) } // The read API may still be used: private val a_read = dontTouch(WireInit(read(bar.a_port))) } ``` -------------------------------- ### Using WireInit with Hardware Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/explanations/chisel-type-vs-scala-type.md Illustrates that `WireInit` should be used with a hardware type. Passing a Chisel type directly will result in an error. ```scala // Do this... elaborate(new Module { val hardware = Wire(new MyBundle(3)) hardware := DontCare val moarHardware = WireInit(hardware) }) ``` ```scala // Not this... elaborate(new Module { val crash = WireInit(new MyBundle(3)) }) ``` -------------------------------- ### Start VCD Recording (REPL Command) Source: https://github.com/chipsalliance/chisel/wiki/Debugging-with-the-Interpreter-REPL-3 Initiate VCD recording within the REPL. The specified filename will be used; the .vcd suffix is not automatically appended. All subsequent circuit changes will be recorded. ```scala record-vcd gcd-run-1.vcd ``` -------------------------------- ### Configure warnings using multiple --warn-conf arguments Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/explanations/warnings.md This example achieves the same warning configuration as the previous one but uses two separate --warn-conf arguments for clarity. ```scala compile(new TooWideIndexModule, args = Array("--warn-conf", "id=4&src=**warnings.md:s", "--warn-conf", "any:e")) ``` -------------------------------- ### Install Firtool to System Path Source: https://github.com/chipsalliance/chisel/blob/main/SETUP.md Moves the firtool binary to a standard system location, making it accessible without modifying the PATH environment variable. Requires root access. ```bash mv firtool-1.56.1/bin/firtool /usr/local/bin/ ``` -------------------------------- ### Annotate Module I/Os with Select.ios Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/cookbooks/hierarchy.md Use `Select.ios` in conjunction with `Select.allInstancesOf` or `Select.allDefinitionsOf` to annotate the I/Os of selected instances or definitions. This allows for targeted annotation of input and output ports. ```scala @instantiable class InOutModule extends Module { @public val in = IO(Input(Bool())) @public val out = IO(Output(Bool())) out := in } @instantiable class TwoInOutModules extends Module { val in = IO(Input(Bool())) val out = IO(Output(Bool())) val definition = Definition(new InOutModule) val i0 = Instance(definition) val i1 = Instance(definition) i0.in := in i1.in := i0.out out := i1.out } class InOutTop extends Module { val definition = Definition(new TwoInOutModules) val instance = Instance(definition) aop.Select.allInstancesOf[InOutModule](instance).foreach { i => aop.Select.ios(i).foreach { io => experimental.annotate(io) { println("instance io: " + io.toTarget) Nil } } } aop.Select.allDefinitionsOf[InOutModule](instance).foreach { d => aop.Select.ios(d).foreach { io => experimental.annotate(io) { println("definition io: " + io.toTarget) Nil } } } } ``` ```scala println("```") val y = circt.stage.ChiselStage.emitCHIRRTL(new InOutTop) println("```") ``` -------------------------------- ### Build Static Website Source: https://github.com/chipsalliance/chisel/blob/main/website/README.md Executes the build process to generate the static website files into the 'build' directory. This involves compiling Scala, running mdoc, and generating contributor pages. ```makefile make build ``` -------------------------------- ### Instantiating External Verilog with ExtModule Source: https://context7.com/chipsalliance/chisel/llms.txt Shows how to use ExtModule for cleaner API and BlackBox with inline Verilog for external module instantiation. Ensure Verilog file paths are correct when using addResource. ```scala import chisel3._ import chisel3.experimental._ // ExtModule: cleaner API, ports are top-level vals class IBUFDS extends ExtModule(Map("DIFF_TERM" -> "TRUE", "IOSTANDARD" -> "DEFAULT")) { val O = IO(Output(Clock())) val I = IO(Input(Clock())) val IB = IO(Input(Clock())) } // BlackBox with inline Verilog class BlackBoxAdd extends BlackBox with HasBlackBoxInline { val io = IO(new Bundle { val in1 = Input(UInt(32.W)) val in2 = Input(UInt(32.W)) val out = Output(UInt(32.W)) }) setInline("BlackBoxAdd.v", """module BlackBoxAdd(input [31:0] in1, input [31:0] in2, output [31:0] out); | assign out = in1 + in2; |endmodule""".stripMargin) } // Using ExtModule with resource Verilog file from classpath class MathExtMod extends ExtModule with HasExtModuleResource { val in = IO(Input(UInt(64.W))) val out = IO(Output(UInt(64.W))) addResource("/math_impl.v") } class Top extends Module { val ibufds = Module(new IBUFDS) ibufds.I := clock ibufds.IB := ~clock // ibufds.O is now a derived Clock } ``` -------------------------------- ### Enum Helper Methods Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/explanations/chisel-enum.md The ChiselEnum object provides helper methods like `.all` to get all enum values and `.getWidth` to get the hardware type's width. ```scala object StoreFunct3 extends ChiselEnum { val sb, sh, sw = Value val ukn = Value(7.U) } // We can see the mapping by printing each Value StoreFunct3.all.foreach(println) ``` -------------------------------- ### Firrtl Initialization Error Message Example Source: https://github.com/chipsalliance/chisel/wiki/Unconnected-Wires An example of a Firrtl error message indicating a reference that is not fully initialized. The indented lines provide context on connections involving the problematic signal. ```bash firrtl.passes.CheckInitialization$RefNotInitializedException: @[:@6.4] : [module Router] Reference io is not fully initialized. @[Decoupled.scala 38:19:@48.12] : node _GEN_23 = mux(and(UInt<1>("h1"), eq(UInt<2>("h3"), _T_84)), _GEN_2, VOID) @[Decoupled.scala 38:19:@48.12] @[Router.scala 78:30:@44.10] : node _GEN_36 = mux(_GEN_0.ready, _GEN_23, VOID) @[Router.scala 78:30:@44.10] @[Router.scala 75:26:@39.8] : node _GEN_54 = mux(io.in.valid, _GEN_36, VOID) @[Router.scala 75:26:@39.8] @[Router.scala 70:50:@27.6] : node _GEN_76 = mux(io.load_routing_table_request.valid, VOID, _GEN_54) @[Router.scala 70:50:@27.6] @[Router.scala 65:85:@19.4] : node _GEN_102 = mux(_T_62, VOID, _GEN_76) @[Router.scala 65:85:@19.4] : io.outs[3].bits.body <= _GEN_102 ``` -------------------------------- ### Run Chisel FIRRTL Generation with sbt Source: https://github.com/chipsalliance/chisel/wiki/Frequently-Asked-Questions Execute the Chisel FIRRTL generation process using sbt. Replace 'intro.Main' with the appropriate main class if different. ```bash sbt 'runMain intro.Main' ``` -------------------------------- ### FileCheck Example for Constant Propagation Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/explanations/testing.md This example demonstrates a FileCheck test that verifies a Chisel module's SystemVerilog output. It checks for a specific module name and ensures that constant computations are correctly simplified. This test is designed to pass if constant propagation occurs as expected. ```scala import chisel3._ import chisel3.testing.scalatest.FileCheck import circt.stage.ChiselStage import org.scalatest.funspec.AnyFunSpec class FileCheckExample extends AnyFunSpec with FileCheck { class Baz extends RawModule { val out = IO(Output(UInt(32.W))) out :<= 1.U(32.W) + 3.U(32.W) } describe("Foo") { it("should simplify the constant computation in its body") { ChiselStage.emitSystemVerilog(new Baz).fileCheck()( """|CHECK: module Baz( |CHECK-NEXT: output [31:0] out |CHECK: assign out = 32'h4; |CHECK: endmodule |""".stripMargin ) } } } ``` -------------------------------- ### Install FileCheck to System Path Source: https://github.com/chipsalliance/chisel/blob/main/SETUP.md Moves the FileCheck binary to a standard system location, making it accessible without modifying the PATH environment variable. This is an alternative to adding to PATH. ```bash mv FileCheck /usr/local/bin ``` -------------------------------- ### ChiselTest Example for MyModule Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/appendix/migrating-from-chiseltest.md Legacy ChiselTest specification for MyModule using ChiselScalatestTester. ```scala import chisel3._ import chiseltest._ import org.scalatest.flatspec.AnyFlatSpec class MyModuleSpec extends AnyFlatSpec with ChiselScalatestTester { behavior of "MyModule" it should "do something" in { test(new MyModule) { c => c.io.in.poke(0.U) c.clock.step() c.io.out.expect(0.U) c.io.in.poke(42.U) c.clock.step() c.io.out.expect(42.U) println("Last output value : " + c.io.out.peek().litValue) } } } ``` -------------------------------- ### Specify Output Directory and Top Name for Verilog Generation Source: https://github.com/chipsalliance/chisel/wiki/Frequently-Asked-Questions Command to run the Chisel HelloWorld main class with sbt, specifying the target output directory and the top-level module name for the generated Verilog file. Use --help for a full list of options. ```bash sbt 'runMain intro.HelloWorld --target-dir buildstuff --top-name HelloWorld' ``` -------------------------------- ### Define a Custom Counter Class Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/explanations/dataview.md Example of a non-Bundle type, MyCounter, with internal Chisel signals. ```scala class MyCounter(val width: Int) { /** Indicates if the Counter is incrementing this cycle */ val active = WireDefault(false.B) val value = RegInit(0.U(width.W)) def inc(): Unit = { active := true.B value := value + 1.U } def reset(): Unit = { value := 0.U } } ``` -------------------------------- ### Initialize and Access ROM with VecInit Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/explanations/memories.md Create a ROM using VecInit with literal values and access its elements using a counter as an address generator. ```scala import chisel3._ import chisel3.util.Counter val m = VecInit(1.U, 2.U, 4.U, 8.U) val c = Counter(m.length) c.inc() val r = m(c.value) ``` -------------------------------- ### Import Chisel and Utilities Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/explanations/chisel-enum.md Imports required for Chisel and utility functions used in subsequent examples. ```scala // Imports used in the following examples import chisel3._ import chisel3.util._ ``` -------------------------------- ### Run Chisel Driver from Command Line Source: https://github.com/chipsalliance/chisel/wiki/Running-Stuff This bash command demonstrates how to execute the Scala code to display the help information for the Chisel driver and its associated tools. ```bash bash> sbt 'run-main xyz.Dummy --help' ``` -------------------------------- ### Instantiate Modules with Instantiate API Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/cookbooks/hierarchy.md Use the `Instantiate` API to create multiple instances of a module, similar to the `Definition`/`Instance` approach but with a more direct syntax. This example instantiates `AddOne` twice within `AddTwoInstantiate`. ```scala import chisel3.experimental.hierarchy.Instantiate class AddTwoInstantiate(width: Int) extends Module { val in = IO(Input(UInt(width.W))) val out = IO(Output(UInt(width.W))) val i0 = Instantiate(new AddOne(width)) val i1 = Instantiate(new AddOne(width)) i0.in := in i1.in := i0.out out := i1.out } ``` ```verilog chisel3.docs.emitSystemVerilog(new AddTwoInstantiate(16)) ``` -------------------------------- ### Run Chisel Verilog Generation via sbt Source: https://github.com/chipsalliance/chisel/wiki/Frequently-Asked-Questions Command to execute the Chisel HelloWorld main class using sbt, which will generate the corresponding Verilog file. This is a convenient one-liner for quick generation. ```bash sbt 'runMain intro.HelloWorld' ``` -------------------------------- ### Instantiate Generic FIFO in Scala Source: https://github.com/chipsalliance/chisel/wiki/Polymorphism-and-Parameterization Example of instantiating the generic `Fifo` module with `DataBundle` and a depth of 8. ```scala val fifo = Module(new Fifo(new DataBundle, 8)) ``` -------------------------------- ### Instantiate and Test Chisel Circuit Source: https://github.com/chipsalliance/chisel/wiki/Running-Stuff Example of instantiating a Chisel circuit and running it with a test harness using `chisel3.iotesters.Driver`. This pattern is common for developing and testing new Chisel circuits. ```scala "here we assign to a F8.1 from a F8.3" in { chisel3.iotesters.Driver(() => new FixedPrecisionChanger(8, 3, 8, 1)) { c=> new FixedPointTruncatorTester(c, 6.875, 6.5) } should be (true) } ``` -------------------------------- ### Functional Module Creation with Apply Source: https://context7.com/chipsalliance/chisel/llms.txt Shows how to wrap module instantiation in an apply method for expression-level hardware composition. Useful for creating functional hardware generators. ```scala import chisel3._ class Mux4 extends Module { val io = IO(new Bundle { val sel = Input(UInt(2.W)) val in0 = Input(UInt(8.W)); val in1 = Input(UInt(8.W)) val in2 = Input(UInt(8.W)); val in3 = Input(UInt(8.W)) val out = Output(UInt(8.W)) }) io.out := MuxLookup(io.sel, io.in0)(Seq(0.U->io.in0, 1.U->io.in1, 2.U->io.in2, 3.U->io.in3)) } // Functional factory: instantiate and wire in a single expression object Add { def apply(a: UInt, b: UInt): UInt = { val m = Module(new AddModule(a.getWidth.max(b.getWidth))) m.io.a := a; m.io.b := b m.io.sum // return the output signal directly } } // Usage in another module's constructor body class FMA extends Module { val io = IO(new Bundle { val a = Input(UInt(8.W)); val b = Input(UInt(8.W)); val c = Input(UInt(8.W)) val out = Output(UInt(9.W)) }) // io.out := Add(Mul(io.a, io.b), io.c) // expression-like composition } ``` -------------------------------- ### Verilog Instantiation of Parameterized BlackBox Source: https://github.com/chipsalliance/chisel/wiki/BlackBoxes Shows the Verilog output for a parameterized BlackBox, illustrating how parameters are applied. ```verilog IBUFDS #(.DIFF_TERM("TRUE"), .IOSTANDARD("DEFAULT")) ibufds ( .IB(ibufds_IB), .I(ibufds_I), .O(ibufds_O) ); ``` -------------------------------- ### Instantiate Parameterized Filter in Scala Source: https://github.com/chipsalliance/chisel/wiki/Polymorphism-and-Parameterization Example of instantiating the generic `Filter` module with a specific `PLink` data type. ```scala val f = Module(new Filter(new PLink)) ``` -------------------------------- ### Instantiate Bundle Literal in Chisel Source: https://github.com/chipsalliance/chisel/wiki/Experimental-Features Example usage of the experimental bundle literal constructors to create a MyBundle instance. ```scala val outsideBundleLit = (new MyBundle).Lit(42.U, true.B) ``` -------------------------------- ### Instantiate and Match on a Scala Case Class Source: https://github.com/chipsalliance/chisel/wiki/Scala-Things-You-Should-Know Demonstrates instantiating a case class without 'new' and using pattern matching to access its parameters. ```scala val d = Drill(true, 10, 3000) ``` ```scala someVarThatMightHaveADrill match { case Drill(hasVarSpeed, amps, rpm) => // here we have access to local variables hasVarSpeed, amps, and rpm, that come // someVarThatMightHaveADrill's parameters. ??? ``` -------------------------------- ### Add genBundleElements to build.sbt Source: https://github.com/chipsalliance/chisel/blob/main/plugin/README.md Example of how to add the `genBundleElements` scalac option to a `build.sbt` file to enable the plugin's features. ```scala scalacOptions += "-P:chiselplugin:genBundleElements", ``` -------------------------------- ### Display FIRRTL Help Source: https://github.com/chipsalliance/chisel/blob/main/firrtl/README.md Display the usage string and available options for the FIRRTL command-line tool. ```bash utils/bin/firrtl --help ``` -------------------------------- ### Camel Case Conversion Example Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/developers/style.md Illustrates the convention for converting prose to camel case, treating acronyms as separate words. ```text Prose form | UpperCamelCase | lowerCamelCase | Incorrect :------------- | :------------- | :------------- | :------------ find GCD | FindGcd | findGcd | ~~findGCD~~ state for FSM | StateForFsm | stateForFsm | ~~stateForFSM~~ mock dut | MockDut | mockDut | ~~MockDUT~~ FIFO Generator | FifoGenerator | fifoGenerator | ~~FIFOGenerator~~ ``` -------------------------------- ### REPL Help Command Source: https://github.com/chipsalliance/chisel/wiki/Debugging-with-the-Interpreter-REPL-2 Displays a list of available commands in the interpreter REPL. Use this to understand the debugging capabilities. ```text load fileName load/replace the current firrtl file script fileName load a script from a text file run [linesToRun|all|list|reset] run loaded script vcd [load|run|list|test|help] control vcd input file record-vcd []|[done] firrtl_interpreter.vcd loaded script type regex show the current type of things matching the regex poke inputPortName value set an input port to the given integer value mempoke memory-instance-name index value set memory at index to value rpoke regex value poke value into ports that match regex eval componentName show the computation of the component peek componentName show the current value of the named circuit component mempeek memory-instance-name index peek memory at index rpeek regex show the current value of things matching the regex randomize randomize all inputs except reset) poison poison everything) reset [numberOfSteps] assert reset (if present) for numberOfSteps (default 1) step [numberOfSteps] cycle the clock numberOfSteps (default 1) times, and show state waitfor componentName value [maxNumberOfSteps] wait for particular value (default 1) on component, up to maxNumberOfSteps (default 100) show [state|input|lofirrtl] show useful things info show information about the circuit timing [clear|bin] show the current timing state verbose [true|false|toggle] set evaluator verbose mode (default toggle) during dependency evaluation eval-all [true|false|toggle] set evaluator to execute un-needed branches (default toggle) during dependency evaluation allow-cycles [true|false|toggle] set evaluator allow combinational loops (could cause correctness problems ordered-exec [true|false|toggle] set evaluator execute circuit in dependency order, now recursive component evaluation help show available commands quit exit the interpreter ``` -------------------------------- ### Instantiate CSR Module with Description Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/explanations/properties.md Creates a hardware module that includes a CSR and its description. Instantiate a `CSRDescription` object, connect its input properties, and assign a reference to the object to a property port. ```scala // A hardware module representing a CSR and its description. class CSRModule( csrDescDef: Definition[CSRDescription], width: Int, identifierStr: String, descriptionStr: String) extends Module { override def desiredName = identifierStr // Create a hardware port for the CSR value. val value = IO(Output(UInt(width.W))) // Create a property port for a reference to the CSR description object. val description = IO(Output(csrDescDef.getPropertyType)) // Instantiate a CSR description object, and connect its input properties. val csrDescription = Instance(csrDescDef) csrDescription.identifierIn := Property(identifierStr) csrDescription.descriptionIn := Property(descriptionStr) csrDescription.widthIn := Property(width) // Create a register for the hardware CSR. A real implementation would be more involved. val csr = RegInit(0.U(width.W)) // Assign the CSR value to the hardware port. value := csr // Assign a reference to the CSR description object to the property port. ``` -------------------------------- ### Generate SystemVerilog for Bundle Literal Example Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/appendix/experimental-features.md This snippet demonstrates how to emit SystemVerilog for a Chisel module that uses Bundle literals. ```scala chisel3.docs.emitSystemVerilog(new Example) ``` -------------------------------- ### Change Default Testing Directory Source: https://github.com/chipsalliance/chisel/blob/main/docs/src/cookbooks/testing.md Override the `buildDir` method to change the default testing directory. Example sets it to `test/`. ```scala import chisel3._ import chisel3.simulator.scalatest.ChiselSim import java.nio.file.Paths import org.scalatest.funspec.AnyFunSpec class FooSpec extends FunSpec with ChiselSim { override def buildDir: Path = Paths.get("test") } ``` -------------------------------- ### Printf and Simulation Logging Source: https://context7.com/chipsalliance/chisel/llms.txt Demonstrates using `printf` with the `cf` interpolator for formatted simulation messages and `SimLog` for logging to files. Includes assertions. ```scala import chisel3._ import chisel3.simulator.SimLog class DebugModule extends Module { val io = IO(new Bundle { val addr = Input(UInt(32.W)) val data = Input(UInt(32.W)) val write = Input(Bool()) }) // cf interpolator: %d=decimal (default), %x=hex, %b=binary when (io.write) { printf(cf"[WRITE] addr=0x${io.addr}%x data=${io.data}%d\n") } // C-style printf printf("Simulation cycle: addr=%d, write=%b\n", io.addr, io.write) // Log to a file (simulation only) val log = SimLog.file("debug.log") log.printf(cf"addr=0x${io.addr}%x data=0x${io.data}%x\n") // Assertion with message assert(io.addr < 1024.U, "Address %d out of range!", io.addr) } ``` -------------------------------- ### Identity Transform Implementation Source: https://github.com/chipsalliance/chisel/wiki/Annotations-Extending-Chisel-and-Firrtl An example of a Firrtl Transform that performs no modifications to the circuit state. Useful as a base for more complex transforms. ```scala class IdentityTransform extends Transform { override def inputForm: CircuitForm = LowForm override def outputForm: CircuitForm = LowForm override def execute(state: CircuitState): CircuitState = { getMyAnnotations(state) match { case Nil => state case myAnnotations => // Use annotations contained in the myAnnotations list to modify state // and return that modified state. state } } } ``` -------------------------------- ### Generate Test Coverage Report with sbt Source: https://github.com/chipsalliance/chisel/wiki/Test-Coverage Execute these sbt commands to clean the project, run tests, and generate a coverage report. The report will be available in the target directory. ```bash sbt clean coverage test ``` ```bash sbt coverageReport ``` -------------------------------- ### Test Chisel Mux2 Circuit with PeekPokeTester Source: https://github.com/chipsalliance/chisel/wiki/Tutorial-Problems This example demonstrates how to test a Mux2 circuit using PeekPokeTester. It iterates through all possible input combinations, setting values with poke, advancing the simulation with step, and verifying the output with expect. ```scala class Mux2Tests(c: Mux2, b: Option[TesterBackend] = None) extends PeekPokeTester(c, _backend=b) { val n = pow(2, 3).toInt for (s <- 0 until 2) { for (i0 <- 0 until 2) { for (i1 <- 0 until 2) { poke(c.io.sel, s) poke(c.io.in1, i1) poke(c.io.in0, i0) step(1) expect(c.io.out, (if (s == 1) i1 else i0)) }} } } ```