Compare commits

...

4 commits

Author SHA1 Message Date
f1a575b2fd
npc: basic architecture implementation 2024-03-13 14:53:31 +08:00
d67fb1138a
npc: Register File 2024-03-11 21:41:45 +08:00
tracer-ysyx
64f891308e > configure(npc)
ysyx_22040000 李心杨
 Linux calcite 6.6.19 #1-NixOS SMP PREEMPT_DYNAMIC Fri Mar  1 12:35:11 UTC 2024 x86_64 GNU/Linux
  18:16:48  up   3:36,  2 users,  load average: 0.28, 0.25, 0.34
2024-03-07 18:16:48 +08:00
833cf7b6d1
pa2.1: add M extension support, finish pa2.1 2024-03-07 13:19:12 +08:00
16 changed files with 555 additions and 197 deletions

View file

@ -17,7 +17,7 @@
}; };
in in
{ {
packages.nemu = pkgs.callPackage ./nemu {}; packages.nemu = pkgs.callPackage ./nemu { am-kernels = self.packages.${system}.am-kernels; };
packages.am-kernels = crossPkgs.stdenv.mkDerivation rec { packages.am-kernels = crossPkgs.stdenv.mkDerivation rec {
pname = "am-kernels"; pname = "am-kernels";
@ -44,12 +44,13 @@
''; '';
buildPhase = '' buildPhase = ''
AS=$CC make -C tests/cpu-tests BUILD_DIR=$(pwd)/build ARCH=$ARCH --trace AS=$CC make -C tests/cpu-tests BUILD_DIR=$(pwd)/build ARCH=$ARCH
''; '';
installPhase = '' installPhase = ''
mkdir -p $out/bin mkdir -p $out/share/images $out/share/dump
cp build/riscv32-nemu/*.bin $out/bin cp build/riscv32-nemu/*.bin $out/share/images
cp build/riscv32-nemu/*.txt $out/share/dump
''; '';
dontFixup = true; dontFixup = true;
@ -60,6 +61,15 @@
gdb gdb
] ++ builtins.attrValues self.packages.${system}; ] ++ builtins.attrValues self.packages.${system};
}; };
devShells.nemu = pkgs.mkShell {
packages = with pkgs; [
clang-tools
];
inputsFrom = [
self.packages.${system}.nemu
];
};
} }
); );
} }

View file

@ -1,17 +1,17 @@
/*************************************************************************************** /***************************************************************************************
* Copyright (c) 2014-2022 Zihao Yu, Nanjing University * Copyright (c) 2014-2022 Zihao Yu, Nanjing University
* *
* NEMU is licensed under Mulan PSL v2. * NEMU is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan
* You may obtain a copy of Mulan PSL v2 at: *PSL v2. You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2 * http://license.coscl.org.cn/MulanPSL2
* *
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, *KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. *NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* *
* See the Mulan PSL v2 for more details. * See the Mulan PSL v2 for more details.
***************************************************************************************/ ***************************************************************************************/
#include "common.h" #include "common.h"
#include "local-include/reg.h" #include "local-include/reg.h"
@ -36,7 +36,8 @@ enum {
#define immB() do { *imm = SEXT(BITS(i, 31, 31), 1) << 12 | BITS(i, 30, 25) << 5 | BITS(i, 11, 8) << 1 | BITS(i, 7, 7) << 11; } while(0) #define immB() do { *imm = SEXT(BITS(i, 31, 31), 1) << 12 | BITS(i, 30, 25) << 5 | BITS(i, 11, 8) << 1 | BITS(i, 7, 7) << 11; } while(0)
#define immJ() do { *imm = SEXT(BITS(i, 31, 31), 1) << 20 | BITS(i, 30, 21) << 1 | BITS(i, 20, 20) << 11 | BITS(i, 19, 12) << 12; } while(0) #define immJ() do { *imm = SEXT(BITS(i, 31, 31), 1) << 20 | BITS(i, 30, 21) << 1 | BITS(i, 20, 20) << 11 | BITS(i, 19, 12) << 12; } while(0)
static void decode_operand(Decode *s, int *rd, word_t *src1, word_t *src2, word_t *imm, int type) { static void decode_operand(Decode *s, int *rd, word_t *src1, word_t *src2,
word_t *imm, int type) {
uint32_t i = s->isa.inst.val; uint32_t i = s->isa.inst.val;
int rs1 = BITS(i, 19, 15); int rs1 = BITS(i, 19, 15);
int rs2 = BITS(i, 24, 20); int rs2 = BITS(i, 24, 20);
@ -100,8 +101,6 @@ static int decode_exec(Decode *s) {
INSTPAT("0000000 ????? ????? 001 ????? 00100 11", slli , I, R(rd) = src1 << imm); INSTPAT("0000000 ????? ????? 001 ????? 00100 11", slli , I, R(rd) = src1 << imm);
INSTPAT("0000000 ????? ????? 101 ????? 00100 11", srli , I, R(rd) = src1 >> imm); INSTPAT("0000000 ????? ????? 101 ????? 00100 11", srli , I, R(rd) = src1 >> imm);
INSTPAT("0100000 ????? ????? 101 ????? 00100 11", srai , I, R(rd) = (sword_t)src1 >> (imm & 0x01F)); INSTPAT("0100000 ????? ????? 101 ????? 00100 11", srai , I, R(rd) = (sword_t)src1 >> (imm & 0x01F));
INSTPAT("0000000 ????? ????? 000 ????? 01100 11", add , R, R(rd) = src1 + src2); INSTPAT("0000000 ????? ????? 000 ????? 01100 11", add , R, R(rd) = src1 + src2);
INSTPAT("0100000 ????? ????? 000 ????? 01100 11", sub , R, R(rd) = src1 - src2); INSTPAT("0100000 ????? ????? 000 ????? 01100 11", sub , R, R(rd) = src1 - src2);
INSTPAT("0000000 ????? ????? 001 ????? 01100 11", sll , R, R(rd) = src1 << src2); INSTPAT("0000000 ????? ????? 001 ????? 01100 11", sll , R, R(rd) = src1 << src2);
@ -114,6 +113,17 @@ static int decode_exec(Decode *s) {
INSTPAT("0000000 ????? ????? 111 ????? 01100 11", and , R, R(rd) = src1 & src2); INSTPAT("0000000 ????? ????? 111 ????? 01100 11", and , R, R(rd) = src1 & src2);
INSTPAT("0000000 00001 00000 000 00000 11100 11", ebreak , N, NEMUTRAP(s->pc, R(10))); // R(10) is $a0 INSTPAT("0000000 00001 00000 000 00000 11100 11", ebreak , N, NEMUTRAP(s->pc, R(10))); // R(10) is $a0
// "M"
INSTPAT("0000001 ????? ????? 000 ????? 01100 11", mul , R, R(rd) = src1 * src2);
INSTPAT("0000001 ????? ????? 001 ????? 01100 11", mulh , R, R(rd) = (int64_t)(sword_t)src1 * (sword_t)src2 >> 32);
INSTPAT("0000001 ????? ????? 010 ????? 01100 11", mulhsu , R, R(rd) = (int64_t)(sword_t)src1 * (uint64_t)src2 >> 32);
INSTPAT("0000001 ????? ????? 011 ????? 01100 11", mulhu , R, R(rd) = (uint64_t)src1 * (uint64_t)src2 >> 32);
INSTPAT("0000001 ????? ????? 100 ????? 01100 11", div , R, R(rd) = (sword_t)src1 / (sword_t)src2);
INSTPAT("0000001 ????? ????? 101 ????? 01100 11", divu , R, R(rd) = src1 / src2);
INSTPAT("0000001 ????? ????? 110 ????? 01100 11", rem , R, R(rd) = (sword_t)src1 % (sword_t)src2);
INSTPAT("0000001 ????? ????? 111 ????? 01100 11", remu , R, R(rd) = src1 % src2);
INSTPAT("??????? ????? ????? ??? ????? ????? ??", inv , N, INV(s->pc)); INSTPAT("??????? ????? ????? ??? ????? ????? ??", inv , N, INV(s->pc));
INSTPAT_END(); INSTPAT_END();

View file

@ -1,6 +1,6 @@
cmake_minimum_required(VERSION 3.20) cmake_minimum_required(VERSION 3.20)
project(npc) project(flow)
set (CMAKE_CXX_STANDARD 11) set (CMAKE_CXX_STANDARD 11)
cmake_policy(SET CMP0144 NEW) cmake_policy(SET CMP0144 NEW)
@ -17,7 +17,7 @@ find_package(verilator REQUIRED)
find_library(NVBOARD_LIBRARY NAMES nvboard) find_library(NVBOARD_LIBRARY NAMES nvboard)
find_path(NVBOARD_INCLUDE_DIR NAMES nvboard.h) find_path(NVBOARD_INCLUDE_DIR NAMES nvboard.h)
set(TOPMODULES "Switch" "Keyboard") set(TOPMODULES "Flow")
foreach(TOPMODULE IN LISTS TOPMODULES) foreach(TOPMODULE IN LISTS TOPMODULES)
@ -58,7 +58,7 @@ foreach(TOPMODULE IN LISTS TOPMODULES)
file(GLOB_RECURSE SOURCES csrc_nvboard/${TOPMODULE}/*.cpp) file(GLOB_RECURSE SOURCES csrc_nvboard/${TOPMODULE}/*.cpp)
add_executable(V${TOPMODULE}_nvboard ${SOURCES} ${CMAKE_CURRENT_BINARY_DIR}/${TOPMODULE}/auto_bind.cpp) add_executable(V${TOPMODULE}_nvboard ${SOURCES} ${CMAKE_CURRENT_BINARY_DIR}/${TOPMODULE}/auto_bind.cpp)
verilate(V${TOPMODULE}_nvboard TRACE COVERAGE THREADS verilate(V${TOPMODULE}_nvboard TRACE THREADS
TOP_MODULE ${TOPMODULE} TOP_MODULE ${TOPMODULE}
PREFIX V${TOPMODULE} PREFIX V${TOPMODULE}
SOURCES ${CMAKE_CURRENT_BINARY_DIR}/${TOPMODULE}/vsrc/${TOPMODULE}.v) SOURCES ${CMAKE_CURRENT_BINARY_DIR}/${TOPMODULE}/vsrc/${TOPMODULE}.v)

3
npc/constr/Flow.nxdc Normal file
View file

@ -0,0 +1,3 @@
top=Flow
io_clock(LD0)

View file

@ -2,14 +2,15 @@ ThisBuild / scalaVersion := "2.13.12"
ThisBuild / version := "0.1.0" ThisBuild / version := "0.1.0"
val chiselVersion = "5.1.0" val chiselVersion = "6.2.0"
lazy val root = (project in file(".")) lazy val root = (project in file("."))
.settings( .settings(
name := "ChiselLearning", name := "flow",
libraryDependencies ++= Seq( libraryDependencies ++= Seq(
"org.chipsalliance" %% "chisel" % chiselVersion, "org.chipsalliance" %% "chisel" % chiselVersion,
"edu.berkeley.cs" %% "chiseltest" % "5.0.2" % "test" "edu.berkeley.cs" %% "chiseltest" % "6.0.0" % "test",
"com.chuusai" %% "shapeless" % "2.3.3"
), ),
scalacOptions ++= Seq( scalacOptions ++= Seq(
"-language:reflectiveCalls", "-language:reflectiveCalls",

View file

@ -1,34 +1,63 @@
package npc.util package flow.components
import chisel3._ import chisel3._
import chisel3.util._ import chisel3.util._
import shapeless.{HNil, ::}
class ALUGenerator(width: Int) extends Module { class ALUControlInterface extends Bundle {
require(width >= 0) object OpSelect extends ChiselEnum {
val io = IO(new Bundle { val aOpAdd, aOpSub, aOpNot, aOpAnd, aOpOr, aOpXor, aOpSlt, aOpEq, aOpNop = Value
val a = Input(UInt(width.W)) }
val b = Input(UInt(width.W)) object SrcSelect extends ChiselEnum {
val op = Input(UInt(4.W)) val aSrcRs1, aSrcImm = Value
val out = Output(UInt(width.W)) }
val op = Input(OpSelect())
val src = Input(SrcSelect())
type CtrlTypes = OpSelect.Type :: SrcSelect.Type :: HNil
def ctrlBindPorts: CtrlTypes = {
op :: src :: HNil
}
}
class ALU[T <: UInt](tpe: T) extends Module {
val control = IO(new ALUControlInterface)
val in = IO(new Bundle {
val a = Input(Vec(control.SrcSelect.all.length, tpe))
val b = Input(tpe)
})
val out = IO(new Bundle {
val result = Output(tpe)
}) })
val adder_b = (Fill(width, io.op(0)) ^ io.b) + io.op(0) // take (-b) if sub val a = in.a(control.src.asUInt)
val add = io.a + adder_b
val and = io.a & io.b
val not = ~io.a
val or = io.a | io.b
val xor = io.a ^ io.b
val slt = io.a < io.b
val eq = io.a === io.b
io.out := MuxLookup(io.op, 0.U)(Seq( // val adder_b = (Fill(tpe.getWidth, io.op(0)) ^ io.b) + io.op(0) // take (-b) if sub
0.U -> add, val add = a + in.b
1.U -> add, // add with b reversed val sub = a - in.b
2.U -> not, val and = a & in.b
3.U -> and, val not = ~a
4.U -> or, val or = a | in.b
5.U -> xor, val xor = a ^ in.b
6.U -> slt, val slt = a < in.b
7.U -> eq, val eq = a === in.b
import control.OpSelect._
out.result := MuxLookup(control.op, 0.U)(Seq(
aOpAdd -> add,
aOpSub -> sub,
aOpNot -> not,
aOpAnd -> and,
aOpOr -> or,
aOpXor -> xor,
aOpSlt -> slt,
aOpEq -> eq
)) ))
} }
object ALU {
def apply[T <: UInt](tpe: T): ALU[T] = {
Module(new ALU(tpe))
}
}

View file

@ -1,33 +1,129 @@
package npc package flow
import scala.reflect.runtime.universe._
import chisel3._ import chisel3._
import chisel3.util.{MuxLookup, Fill, Decoupled, Counter, Queue, Reverse} import chisel3.util.{MuxLookup, Fill, Decoupled, Counter, Queue, Reverse}
import chisel3.util.{SRAM}
import chisel3.util.experimental.decode.{decoder, TruthTable}
import chisel3.stage.ChiselOption import chisel3.stage.ChiselOption
import npc.util.KeyboardSegController import chisel3.util.log2Ceil
import chisel3.util.BitPat
import chisel3.util.Enum
import chisel3.experimental.prefix
import shapeless.{HNil, ::}
import shapeless.HList
import shapeless.ops.coproduct.Prepend
import chisel3.util.{ BinaryMemoryFile, HexMemoryFile }
class Switch extends Module { object RV32Inst {
val io = IO(new Bundle { private val bp = BitPat
val sw = Input(Vec(2, Bool())) val addi = this.bp("b???????_?????_?????_000_?????_00100_11")
val out = Output(Bool()) val inv = this.bp("b???????_?????_?????_???_?????_?????_??")
})
io.out := io.sw(0) ^ io.sw(1)
} }
import npc.util.{PS2Port, KeyboardController, SegControllerGenerator} class PcControl(width: Int) extends Bundle {
object SrcSelect extends ChiselEnum {
class Keyboard extends Module { val pPC, pExeResult = Value
val io = IO(new Bundle { }
val ps2 = PS2Port() val srcSelect = Output(SrcSelect())
val segs = Output(Vec(8, UInt(8.W)))
})
val seg_handler = Module(new KeyboardSegController)
val keyboard_controller = Module(new KeyboardController)
seg_handler.io.keycode <> keyboard_controller.io.out
keyboard_controller.io.ps2 := io.ps2
io.segs := seg_handler.io.segs
} }
import flow.components.{RegControl, PcControlInterface, ALUControlInterface}
class Control(width: Int) extends Module {
val inst = IO(Input(UInt(width.W)))
val reg = IO(Flipped(new RegControl))
val pc = IO(Flipped(new PcControlInterface))
val alu = IO(Flipped(new ALUControlInterface))
// TODO: Add .ctrlTypes together instead of writing them by hand.
type T =
Bool :: reg.WriteSelect.Type :: pc.SrcSelect.Type :: alu.OpSelect.Type :: alu.SrcSelect.Type :: HNil
val dst: T = reg.ctrlBindPorts ++ pc.ctrlBindPorts ++ alu.ctrlBindPorts
val dstList = dst.toList
val reversePrefixSum = dstList.scanLeft(0)(_ + _.getWidth).reverse
val slices = reversePrefixSum.zip(reversePrefixSum.tail)
import reg.WriteSelect._
import pc.SrcSelect._
import alu.OpSelect._
import alu.SrcSelect._
import RV32Inst._
val ControlMapping: Array[(BitPat, T)] = Array(
// Regs :: PC :: Exe
// writeEnable :: writeSelect :: srcSelect ::
(addi, true.B :: rAluOut :: pStaticNpc :: aOpAdd :: aSrcImm :: HNil),
)
val default = BitPat.dontCare(dstList.map(_.getWidth).reduce(_ + _))
def toBits(t: T): BitPat = {
val list: List[Data] = t.toList
list.map(x => BitPat(x.litValue.toInt.U(x.getWidth.W))).reduceLeft(_ ## _)
}
val out = decoder(
inst,
TruthTable(ControlMapping.map(it => (it._1 -> toBits(it._2))), default))
val srcList = slices.map(s => out(s._1 - 1, s._2))
srcList
.zip(dstList.reverse)
.foreach({ case (src, dst) =>
dst := src.asTypeOf(dst)
})
}
import flow.components.{RegisterFile, RegFileInterface, ProgramCounter, ALU}
import chisel3.util.experimental.loadMemoryFromFileInline
class Flow extends Module {
val dataType = UInt(32.W)
val ram = SRAM(
size = 1024,
tpe = dataType,
numReadPorts = 2,
numWritePorts = 1,
numReadwritePorts = 0,
memoryFile = HexMemoryFile("./resource/addi.txt")
)
val control = Module(new Control(32))
val reg = RegisterFile(32, dataType, 2, 2)
val pc = Module(new ProgramCounter(dataType))
val alu = Module(new ALU(dataType))
ram.readPorts(0).enable := true.B
ram.readPorts(0).address := pc.out - 0x80000000L.U
val inst = ram.readPorts(0).data
import control.pc.SrcSelect._
pc.in.pcSrcs(pStaticNpc.litValue.toInt) := pc.out + 4.U
pc.in.pcSrcs(pBranchResult.litValue.toInt) := alu.out.result
control.inst := inst
reg.control <> control.reg
pc.control <> control.pc
alu.control <> control.alu
import control.reg.WriteSelect._
reg.in.writeData(rAluOut.litValue.toInt) := alu.out.result
// TODO: Read address in load command goes here
ram.readPorts(1).enable := false.B
ram.readPorts(1).address := 0.U
reg.in.writeData(rMemOut.litValue.toInt) := ram.readPorts(1).data
reg.in.writeAddr := inst(11, 7)
reg.in.rs(0) := inst(19, 15)
reg.in.rs(1) := inst(24, 20)
// TODO: Memory write goes here
ram.writePorts(0).address := 1.U
ram.writePorts(0).data := 1.U
ram.writePorts(0).enable := false.B
import control.alu.SrcSelect._
alu.in.a(aSrcRs1.litValue.toInt) := reg.out.src(0)
alu.in.a(aSrcImm.litValue.toInt) := inst(31, 20)
alu.in.b := reg.out.src(1)
dontTouch(control.out)
}

View file

@ -0,0 +1,39 @@
package flow.components
import chisel3._
import chisel3.util.{Valid, log2Ceil}
import chisel3.util.MuxLookup
import shapeless.{HNil, ::}
class PcControlInterface extends Bundle {
object SrcSelect extends ChiselEnum {
val pStaticNpc, pBranchResult = Value
}
val srcSelect = Input(SrcSelect())
type CtrlTypes = SrcSelect.Type :: HNil
def ctrlBindPorts: CtrlTypes = {
srcSelect :: HNil
}
}
class ProgramCounter[T <: Data](tpe: T) extends Module {
val control = IO(new PcControlInterface)
val in = IO(new Bundle {
val pcSrcs = Input(Vec(control.SrcSelect.all.length, tpe))
})
val out = IO(Output(tpe))
private val pc = RegInit(0x80000000L.U)
pc := in.pcSrcs(control.srcSelect.asUInt)
out := pc
}
object ProgramCounter {
def apply[T <: Data](tpe: T): ProgramCounter[T] = {
val pc = Module(new ProgramCounter(tpe))
pc
}
}

View file

@ -1,25 +1,86 @@
package npc.util package flow.components
import chisel3._ import chisel3._
import chisel3.util.log2Ceil
import chisel3.util.UIntToOH
import chisel3.util.MuxLookup
import shapeless.{ HNil, :: }
class RegisterFile(readPorts: Int) extends Module { class RegControl extends Bundle {
require(readPorts >= 0) object WriteSelect extends ChiselEnum {
val io = IO(new Bundle { val rAluOut, rMemOut = Value
val writeEnable = Input(Bool())
val writeAddr = Input(UInt(5.W))
val writeData = Input(UInt(32.W))
val readAddr = Input(Vec(readPorts, UInt(5.W)))
val readData = Output(Vec(readPorts, UInt(32.W)))
})
val regFile = RegInit(VecInit(Seq.fill(32)(0.U(32.W))))
for (i <- 1 until 32) {
regFile(i) := regFile(i)
} }
regFile(io.writeAddr) := Mux(io.writeEnable, io.writeData, regFile(io.writeAddr))
regFile(0) := 0.U
for (i <- 0 until readPorts) { val writeEnable = Input(Bool())
io.readData(i) := regFile(io.readAddr(i)) val writeSelect = Input(WriteSelect())
type CtrlTypes = Bool :: WriteSelect.Type :: HNil
def ctrlBindPorts: CtrlTypes = {
writeEnable :: writeSelect :: HNil
}
}
class RegFileData[T <: Data](size:Int, tpe: T, numReadPorts: Int, numWritePorts: Int) extends Bundle {
val write = new Bundle {
val addr = Input(UInt(size.W))
val data = Vec(numWritePorts, Input(tpe))
}
val read = Vec(numReadPorts, new Bundle {
val rs = Input(UInt(size.W))
val src = Output(tpe)
})
}
class RegFileInterface[T <: Data](size: Int, tpe: T, numReadPorts: Int, numWritePorts: Int) extends Bundle {
val control = new RegControl
// val data = new RegFileData(size, tpe, numReadPorts, numWritePorts)
val in = new Bundle {
val writeAddr = Input(UInt(size.W))
val writeData = Input(Vec(numWritePorts, tpe))
val rs = Input(Vec(numReadPorts, UInt(size.W)))
}
val out = new Bundle {
val src = Output(Vec(numReadPorts, tpe))
}
}
class RegisterFileCore[T <: Data](size: Int, tpe: T, numReadPorts: Int) extends Module {
require(numReadPorts >= 0)
val writePort = IO(new Bundle {
val enable = Input(Bool())
val addr = Input(UInt(log2Ceil(size).W))
val data = Input(tpe)
})
val readPorts = IO(Vec(numReadPorts, new Bundle {
val addr = Input(UInt(log2Ceil(size).W))
val data = Output(tpe)
}))
val regFile = RegInit(VecInit(Seq.fill(size)(0.U(tpe.getWidth.W))))
val writeAddrOH = UIntToOH(writePort.addr)
for ((reg, i) <- regFile.zipWithIndex.tail) {
reg := Mux(writeAddrOH(i) && writePort.enable, writePort.data, reg)
}
regFile(0) := 0.U
for (readPort <- readPorts) {
readPort.data := regFile(readPort.addr)
}
dontTouch(regFile)
}
object RegisterFile {
def apply[T <: Data](size: Int, tpe: T, numReadPorts: Int, numWritePorts: Int): RegFileInterface[T] = {
val core = Module(new RegisterFileCore(size, tpe, numReadPorts))
val _out = Wire(new RegFileInterface(size, tpe, numReadPorts, numWritePorts))
val clock = core.clock
for (i <- 0 until numReadPorts) {
core.readPorts(i).addr := _out.in.rs(i)
_out.out.src(i) := core.readPorts(i).data
}
core.writePort.addr := _out.in.writeAddr
core.writePort.data := _out.in.writeData(_out.control.writeSelect.asUInt)
core.writePort.enable := _out.control.writeEnable
_out
} }
} }

View file

@ -1,105 +1,47 @@
package npc package flow
import chisel3._ import chisel3._
import chiseltest._ import chiseltest._
import org.scalatest.freespec.AnyFreeSpec import org.scalatest.freespec.AnyFreeSpec
import chiseltest.simulator.WriteVcdAnnotation import chiseltest.simulator.WriteVcdAnnotation
import npc.util._ import flow.Flow
class RegisterFileSpec extends AnyFreeSpec with ChiselScalatestTester { class RV32CPUSpec extends AnyFreeSpec with ChiselScalatestTester {
"RegisterFile should work" - { "MemoryFile" - {
"with 2 read ports" in { "correctly load" in {
test(new RegisterFile(2)) { c => import chisel3.util.{SRAM, SRAMInterface, HexMemoryFile}
def readExpect(addr: Int, value: Int, port: Int = 0): Unit = { class UserMem extends Module {
c.io.readAddr(port).poke(addr.U) val io = IO(new SRAMInterface(1024, UInt(32.W), 1, 1, 0))
c.io.readData(port).expect(value.U) val memoryFile = HexMemoryFile("../resource/addi.txt")
io :<>= SRAM(
size = 1024,
tpe = UInt(32.W),
numReadPorts = 1,
numWritePorts = 1,
numReadwritePorts = 0,
memoryFile = memoryFile
)
val read = io.readPorts(0).data
printf(cf"memoryFile=$memoryFile, readPort=$read%x\n")
} }
def write(addr: Int, value: Int): Unit = { test(new UserMem).withAnnotations(Seq(WriteVcdAnnotation)) { c =>
c.io.writeEnable.poke(true.B) c.io.readPorts(0).enable.poke(true.B)
c.io.writeData.poke(value.U) c.io.writePorts(0).enable.poke(false.B)
c.io.writeAddr.poke(addr.U) c.io.writePorts(0).address.poke(0.U)
c.io.writePorts(0).data.poke(0.U)
for (i <- 0 until 32) {
c.io.readPorts(0).address.poke(i.U)
c.clock.step(1)
}
}
}
}
"should compile" in {
test(new Flow) { c =>
c.clock.step(1) c.clock.step(1)
c.io.writeEnable.poke(false.B)
} }
// everything should be 0 on init
for (i <- 0 until 32) {
readExpect(i, 0, port = 0)
readExpect(i, 0, port = 1)
} }
// write 5 * addr + 3
for (i <- 0 until 32) {
write(i, 5 * i + 3)
}
// check that the writes worked
for (i <- 0 until 32) {
readExpect(i, if (i == 0) 0 else 5 * i + 3, port = i % 2)
}
}
}
}
}
class ALUGeneratorSpec extends AnyFreeSpec with ChiselScalatestTester {
"With 32 width, " - {
val neg = (x: BigInt) => BigInt("FFFFFFFF", 16) - x + 1
val not = (x: BigInt) => x ^ BigInt("FFFFFFFF", 16)
val mask = BigInt("FFFFFFFF", 16)
val oprands: List[(BigInt, BigInt)] = List(
(5, 3), (101010, 101010), (0xFFFFFFFCL, 0xFFFFFFFFL), (4264115, 2)
)
val operations: Map[Int, (BigInt, BigInt) => BigInt] = Map(
0 -> ((a: BigInt, b: BigInt) => (a + b) & mask),
1 -> ((a: BigInt, b: BigInt) => (a + neg(b)) & mask),
2 -> ((a, _) => not(a)),
3 -> (_ & _),
4 -> (_ | _),
5 -> (_ ^ _),
6 -> ((a, b) => if (a < b) 1 else 0),
7 -> ((a, b) => if (a == b) 1 else 0),
)
val validate = (c: ALUGenerator,op: Int, oprands: List[(BigInt, BigInt)]) => {
c.io.op.poke(op.U)
oprands.foreach({ case (a, b) =>
c.io.a.poke(a.U)
c.io.b.poke(b.U)
c.io.out.expect(operations(op)(a, b))
})
}
"add should work" in {
test(new ALUGenerator(32)) { c => validate(c, 0, oprands) }
}
"sub should work" - {
"with positive result" in {
test(new ALUGenerator(32)) { c =>
validate(c, 1, oprands.filter({case (a, b) => a >= b}))
}
}
"with negative result" in {
test(new ALUGenerator(32)) { c =>
validate(c, 1, oprands.filter({case (a, b) => a < b}))
}
}
}
"not should work" in {
test(new ALUGenerator(32)) { c => validate(c, 2, oprands) }
}
"and should work" in {
test(new ALUGenerator(32)) { c => validate(c, 3, oprands) }
}
"or should work" in {
test(new ALUGenerator(32)) { c => validate(c, 4, oprands) }
}
"xor should work" in {
test(new ALUGenerator(32)) { c => validate(c, 5, oprands) }
}
"compare should work" in {
test(new ALUGenerator(32)) { c => validate(c, 6, oprands) }
}
"equal should work" in {
test(new ALUGenerator(32)) { c => validate(c, 7, oprands) }
}
}
} }

View file

@ -0,0 +1,81 @@
package flow
import chisel3._
import chiseltest._
import org.scalatest.freespec.AnyFreeSpec
import chiseltest.simulator.WriteVcdAnnotation
import flow.components._
class RegisterFileSpec extends AnyFreeSpec with ChiselScalatestTester {
"RegisterFileCore" - {
"register 0 is always 0" in {
test(new RegisterFileCore(32, UInt(32.W), 2)) { c =>
c.readPorts(0).addr.poke(0)
c.readPorts(1).addr.poke(0)
c.writePort.enable.poke(true)
c.writePort.addr.poke(0)
c.writePort.data.poke(0x1234)
c.readPorts(0).data.expect(0)
c.readPorts(1).data.expect(0)
c.clock.step(2)
c.readPorts(0).data.expect(0)
c.readPorts(1).data.expect(0)
}
}
"register other than 0 can be written" in {
test(new RegisterFileCore(32, UInt(32.W), 2)) { c =>
import scala.util.Random
val r = new Random()
for (i <- 1 until 32) {
val v = r.nextLong() & 0xFFFFFFFFL
c.readPorts(0).addr.poke(i)
c.writePort.enable.poke(true)
c.writePort.addr.poke(i)
c.writePort.data.poke(v)
c.clock.step(1)
c.readPorts(0).data.expect(v)
}
}
}
}
"RegisterInterface" - {
class Top extends Module {
val io = IO(new RegFileInterface(32, UInt(32.W), 2, 2))
val rf = RegisterFile(32, UInt(32.W), 2, 2)
io :<>= rf
}
"write" in {
test(new Top).withAnnotations(Seq(WriteVcdAnnotation)) { c =>
import c.io.control.WriteSelect._
val writePort = rAluOut.litValue.toInt
c.io.control.writeEnable.poke(true)
c.io.control.writeSelect.poke(rAluOut)
c.io.in.writeAddr.poke(5)
c.io.in.writeData(writePort).poke(0xcdef)
c.io.in.rs(0).poke(5)
c.clock.step(1)
c.io.out.src(0).expect(0xcdef)
}
}
"no data is written when not enabled" in {
test(new Top).withAnnotations(Seq(WriteVcdAnnotation)) { c =>
import c.io.control.WriteSelect._
val writePort = rAluOut.litValue.toInt
c.io.control.writeEnable.poke(true)
c.io.control.writeSelect.poke(rAluOut)
c.io.in.writeAddr.poke(5)
c.io.in.writeData(writePort).poke(0xcdef)
c.io.in.rs(0).poke(5)
c.clock.step(1)
c.io.control.writeEnable.poke(false)
c.io.in.writeData(writePort).poke(0x1234)
c.clock.step(1)
c.io.out.src(0).expect(0xcdef)
}
}
}
}

43
npc/csrc/Flow/main.cpp Normal file
View file

@ -0,0 +1,43 @@
#include <cstdlib>
#include <cassert>
#include <cstdlib>
#include <verilated.h>
#include <verilated_vcd_c.h>
#include <VFlow.h>
#define MAX_SIM_TIME 100
#define VERILATOR_TRACE
int main(int argc, char **argv, char **env) {
int sim_time = 0;
Verilated::commandArgs(argc, argv);
VFlow *top = new VFlow;
Verilated::traceEverOn(true);
VerilatedVcdC *m_trace = new VerilatedVcdC;
#ifdef VERILATOR_TRACE
top->trace(m_trace, 5);
m_trace->open("waveform.vcd");
#endif
for (sim_time = 0; sim_time < 10; sim_time++) {
top->eval();
top->clock = !top->clock;
top->reset = 1;
#ifdef VERILATOR_TRACE
m_trace->dump(sim_time);
#endif
}
top->reset = 0;
for (sim_time = 10; sim_time < MAX_SIM_TIME; sim_time++) {
top->eval();
top->clock = !top->clock;
#ifdef VERILATOR_TRACE
m_trace->dump(sim_time);
#endif
}
#ifdef VERILATOR_TRACE
m_trace->close();
#endif
delete top;
exit(EXIT_SUCCESS);
}

View file

@ -0,0 +1,12 @@
#include <verilated.h>
#include <verilated_vcd_c.h>
// #include <nvboard.h>
#include <VFlow.h>
const int MAX_SIM_TIME=100;
// void nvboard_bind_all_pins(VFLow* top);
int main(int argc, char **argv, char **env) {
return 0;
}

View file

@ -5,11 +5,11 @@
"systems": "systems" "systems": "systems"
}, },
"locked": { "locked": {
"lastModified": 1701680307, "lastModified": 1710146030,
"narHash": "sha256-kAuep2h5ajznlPMD9rnQyffWG8EM/C73lejGofXvdM8=", "narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=",
"owner": "numtide", "owner": "numtide",
"repo": "flake-utils", "repo": "flake-utils",
"rev": "4022d587cbbfd70fe950c1e2083a02621806a725", "rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -20,11 +20,11 @@
}, },
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1704194953, "lastModified": 1709961763,
"narHash": "sha256-RtDKd8Mynhe5CFnVT8s0/0yqtWFMM9LmCzXv/YKxnq4=", "narHash": "sha256-6H95HGJHhEZtyYA3rIQpvamMKAGoa8Yh2rFV29QnuGw=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "bd645e8668ec6612439a9ee7e71f7eac4099d4f6", "rev": "3030f185ba6a4bf4f18b87f345f104e6a6961f34",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -34,6 +34,22 @@
"type": "github" "type": "github"
} }
}, },
"nixpkgs-circt162": {
"locked": {
"lastModified": 1705645507,
"narHash": "sha256-tX3vipIAmNDBA8WNWG4oY4KyTfnm2YieTHO2BhG8ISA=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "7995cae3ad60e3d6931283d650d7f43d31aaa5c7",
"type": "github"
},
"original": {
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "7995cae3ad60e3d6931283d650d7f43d31aaa5c7",
"type": "github"
}
},
"nur-xin": { "nur-xin": {
"inputs": { "inputs": {
"nixpkgs": [ "nixpkgs": [
@ -41,11 +57,11 @@
] ]
}, },
"locked": { "locked": {
"lastModified": 1704450168, "lastModified": 1707020873,
"narHash": "sha256-zOLL35LX83Of64quCyxpyP8rTSO/tgrfHNm52tFo6VU=", "narHash": "sha256-+dNltc7tjgTIyle/I/5siQ5IvPwu+R5Uf6e24CmjLNk=",
"ref": "refs/heads/master", "ref": "refs/heads/master",
"rev": "beda2a57d946f392d958755c7bb03ac092a20f42", "rev": "8142717e7154dbaadee0679f0224fe75cebb1735",
"revCount": 140, "revCount": 147,
"type": "git", "type": "git",
"url": "https://git.xinyang.life/xin/nur.git" "url": "https://git.xinyang.life/xin/nur.git"
}, },
@ -58,6 +74,7 @@
"inputs": { "inputs": {
"flake-utils": "flake-utils", "flake-utils": "flake-utils",
"nixpkgs": "nixpkgs", "nixpkgs": "nixpkgs",
"nixpkgs-circt162": "nixpkgs-circt162",
"nur-xin": "nur-xin" "nur-xin": "nur-xin"
} }
}, },

View file

@ -1,6 +1,7 @@
{ {
inputs = { inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
nixpkgs-circt162.url = "github:NixOS/nixpkgs/7995cae3ad60e3d6931283d650d7f43d31aaa5c7";
flake-utils.url = "github:numtide/flake-utils"; flake-utils.url = "github:numtide/flake-utils";
nur-xin = { nur-xin = {
url = "git+https://git.xinyang.life/xin/nur.git"; url = "git+https://git.xinyang.life/xin/nur.git";
@ -11,14 +12,17 @@
outputs = { self, ... }@inputs: with inputs; outputs = { self, ... }@inputs: with inputs;
flake-utils.lib.eachDefaultSystem (system: flake-utils.lib.eachDefaultSystem (system:
let let
pkgs = nixpkgs.legacyPackages.${system} // pkgs = import nixpkgs { inherit system; config.allowUnfree = true; }//
{ nur.xin = nur-xin.legacyPackages.${system}; }; { nur.xin = nur-xin.legacyPackages.${system}; };
in in
{ {
devShells.default = with pkgs; mkShell { devShells.default = with pkgs; mkShell {
CHISEL_FIRTOOL_PATH = "${nixpkgs-circt162.legacyPackages.${system}.circt}/bin";
packages = [ packages = [
clang-tools clang-tools
rnix-lsp # rnix-lsp
coursier
espresso
gdb gdb
jre jre
@ -36,7 +40,7 @@
cmake cmake
sbt sbt
nur.xin.nvboard nur.xin.nvboard
self.packages.${system}.circt nixpkgs-circt162.legacyPackages.${system}.circt
yosys yosys
]; ];
buildInputs = [ buildInputs = [

10
npc/resource/addi.txt Normal file
View file

@ -0,0 +1,10 @@
00114113
00114113
00114113
00114113
00114113
00114113
00114113
00114113
00114113
00114113