Commit e66a649d authored by apaj's avatar apaj

Initial Journey: adding all examples from chisel-tutorial, as-is

parent 9df164a5
def scalacOptionsVersion(scalaVersion: String): Seq[String] = {
Seq() ++ {
// If we're building with Scala > 2.11, enable the compile option
// switch to support our anonymous Bundle definitions:
// https://github.com/scala/bug/issues/10047
CrossVersion.partialVersion(scalaVersion) match {
case Some((2, scalaMajor: Int)) if scalaMajor < 12 => Seq()
case _ => Seq("-Xsource:2.11")
}
}
}
def javacOptionsVersion(scalaVersion: String): Seq[String] = {
Seq() ++ {
// Scala 2.12 requires Java 8. We continue to generate
// Java 7 compatible code for Scala 2.11
// for compatibility with old clients.
CrossVersion.partialVersion(scalaVersion) match {
case Some((2, scalaMajor: Int)) if scalaMajor < 12 =>
Seq("-source", "1.7", "-target", "1.7")
case _ =>
Seq("-source", "1.8", "-target", "1.8")
}
}
}
organization := "edu.berkeley.cs"
version := "3.0.0"
name := "chisel-tutorial"
scalaVersion := "2.11.11"
crossScalaVersions := Seq("2.11.11", "2.12.3")
scalacOptions ++= Seq("-deprecation", "-feature", "-unchecked", "-language:reflectiveCalls")
// Provide a managed dependency on X if -DXVersion="" is supplied on the command line.
// The following are the default development versions, not the "release" versions.
val defaultVersions = Map(
"chisel3" -> "3.0.+",
"chisel-iotesters" -> "1.1.+"
)
libraryDependencies ++= (Seq("chisel3","chisel-iotesters").map {
dep: String => "edu.berkeley.cs" %% dep % sys.props.getOrElse(dep + "Version", defaultVersions(dep)) })
resolvers ++= Seq(
Resolver.sonatypeRepo("snapshots"),
Resolver.sonatypeRepo("releases")
)
// Recommendations from http://www.scalatest.org/user_guide/using_scalatest_with_sbt
logBuffered in Test := false
// Disable parallel execution when running tests.
// Running tests in parallel on Jenkins currently fails.
parallelExecution in Test := false
scalacOptions ++= scalacOptionsVersion(scalaVersion.value)
javacOptions ++= javacOptionsVersion(scalaVersion.value)
# Building the docs on osx will require to install Jinja2 and BeautifulSoup:
# $ pip install Jinja2 BeautifulSoup
# and the different tools for text to pdf:
# $ port install texlive-latex-extra texlive-latex-recommended \
# texlive-htmlxml ImageMagick
#
# For building on Ubuntu 14.04 LTS, the following packages should be
# installed with "apt-get install":
# python-bs4 imagemagick source-highlight tex4ht texlive-latex-base \
# texlive-latex-recommended texlive-latex-extra texlive-fonts-recommended \
# texlive-fonts-extra
PDFLATEX := pdflatex
WWW_PAGES :=
WWW_EXTRA :=
# The following subdirectories build documentation correctly.
PDF_DIRS := tutorial
# Define a function to map PDF_DIRS to a PDF base name.
# Basically, every directory is the base name of the pdf except for dac12-talk.
pdf_base_name_from_dir = $(subst talks/dac12,dac12-talk,$(1))
# Define a map function to apply a function to multiple arguments.
map = $(foreach arg,$(2),$(call $(1),$(arg)))
PDFS := $(addsuffix .pdf,$(addprefix chisel-,$(call map,pdf_base_name_from_dir,$(PDF_DIRS))))
# Suffixes for tex temporary files we'll clean
TEX_SUFFIXES := 4ct 4tc aux css dvi html idv lg log out tmp xref
TEX_TEMP_FILES := $(foreach dir,$(PDF_DIRS),$(foreach suffix,$(TEX_SUFFIXES),$(dir)/$(call pdf_base_name_from_dir,$(dir)).$(suffix)))
STY_TEMP_FILES := $(foreach dir,$(PDF_DIRS),$(dir)/$(call pdf_base_name_from_dir,$(dir))_date.sty)
LATEX2MAN := latex2man
MAN_PAGES := chisel.man
srcDir := .
installTop:= ../www
toolDir ?= ../../chisel-doc/bin
vpath %.tex $(addprefix $(srcDir)/,$(PDF_DIRS))
vpath %.mtt $(addprefix $(srcDir)/,$(PDF_DIRS))
all: $(WWW_PAGES) $(WWW_EXTRA) $(PDFS)
extra: $(WWW_EXTRA)
html: $(WWW_PAGES)
pdf: $(PDFS)
install: all
# NOTE: We follow the recommended practice of running the *latex tools twice
# so references (citations and figures) are correctly handled.
# NOTE: There are problems with running pdflatex after htlatex due to the
# manual.aux file left over by the latter. We see:
# ./manual.tex:113: Undefined control sequence.
# <argument> ...tring :autoref\endcsname {\@captype
# }1
# l.113 Figure~\ref{fig:node-hierarchy}
# This was reported at:
# http://tex.stackexchange.com/questions/117802/running-pdflatex-after-htlatex-causes-hyperref-error-undefined-control-sequence
# but apparently went away after upgrading to texlive 2013.
# It fails on ubuntu 14.04 LTS and texlive-latex-recommended 2013.20140215-1
# if we don't remove the manual.aux file
chisel-%.pdf: %.tex %_date.sty
rm -f $(subst .tex,.aux,$<)
cd $(dir $<) && for c in 0 1; do pdflatex -file-line-error -interaction nonstopmode -output-directory $(PWD) $(notdir $<) ; done
mv $(subst .tex,.pdf,$(notdir $<)) $@
%.html: %.tex %_date.sty
cd $(dir $<) && for c in 0 1; do htlatex $(notdir $<) $(PWD)/$(srcDir)/html.cfg "" -d/$(PWD)/ ; done
mv $(subst .tex,.html,$(notdir $<)) $@~
$(toolDir)/tex2html.py $@~ $@
%.man: %.mtt
# cd into the directory containing the .tex file and massage it
cd $(dir $<) && \
sed -e "s/@VERSION@/$(RELEASE_TAG)/" -e "s/@DATE@/$(RELEASE_DATE)/" $(notdir $<) > $(basename $@).ttex ;\
latex2man $(basename $@).ttex $@
%.html: $(srcDir)/templates/%.html $(srcDir)/templates/base.html
$(toolDir)/jinja2html.py $(notdir $<) $@
clean:
-rm -f $(TEX_TEMP_FILES)
-rm -f $(STY_TEMP_FILES)
# Remove any .{png,graffle} files that are created from pdfs
-rm -f $(foreach gext,png graffle,$(subst .pdf,.$(gext),$(wildcard tutorial/figs/*.pdf)))
-rm -f $(WWW_PAGES) $(PDFS) $(WWW_EXTRA) $(addsuffix .1,$(WWW_EXTRA)) $(patsubst %.html,%.css,$(WWW_EXTRA))
-rm -f *~ *.aux *.log *.nav *.out *.snm *.toc *.vrb
-rm -f *.jpg *.png
# Generate a date (optional) for the document based on the latest
# git commit of any of its (obvious) constituent parts.
%_date.sty: %.tex
for f in $(wildcard $(dir $<)*.tex); do git log -n 1 --format="%at" -- $$f; done | sort -nr | head -1 | gawk '{print "\\date{",strftime("%B %e, %Y", $$1),"}"}' > $@
cmp $@ $(dir $<)$@ || cp $@ $(dir $<)
\Preamble{xhtml}
\Configure{graphics*}
{pdf}
{\Needs{"convert \csname Gin@base\endcsname.pdf
\csname Gin@base\endcsname.png"}%
\Picture[pict]{\csname Gin@base\endcsname.png}%
}
\begin{document}
\EndPreamble
% "define" Scala
\usepackage[T1]{fontenc}
\usepackage[scaled=0.82]{beramono}
\usepackage{microtype}
\sbox0{\small\ttfamily A}
\edef\mybasewidth{\the\wd0 }
\lstdefinelanguage{scala}{
morekeywords={abstract,case,catch,class,def,%
do,else,extends,false,final,finally,%
for,if,implicit,import,match,mixin,%
new,null,object,override,package,%
private,protected,requires,return,sealed,%
super,this,throw,trait,true,try,%
type,val,var,while,with,yield},
sensitive=true,
morecomment=[l]{//},
morecomment=[n]{/*}{*/},
morestring=[b]",
morestring=[b]',
morestring=[b]"""
}
\usepackage{color}
\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}
% Default settings for code listings
\lstset{frame=tb,
language=scala,
aboveskip=3mm,
belowskip=3mm,
showstringspaces=false,
columns=fixed, % basewidth=\mybasewidth,
basicstyle={\small\ttfamily},
numbers=none,
numberstyle=\footnotesize\color{gray},
% identifierstyle=\color{red},
keywordstyle=\color{blue},
commentstyle=\color{dkgreen},
stringstyle=\color{mauve},
frame=single,
breaklines=true,
breakatwhitespace=true,
procnamekeys={def, val, var, class, trait, object, extends},
procnamestyle=\ttfamily\color{red},
tabsize=2
}
\lstnewenvironment{scala}[1][]
{\lstset{language=scala,#1}}
{}
\lstnewenvironment{cpp}[1][]
{\lstset{language=C++,#1}}
{}
\lstnewenvironment{bash}[1][]
{\lstset{language=bash,#1}}
{}
\lstnewenvironment{verilog}[1][]
{\lstset{language=verilog,#1}}
{}
\lstset{basicstyle={\footnotesize\ttfamily}}
\usetheme[height=8mm]{Rochester}
\setbeamersize{text margin left=3mm}
\setbeamersize{text margin right=3mm}
\setbeamertemplate{navigation symbols}{}
\definecolor{Cobalt}{rgb}{0.25,0.125,0.70}
\definecolor{RedOrange}{rgb}{0.8,0.25,0.0}
% \definecolor{RedOrange}{rgb}{0.8,0.775,0.25}
\def\frametitledefaultcolor{Cobalt}
\def\frametitleproblemcolor{RedOrange}
\lstset{basicstyle={\footnotesize\ttfamily}}
\setbeamertemplate{frametitle}
{
\vskip-7mm
\textbf{\insertframetitle}\hfill\insertframenumber
}
\setbeamercolor{frametitle}{bg=\frametitledefaultcolor}
\newenvironment{sample}{\VerbatimEnvironment\begin{footnotesize}\begin{semiverbatim}}{\end{semiverbatim}\end{footnotesize}}
\newenvironment{FramedSemiVerb}%
{\begin{Sbox}\begin{minipage}{.94\textwidth}\begin{semiverbatim}}%
{\end{semiverbatim}\end{minipage}\end{Sbox}
\setlength{\fboxsep}{8pt}\fbox{\TheSbox}}
\newenvironment{FramedVerb}%
{\VerbatimEnvironment
\begin{Sbox}\begin{minipage}{.94\textwidth}\begin{Verbatim}}%
{\end{Verbatim}\end{minipage}\end{Sbox}
\setlength{\fboxsep}{8pt}\fbox{\TheSbox}}
% \newenvironment{sample}{\VerbatimEnvironment\begin{footnotesize}\begin{Verbatim}}{\end{Verbatim}\end{footnotesize}}
\newcommand{\code}[1]{\begin{footnotesize}{\tt #1}\end{footnotesize}}
\newcommand{\comment}[1]{{\color{Green}\it\smaller #1}}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
sbt.version = 0.13.16
#!/usr/bin/env bash
args=$@
sbt -v "test:run-main examples.Launcher $args"
#!/usr/bin/env bash
args=$@
sbt "test:run-main problems.Launcher $args"
#!/usr/bin/env bash
args=$@
sbt "test:run-main solutions.Launcher $args"
// See LICENSE.txt for license details.
package examples
import chisel3._
//A n-bit adder with carry in and carry out
class Adder(val n:Int) extends Module {
val io = IO(new Bundle {
val A = Input(UInt(n.W))
val B = Input(UInt(n.W))
val Cin = Input(UInt(1.W))
val Sum = Output(UInt(n.W))
val Cout = Output(UInt(1.W))
})
//create an Array of FullAdders
// NOTE: Since we do all the wiring during elaboration and not at run-time,
// i.e., we don't need to dynamically index into the data structure at run-time,
// we use an Array instead of a Vec.
val FAs = Array.fill(n)(Module(new FullAdder()).io)
val carry = Wire(Vec(n+1, UInt(1.W)))
val sum = Wire(Vec(n, Bool()))
//first carry is the top level carry in
carry(0) := io.Cin
//wire up the ports of the full adders
for (i <- 0 until n) {
FAs(i).a := io.A(i)
FAs(i).b := io.B(i)
FAs(i).cin := carry(i)
carry(i+1) := FAs(i).cout
sum(i) := FAs(i).sum.toBool()
}
io.Sum := sum.asUInt
io.Cout := carry(n)
}
// See LICENSE.txt for license details.
package examples
import chisel3._
import chisel3.util._
//A 4-bit adder with carry in and carry out
class Adder4 extends Module {
val io = IO(new Bundle {
val A = Input(UInt(4.W))
val B = Input(UInt(4.W))
val Cin = Input(UInt(1.W))
val Sum = Output(UInt(4.W))
val Cout = Output(UInt(1.W))
})
//Adder for bit 0
val Adder0 = Module(new FullAdder())
Adder0.io.a := io.A(0)
Adder0.io.b := io.B(0)
Adder0.io.cin := io.Cin
val s0 = Adder0.io.sum
//Adder for bit 1
val Adder1 = Module(new FullAdder())
Adder1.io.a := io.A(1)
Adder1.io.b := io.B(1)
Adder1.io.cin := Adder0.io.cout
val s1 = Cat(Adder1.io.sum, s0)
//Adder for bit 2
val Adder2 = Module(new FullAdder())
Adder2.io.a := io.A(2)
Adder2.io.b := io.B(2)
Adder2.io.cin := Adder1.io.cout
val s2 = Cat(Adder2.io.sum, s1)
//Adder for bit 3
val Adder3 = Module(new FullAdder())
Adder3.io.a := io.A(3)
Adder3.io.b := io.B(3)
Adder3.io.cin := Adder2.io.cout
io.Sum := Cat(Adder3.io.sum, s2).asUInt
io.Cout := Adder3.io.cout
}
// See LICENSE.txt for license details.
package examples
import chisel3._
class ByteSelector extends Module {
val io = IO(new Bundle {
val in = Input(UInt(32.W))
val offset = Input(UInt(2.W))
val out = Output(UInt(8.W))
})
io.out := 0.U(8.W)
when (io.offset === 0.U(2.W)) {
io.out := io.in(7,0)
} .elsewhen (io.offset === 1.U) {
io.out := io.in(15,8)
} .elsewhen (io.offset === 2.U) {
io.out := io.in(23,16)
} .otherwise {
io.out := io.in(31,24)
}
}
// See LICENSE.txt for license details.
package examples
import chisel3._
class Combinational extends Module {
val io = IO(new Bundle {
val x = Input(UInt(16.W))
val y = Input(UInt(16.W))
val z = Output(UInt(16.W))
})
io.z := io.x + io.y
}
// See LICENSE.txt for license details.
package examples
import chisel3._
class Darken extends Module {
val io = IO(new Bundle {
val in = Input(UInt(8.W))
val out = Output(UInt(8.W))
})
io.out := io.in << 1.U
}
// See LICENSE.txt for license details.
package examples
import chisel3._
class EnableShiftRegister extends Module {
val io = IO(new Bundle {
val in = Input(UInt(4.W))
val shift = Input(Bool())
val out = Output(UInt(4.W))
})
val r0 = Reg(UInt())
val r1 = Reg(UInt())
val r2 = Reg(UInt())
val r3 = Reg(UInt())
when(reset.toBool) {
r0 := 0.U(4.W)
r1 := 0.U(4.W)
r2 := 0.U(4.W)
r3 := 0.U(4.W)
} .elsewhen(io.shift) {
r0 := io.in
r1 := r0
r2 := r1
r3 := r2
}
io.out := r3
}
// See LICENSE.txt for license details.
package examples
import chisel3._
class FullAdder extends Module {
val io = IO(new Bundle {
val a = Input(UInt(1.W))
val b = Input(UInt(1.W))
val cin = Input(UInt(1.W))
val sum = Output(UInt(1.W))
val cout = Output(UInt(1.W))
})
// Generate the sum
val a_xor_b = io.a ^ io.b
io.sum := a_xor_b ^ io.cin
// Generate the carry
val a_and_b = io.a & io.b
val b_and_cin = io.b & io.cin
val a_and_cin = io.a & io.cin
io.cout := a_and_b | b_and_cin | a_and_cin
}
// See LICENSE.txt for license details.
package examples
import chisel3._
class Functionality extends Module {
val io = IO(new Bundle {
val x = Input(UInt(16.W))
val y = Input(UInt(16.W))
val z = Output(UInt(16.W))
})
def clb(a: UInt, b: UInt, c: UInt, d: UInt) =
(a & b) | (~c & d)
io.z := clb(io.x, io.y, io.x, io.y)
}
// See LICENSE.txt for license details.
package examples
import chisel3._
class GCD extends Module {
val io = IO(new Bundle {
val a = Input(UInt(16.W))
val b = Input(UInt(16.W))
val e = Input(Bool())
val z = Output(UInt(16.W))
val v = Output(Bool())
})
val x = Reg(UInt())
val y = Reg(UInt())
when (x > y) {
x := x - y
}
.elsewhen (x <= y) { y := y - x }
when (io.e) { x := io.a; y := io.b }
io.z := x
io.v := y === 0.U
}
\ No newline at end of file
// See LICENSE.txt for license details.
package examples
import chisel3._
//A 4-bit adder with carry in and carry out
class HiLoMultiplier() extends Module {
val io = IO(new Bundle {
val A = Input(UInt(16.W))
val B = Input(UInt(16.W))
val Hi = Output(UInt(16.W))
val Lo = Output(UInt(16.W))
})
val mult = io.A * io.B
io.Lo := mult(15, 0)
io.Hi := mult(31, 16)
}
// See LICENSE.txt for license details.
package examples
import chisel3._
import chisel3.util.log2Ceil
class Cell extends Module {
//noinspection TypeAnnotation
val io = IO(new Bundle {
val neighbors = Vec(8, Input(Bool()))
val out = Output(Bool())
val running = Input(Bool())
val writeEnable = Input(Bool())
val writeValue = Input(Bool())
})
val isAlive = RegInit(false.B)
when(!io.running) {
when(io.writeEnable) {
isAlive := io.writeValue
}
.otherwise {
isAlive := isAlive
}
}.otherwise {
val count = io.neighbors.foldRight(0.U(3.W))((x: Bool, y: UInt) => x.asUInt + y)
when(isAlive) {
when(count < 2.U) {
isAlive := false.B
}.elsewhen(count < 4.U) {
isAlive := true.B
}.otherwise {
isAlive := false.B
}
}.otherwise {
when(!isAlive && count === 3.U) {
isAlive := true.B
}
.otherwise {
isAlive := false.B
}
}
}
io.out := isAlive
}
class Life(val rows: Int, val cols: Int) extends Module {
//noinspection TypeAnnotation
val io = IO(new Bundle {
val state = Output(Vec(rows, Vec(cols, Bool())))
val running = Input(Bool())
val writeValue = Input(Bool())
val writeRowAddress = Input(UInt(log2Ceil(rows+1).W))
val writeColAddress = Input(UInt(log2Ceil(cols+1).W))
})
private val cells = Array.fill(rows, cols)(Module(new Cell))
for {
row <- 0 until rows
col <- 0 until cols
} {
io.state(row)(col) := cells(row)(col).io.out
cells(row)(col).io.running := io.running
cells(row)(col).io.writeValue := io.writeValue
cells(row)(col).io.writeEnable := io.writeRowAddress === row.U & io.writeColAddress === col.U
}
def getNeighborIndex(row: Int, rowDelta: Int, col: Int, colDelta: Int): (Int, Int) = {
def wrapIndex(index: Int, delta: Int, max: Int): Int = {
if(index == 0 && delta == -1) { max - 1 }
else if(index == max - 1 && delta == 1) { 0 }
else { index + delta }
}
(wrapIndex(row, rowDelta, rows), wrapIndex(col, colDelta, cols))
}
// for every cell wire it up to it's neighbors, edges wrap, world is a torus
for (row <- 0 until rows) {
for (col <- 0 until cols) {
val cell = cells(row)(col)
var neighborInput = 0
for (deltaRow <- -1 to 1) {
for (deltaCol <- -1 to 1) {
if (deltaRow != 0 || deltaCol != 0) {
val (rowIndex, colIndex) = getNeighborIndex(row, deltaRow, col, deltaCol)
cell.io.neighbors(neighborInput) := cells(rowIndex)(colIndex).io.out
neighborInput = neighborInput + 1
}
}
}
}
}
}
\ No newline at end of file
// See LICENSE.txt for license details.
package examples
import chisel3._
class LogShifter extends Module {
val io = IO(new Bundle {
val in = Input(UInt(16.W))
val shamt = Input(UInt(4.W))
val out = Output(UInt(16.W))
})
val s0 = RegInit(0.U(16.W))
when (io.shamt(3) === 1.U) {
s0 := io.in << 8.U
} .otherwise {
s0 := io.in
}