{"task_id": "chiffre", "path": "chiffre/le-chiffre/src/main/scala/rocketchip/Configs.scala", "left_context": "// Copyright 2017 IBM\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\npackage freechips.rocketchip.system\n\nimport chisel3._\nimport chiffre.{ChiffreParameters, LeChiffre, BuildChiffre}\nimport freechips.rocketchip.config.{Config, Parameters}\nimport freechips.rocketchip.tile.{BuildRoCC, OpcodeSet}\nimport freechips.rocketchip.subsystem.RocketTilesKey\nimport freechips.rocketchip.diplomacy.LazyModule\n\nclass WithLeChiffre extends Config (\n (site, here, up) => {\n case BuildChiffre => ChiffreParameters()\n case BuildRoCC => List(\n (p: Parameters) => {\n val chiffre = LazyModule(new LeChiffre(OpcodeSet.custom2, \"main\")(p))\n chiffre })\n })\n\n", "right_context": "", "groundtruth": "class LeChiffreConfig extends Config(new WithLeChiffre ++ new DefaultConfig)\n", "crossfile_context": ""}
{"task_id": "chiffre", "path": "chiffre/src/main/scala/chiffre/InjectorInfo.scala", "left_context": "// Copyright 2018 IBM\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\npackage chiffre\n\ncase class InjectorInfoBindingException(msg: String) extends Exception(msg)\n\ntrait InjectorInfo extends HasName with HasWidth with Equals {\n /* All configurable fields for this specific injector */\n val fields: Seq[ScanField]\n\n val name: String = this.getClass.getSimpleName\n\n /* The width of this injector's scan chain configuration */\n lazy val width: Int = fields.foldLeft(0)( (l, r) => l + r.width )\n\n /* Prety print */\n def serialize(tab: String = \"\"): String = {\n s\"\"\"|${tab}class: $name\n |${tab}width: $width\n", "right_context": " .stripMargin\n }\n\n def toBits(): String = fields.map(_.toBits()).mkString\n\n def bind(in: Seq[ScanField]): InjectorInfo = {\n val widthIn = in.foldLeft(0)( (l, r) => l + r.width )\n if (width != widthIn) {\n throw new InjectorInfoBindingException(s\"Unable to bind, widths differ ($width vs. $widthIn) between $name and $in\") }\n if (!(fields.zip(in).map{ case (l, r) => l canEqual r }).foldLeft(true)( (l, r) => l & r )) {\n throw new InjectorInfoBindingException(s\"Unable to bind, types differ between $name and $in\") }\n fields.zip(in).map{ case (l, r) => l.bind(r.value) }\n this\n }\n\n def isBound(): Boolean = fields.map(_.isBound).reduceOption(_ && _).getOrElse(true)\n\n def unbind(): InjectorInfo = {\n fields.map(_.unbind)\n this\n }\n\n override def equals(that: Any): Boolean = that match {\n case that: InjectorInfo => (this canEqual that) &&\n width == that.width &&\n fields.zip(that.fields).foldLeft(true){ case (x, (l, r)) => x & (l == r) }\n case _ => false\n }\n\n override def hashCode = fields.hashCode\n}\n", "groundtruth": " |${fields.map(a => s\"${a.serialize(tab + \" \")}\").mkString(\"\\n\")}\"\"\"\n", "crossfile_context": ""}
{"task_id": "chiffre", "path": "chiffre/src/main/scala/chiffre/ScanField.scala", "left_context": "// Copyright 2018 IBM\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\npackage chiffre\n\ncase class ScanFieldException(msg: String) extends Exception(msg)\ncase class ScanFieldUnboundException(msg: String) extends Exception(msg)\n", "right_context": "\ntrait HasWidth {\n val width: Int\n}\n\ntrait HasName {\n val name: String\n}\n\n/** A configurable field of the scan chain */\ntrait ScanField extends HasName with HasWidth with Equals {\n var value: Option[BigInt] = None\n\n val name: String = this.getClass.getSimpleName\n\n if (width < 1) {\n throw new ScanFieldException(s\"ScanField '$name' width must be greater than 0\") }\n\n def bind(in: BigInt): ScanField = {\n if (in < 0 || in > maxValue) {\n throw new ScanFieldBindingException(\n s\"Cannot bind ScanField '$name' to value $in must be on domain [0, $maxValue], but would be ${in}\")\n }\n value = Some(in)\n this\n }\n\n def bind(in: Option[BigInt]): ScanField =\n if (in.nonEmpty) {\n bind(in.get)\n } else {\n value = None\n this\n }\n\n lazy val maxValue = BigInt(2).pow(width) - 1\n\n def toBits(): String = s\"%${width}s\"\n .format(value.getOrElse(BigInt(0)).toString(2))\n .replace(' ', '0')\n\n def serialize(indent: String = \"\"): String = {\n s\"\"\"|${indent}name: $name\n |${indent} width: $width\n |${indent} value: ${toBits}\"\"\"\n .stripMargin\n }\n\n def unbind(): ScanField = {\n value = None\n this\n }\n\n def isBound(): Boolean = value.nonEmpty\n\n override def equals(that: Any): Boolean = that match {\n case that: ScanField => (this canEqual that) && (width == that.width) && (value == that.value)\n }\n\n override def hashCode = value.hashCode\n}\n\ntrait ProbabilityBind { this: ScanField =>\n def bind(probability: Double): ScanField = bind(BigDecimal((math.pow(2, width) - 1) * probability).toBigInt)\n def bind(probability: Option[Double]): ScanField =\n if (probability.nonEmpty) {\n bind(probability.get)\n } else {\n value = None\n this\n }\n}\n", "groundtruth": "case class ScanFieldBindingException(msg: String) extends Exception(msg)\n", "crossfile_context": ""}
{"task_id": "chiffre", "path": "chiffre/src/main/scala/chiffre/inject/CycleInjector.scala", "left_context": "// Copyright 2018 IBM\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\npackage chiffre.inject\n\nimport chisel3._\nimport chiffre.ChiffreInjector\n\nimport chiffre.{InjectorInfo, ScanField, HasWidth}\n\n", "right_context": "case class CycleInject(width: Int) extends ScanField\n\ncase class CycleInjectorInfo(bitWidth: Int, cycleWidth: Int) extends InjectorInfo {\n val fields = Seq(Cycle(cycleWidth), CycleInject(bitWidth))\n}\n\nclass CycleInjector(bitWidth: Int, val cycleWidth: Int) extends Injector(bitWidth) {\n val cycleTarget = Reg(UInt(cycleWidth.W))\n val cycleCounter = Reg(UInt(cycleWidth.W))\n val flipMask = Reg(UInt(bitWidth.W))\n\n lazy val info = CycleInjectorInfo(bitWidth, cycleWidth)\n\n val fire = enabled & (cycleCounter === cycleTarget)\n io.out := Mux(fire, io.in ^ flipMask, io.in)\n\n when (enabled) {\n cycleCounter := cycleCounter + 1.U\n }\n\n when (io.scan.clk) {\n enabled := false.B\n cycleCounter := 0.U\n cycleTarget := (io.scan.in ## cycleTarget) >> 1\n flipMask := (cycleTarget(0) ## flipMask) >> 1\n }\n io.scan.out := flipMask(0)\n\n when (enabled && RegNext(!enabled)) {\n printf(s\"\"\"|[info] $name enabled\n |[info] - target: 0x%x\n |[info] - mask: 0x%x\n |\"\"\".stripMargin, cycleTarget, flipMask)\n }\n\n when (!enabled && RegNext(enabled)) {\n printf(s\"[info] $name disabled\\n\")\n }\n\n when (fire) {\n printf(s\"[info] $name injecting 0x%x into 0x%x to output 0x%x!\\n\", flipMask, io.in, io.out)\n enabled := false.B\n }\n}\n\n// scalastyle:off magic.number\nclass CycleInjector32(bitWidth: Int, val scanId: String) extends CycleInjector(bitWidth, 32) with ChiffreInjector\n// scalastyle:on magic.number\n", "groundtruth": "case class Cycle(width: Int) extends ScanField\n", "crossfile_context": ""}
{"task_id": "chiffre", "path": "chiffre/src/main/scala/chiffre/inject/LfsrInjector.scala", "left_context": "// Copyright 2018 IBM\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\npackage chiffre.inject\n\nimport chisel3._\nimport chiffre.ChiffreInjector\n\nimport chiffre.{ScanField, InjectorInfo, ProbabilityBind}\n\ncase class Seed(width: Int) extends ScanField\n", "right_context": "\ncase class LfsrInjectorInfo(bitWidth: Int, lfsrWidth: Int) extends InjectorInfo {\n val fields = Seq.fill(bitWidth)(Seq(Seed(lfsrWidth), Difficulty(lfsrWidth))).flatten\n}\n\nsealed class LfsrInjector(val lfsrWidth: Int) extends Injector(1) {\n val difficulty = RegInit(0.U(lfsrWidth.W))\n val seed = RegInit(1.U(lfsrWidth.W))\n lazy val info = LfsrInjectorInfo(1, lfsrWidth)\n\n val lfsr = Module(new perfect.random.Lfsr(lfsrWidth))\n lfsr.io.seed.valid := io.scan.en\n lfsr.io.seed.bits := seed\n\n val fire = enabled && (lfsr.io.y <= difficulty)\n io.out := Mux(fire, ~io.in, io.in)\n\n when (io.scan.clk) {\n enabled := false.B\n seed := (io.scan.in ## seed) >> 1\n difficulty := (seed(0) ## difficulty) >> 1\n }\n\n io.scan.out := difficulty(0)\n\n when (enabled && RegNext(!enabled)) {\n printf(s\"\"\"|[info] $name enabled\n |[info] - seed: 0x%x\n |[info] - difficulty: 0x%x\n |\"\"\".stripMargin, seed, difficulty)\n }\n\n when (!enabled && RegNext(enabled)) {\n printf(s\"[info] $name disabled\\n\")\n }\n}\n\nclass LfsrInjectorN(bitWidth: Int, val lfsrWidth: Int, val scanId: String) extends\n InjectorBitwise(bitWidth, new LfsrInjector(lfsrWidth)) with ChiffreInjector {\n lazy val info = LfsrInjectorInfo(bitWidth, lfsrWidth)\n}\n\nclass LfsrInjector32(bitWidth: Int, scanId: String) extends LfsrInjectorN(bitWidth, 32, scanId) // scalastyle:ignore\n", "groundtruth": "case class Difficulty(width: Int) extends ScanField with ProbabilityBind\n", "crossfile_context": ""}
{"task_id": "chiffre", "path": "chiffre/src/main/scala/chiffre/inject/StuckAt.scala", "left_context": "// Copyright 2018 IBM\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\npackage chiffre.inject\n\nimport chisel3._\nimport chisel3.util.Fill\nimport chiffre.ChiffreInjector\n\nimport chiffre.{ScanField, InjectorInfo}\n\ncase class Mask(width: Int) extends ScanField\ncase class StuckAt(width: Int) extends ScanField\n\ncase class StuckAtInjectorInfo(bitWidth: Int) extends InjectorInfo {\n val fields = Seq(Mask(bitWidth), StuckAt(bitWidth))\n}\n\nclass StuckAtInjector(val bitWidth: Int) extends Injector(bitWidth) {\n val mask = Reg(UInt(bitWidth.W))\n val value = Reg(UInt(bitWidth.W))\n\n lazy val info = StuckAtInjectorInfo(bitWidth)\n\n val select = mask & Fill(mask.getWidth, enabled)\n io.out := (io.in & ~select) | (value & select)\n\n when (io.scan.clk) {\n enabled := false.B\n mask := (io.scan.in ## mask) >> 1\n value := (mask(0) ## value) >> 1\n }\n\n io.scan.out := value(0)\n\n when (io.scan.en && !enabled) {\n printf(s\"\"\"|[info] $name enabled\n |[info] - mask: 0x%x\n |[info] - value: 0x%x\n |\"\"\".stripMargin, mask, value)\n }\n\n when (io.scan.en && enabled) {\n printf(s\"[info] $name disabled\\n\")\n }\n}\n\n", "right_context": "", "groundtruth": "class StuckAtInjectorWithId(bitWidth: Int, val scanId: String) extends StuckAtInjector(bitWidth) with ChiffreInjector\n", "crossfile_context": ""}
{"task_id": "chiffre", "path": "chiffre/src/main/scala/chiffre/passes/FaultInstrumentation.scala", "left_context": "// Copyright 2017 IBM\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\npackage chiffre.passes\n\nimport chiffre.inject.Injector\nimport chiffre.util.removeZeroWidth\nimport chisel3.experimental.{annotate, ChiselAnnotation}\nimport chisel3.stage.{ChiselGeneratorAnnotation, CircuitSerializationAnnotation}\nimport firrtl._\nimport firrtl.ir._\nimport firrtl.passes.{PassException, ToWorkingIR}\nimport firrtl.passes.wiring.SinkAnnotation\nimport firrtl.stage.FirrtlCircuitAnnotation\nimport firrtl.annotations.{Annotation, ComponentName, ModuleName, CircuitName}\nimport firrtl.annotations.AnnotationUtils._\nimport scala.collection.mutable\n\ncase class FaultInstrumentationException(msg: String) extends PassException(msg)\n\ncase class FaultInstrumentationInfo(orig: ComponentName, conn: ComponentName, repl: ComponentName)\n\ncase class Modifications(\n defines: Seq[Statement] = Seq.empty,\n connects: Seq[Statement] = Seq.empty,\n modules: Seq[DefModule] = Seq.empty,\n annotations: Seq[Annotation] = Seq.empty,\n renames: Map[String, String] = Map.empty) {\n\n override def toString: String = serialize(\"\")\n\n def serialize(indent: String): String =\n s\"\"\"|${indent}defines:\n |${defines.map(a => s\"$indent - ${a.serialize}\").mkString(\"\\n\")}\n |${indent}connects:\n |${connects.map(a => s\"$indent - ${a.serialize}\").mkString(\"\\n\")}\n |${indent}modules:\n |${modules.map(a => s\"$indent - ${a.name}\").mkString(\"\\n\")}\n |${indent}annotations:\n |${annotations.map(a => s\"$indent - ${a.serialize}\").mkString(\"\\n\")}\n |${indent}renames:\n |${renames.map{case (a, b) => s\"$indent - $a: $b\"}.mkString(\"\\n\")}\"\"\"\n .stripMargin\n\n def serializeInMemory(indent: String): String =\n s\"\"\"|${indent}defines:\n |${defines.map(a => s\"$indent - $a\").mkString(\"\\n\")}\n |${indent}connects:\n |${connects.map(a => s\"$indent - $a\").mkString(\"\\n\")}\n |${indent}modules:\n |${modules.map(a => s\"$indent - ${a.name}\").mkString(\"\\n\")}\n |${indent}annotations:\n |${annotations.map(a => s\"$indent - $a\").mkString(\"\\n\")}\n", "right_context": " |${renames.map{case (a, b) => s\"$indent - $a: $b\"}.mkString(\"\\n\")}\"\"\"\n .stripMargin\n}\n\nclass FaultInstrumentation(compMap: Map[String, Seq[(ComponentName, String, Class[_ <: Injector])]]) extends Transform {\n def inputForm: CircuitForm = MidForm\n def outputForm: CircuitForm = MidForm\n def execute(state: CircuitState): CircuitState = {\n val modifications = analyze(state.circuit)\n\n val (mxx, ax) = modifications\n .foldLeft((Seq[DefModule](), Seq[Annotation]())){\n case ((m, a), (_, Modifications(_,_,mm,aa,_))) => (m ++ mm, a ++ aa) }\n\n val mx = state.circuit.modules map onModule(modifications)\n val cx = ToWorkingIR.run(state.circuit.copy(modules = mxx ++ mx))\n\n val inAnno: Seq[Annotation] = state.annotations.toSeq\n state.copy(circuit = cx,\n annotations = AnnotationSeq(inAnno ++ ax))\n }\n\n private def inlineCompile(gen: () => chisel3.Module, ns: Option[Namespace] = None): CircuitState = {\n def genName(name: String, n: Option[Namespace] = None): String = n.map(_.newName(name)).getOrElse(name)\n\n val (chirrtl: firrtl.ir.Circuit, inlineAnnos: AnnotationSeq) = {\n val outputAnnotations = (new chisel3.stage.ChiselStage).execute(\n args = Array(\"--no-run-firrtl\"),\n annotations = Seq(ChiselGeneratorAnnotation(gen))\n )\n val (circuitAnnos, otherAnnos) = outputAnnotations.partition {\n case _: FirrtlCircuitAnnotation => true\n case _ => false\n }\n require(circuitAnnos.size == 1)\n (circuitAnnos.head.asInstanceOf[FirrtlCircuitAnnotation].circuit, AnnotationSeq(otherAnnos))\n }\n val midFirrtl = (new MiddleFirrtlCompiler)\n .compileAndEmit(CircuitState(chirrtl, ChirrtlForm))\n .circuit\n .mapModule(\n _ match {\n case m: Module => m.copy(name = genName(m.name, ns))\n case m: ExtModule => m.copy(name = genName(m.name, ns))\n })\n CircuitState(\n circuit = midFirrtl,\n form = MidForm,\n annotations = AnnotationSeq(inlineAnnos))\n }\n\n private def analyze(c: Circuit): Map[String, Modifications] = {\n val mods = new mutable.HashMap[String, Modifications].withDefaultValue(Modifications())\n val cmods = new mutable.HashMap[ComponentName, CircuitState]()\n val circuitNamespace = Namespace(c)\n\n c.modules\n .filter((m: DefModule) => compMap.contains(m.name))\n .foreach {\n case m: Module =>\n val moduleNamespace = Namespace(m)\n var scanIn: Option[String] = None\n var scanOut: String = \"\"\n compMap(m.name) map { case (comp, id, gen) =>\n val t = passes.wiring.WiringUtils.getType(c, m.name, comp.name)\n val width = bitWidth(t)\n if (width == 0)\n throw new FaultInstrumentationException(\"Cannot instrument zero-width signals\")\n\n val args = Array[AnyRef](new java.lang.Integer(width.toInt), id)\n val dut = () => {\n val injector = gen.getConstructors()(0)\n .newInstance(args: _*)\n .asInstanceOf[Injector]\n annotate(new ChiselAnnotation {\n def toFirrtl: ScanChainDescriptionAnnotation = ScanChainDescriptionAnnotation(comp, id, injector.info)\n })\n injector\n }\n val (subcir, defms, annosx) = if (cmods.contains(comp)) {\n (cmods(comp).circuit, Seq.empty, Seq.empty)\n } else {\n try {\n cmods(comp) = inlineCompile(dut, Some(circuitNamespace))\n } catch {\n case e: java.lang.IllegalArgumentException => throw new FaultInstrumentationException(\n s\"Did not find '(Int, String)' constructor for injector '${gen.getName}' (Did you forget to specify it?)\")\n }\n (cmods(comp).circuit, cmods(comp).circuit.modules,\n if (cmods(comp).annotations.isEmpty) { Seq.empty }\n else { cmods(comp).annotations.toSeq } )\n }\n val injector = defms.last // the top-level module (the injector) should be the last module of the subcircuit\n val inst = DefInstance(NoInfo, moduleNamespace.newName(s\"${comp.name}_injector\"), injector.name)\n val rename = moduleNamespace.newName(s\"${comp.name}_fault\")\n\n val Seq(scanEn, scanClk, scanIn, scanOut) =\n Seq(\"en\", \"clk\", \"in\", \"out\").map( s =>\n ComponentName(s\"${inst.name}.io.scan.$s\",\n ModuleName(m.name, CircuitName(c.main))) )\n\n val faulty = DefWire(NoInfo, rename, t)\n val data = fromBits(WRef(faulty).mapType(removeZeroWidth.apply), toExp(s\"${inst.name}.io.out\")) match {\n case Block(stmts: Seq[Statement]) =>\n stmts :+ Connect(NoInfo, toExp(s\"${inst.name}.io.in\"), toBits(WRef(comp.name, t, RegKind, UnknownFlow).mapType(removeZeroWidth.apply)))\n }\n val x = mods(m.name)\n mods(m.name) = x.copy(\n defines = inst +: x.defines :+ faulty,\n connects = x.connects ++ Seq(\n Connect(NoInfo, toExp(s\"${inst.name}.clock\"), toExp(s\"clock\")),\n Connect(NoInfo, toExp(s\"${inst.name}.reset\"), toExp(s\"reset\")),\n IsInvalid(NoInfo, toExp(s\"${inst.name}.io.scan.en\")),\n IsInvalid(NoInfo, toExp(s\"${inst.name}.io.scan.clk\")),\n IsInvalid(NoInfo, toExp(s\"${inst.name}.io.scan.in\"))\n ) ++ data,\n modules = x.modules ++ defms,\n annotations = x.annotations ++ annosx ++ Seq(\n SinkAnnotation(scanEn, \"scan_en\"),\n SinkAnnotation(scanClk, \"scan_clk\"),\n ScanChainInjectorAnnotation(comp, id, injector.name),\n ScanChainAnnotation(scanIn, \"slave\", \"in\", id, Some(comp)),\n ScanChainAnnotation(scanOut, \"slave\", \"out\", id, Some(comp))\n ),\n renames = x.renames ++ Map(comp.name -> rename)\n )\n }\n case m: ExtModule =>\n throw new FaultInstrumentationException(\n \"Tried to instrument an ExtModule\")\n }\n\n mods.map{ case (k, v) =>\n logger.info(s\"[info] $k\")\n logger.info(v.serialize(\"[info] \"))\n }\n\n mods.toMap\n }\n\n private def onModule(mods: Map[String, Modifications])\n (m: DefModule): DefModule = {\n mods.get(m.name) match {\n case None => m\n case Some(l) => m match {\n case m: Module =>\n val x = mods(m.name)\n val mx = m.copy(\n body = Block(\n (x.defines :+ (m.body mapStmt onStmt(x.renames))) ++ x.connects))\n mx\n case _ => m\n }\n }\n }\n\n private def onStmt(renames: Map[String, String])(s: Statement): Statement = {\n s mapStmt onStmt(renames) match {\n case Connect(i, l, e) =>\n Connect(i, l, replace(renames)(e))\n case PartialConnect(i, l, e) =>\n PartialConnect(i, l, replace(renames)(e))\n case s => s mapExpr replace(renames)\n }\n }\n\n private def replace(renames: Map[String, String])\n (e: Expression): Expression = {\n e match {\n case ex: WRef => ex.name match {\n case name if renames.contains(name) => ex.copy(name=renames(name))\n case _ => ex\n }\n case ex: Reference => ex.name match {\n case name if renames.contains(name) => ex.copy(name=renames(name))\n case _ => ex\n }\n case _ => e mapExpr replace(renames)\n }\n }\n}\n", "groundtruth": " |${indent}renames:\n", "crossfile_context": ""}
{"task_id": "chiffre", "path": "chiffre/src/main/scala/chiffre/passes/ScanChainTransform.scala", "left_context": "// Copyright 2018 IBM\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\npackage chiffre.passes\n\nimport firrtl._\nimport firrtl.ir._\nimport firrtl.passes.PassException\nimport firrtl.passes.wiring.{SinkAnnotation, SourceAnnotation}\nimport firrtl.annotations.{ComponentName, ModuleName, CircuitName, SingleTargetAnnotation, Annotation}\nimport chiffre.{InjectorInfo, FaultyComponent}\nimport chiffre.scan.{ScanChain, JsonProtocol}\n\nimport scala.collection.mutable\nimport scala.collection.immutable.ListMap\nimport java.io.{File, FileWriter}\n\ncase class ScanChainException(msg: String) extends PassException(msg)\n\ncase class ScanChainInfo(\n masterScan: ComponentName,\n /* Everything here is keyed by the injector component */\n slaveIn: Map[ComponentName, ComponentName] = Map.empty,\n slaveOut: Map[ComponentName, ComponentName] = Map.empty,\n injectors: ListMap[ComponentName, ModuleName] = ListMap.empty,\n /* This is keyed by the injector module name */\n description: Map[ComponentName, InjectorInfo] = Map.empty) {\n // scalastyle:off line.size.limit\n def serialize(tab: String): String =\n s\"\"\"|${tab}master:\n |${tab} scan: ${masterScan}\n |${tab}slaves:\n", "right_context": " |${tab}description:\n |${description.map{case(k,v)=>s\"${tab} ${k.name}: $v\"}.mkString(\"\\n\")}\"\"\"\n .stripMargin\n // scalastyle:on line.size.limit\n\n def toFaultyComponent: Seq[FaultyComponent] = injectors\n .map{ case(c, m) => FaultyComponent(c.serialize, description(c)) }\n .toSeq\n}\n\nsealed trait ScanAnnos\n\ncase class ScanChainAnnotation(\n target: ComponentName,\n ctrl: String,\n dir: String,\n id: String,\n // [todo] remove key, is this used?\n key: Option[ComponentName]) extends SingleTargetAnnotation[ComponentName]\n with ScanAnnos {\n def duplicate(x: ComponentName): ScanChainAnnotation = this.copy(target = x)\n}\n\ncase class ScanChainInjectorAnnotation(\n target: ComponentName,\n id: String,\n moduleName: String) extends SingleTargetAnnotation[ComponentName]\n with ScanAnnos {\n def duplicate(x: ComponentName): ScanChainInjectorAnnotation =\n this.copy(target = x)\n}\n\ncase class ScanChainDescriptionAnnotation(\n target: ComponentName,\n id: String,\n d: InjectorInfo) extends SingleTargetAnnotation[ComponentName]\n with ScanAnnos {\n def duplicate(x: ComponentName): ScanChainDescriptionAnnotation =\n this.copy(target = x)\n}\n\nclass ScanChainTransform extends Transform {\n def inputForm: CircuitForm = MidForm\n def outputForm: CircuitForm = HighForm\n\n // scalastyle:off cyclomatic.complexity\n def analyze(circuit: Circuit, annos: Seq[Annotation]): Map[String, ScanChainInfo] = {\n val s = mutable.HashMap[String, ScanChainInfo]()\n annos.foreach {\n case ScanChainAnnotation(comp, ctrl, dir, id, key) => (ctrl, dir) match {\n case (\"master\", \"scan\") => s(id) = ScanChainInfo(masterScan = comp)\n case _ =>\n }\n case _ =>\n }\n def exceptionIfUnknownId(id: String): Unit = if (!s.contains(id)) {\n throw new ScanChainException(\n s\"No known scan chain master '$id' (Did you misspell it? Did you not include an injector?)\") }\n annos.foreach {\n case ScanChainAnnotation(comp, ctrl, dir, id, key) =>\n exceptionIfUnknownId(id)\n s(id) =\n (ctrl, dir) match {\n case (\"slave\", \"in\") => s(id).copy(slaveIn = s(id).slaveIn ++ Map(key.get -> comp))\n case (\"slave\", \"out\") => s(id).copy(slaveOut = s(id).slaveOut ++ Map(key.get -> comp))\n case _ => s(id)\n }\n case ScanChainInjectorAnnotation(comp, id, mod) =>\n exceptionIfUnknownId(id)\n s(id) = s(id).copy(injectors = s(id).injectors ++ Map(comp -> ModuleName(mod, comp.module.circuit)))\n case _ =>\n }\n annos.foreach {\n case ScanChainDescriptionAnnotation(comp, id, d) =>\n exceptionIfUnknownId(id)\n s(id) = s(id).copy(description = s(id).description ++ Map(comp -> d))\n case _ =>\n }\n s.toMap\n } // scalastyle:on cyclomatic.complexity\n\n /** Run the transform\n *\n * @param state a circuit\n * @todo order the scan chain based on distance\n */\n def execute(state: CircuitState): CircuitState = {\n val targetDir = new File(state.annotations.collectFirst{ case a: TargetDirAnnotation => a.directory }.getOrElse(\".\"))\n val myAnnos = state.annotations.collect{ case a: ScanAnnos => a }\n myAnnos match {\n case Nil => state\n case p =>\n // s is a map of scan chains indexed by scan chain id\n val s: Map[String, ScanChainInfo] = analyze(state.circuit, p)\n\n s.foreach{ case (k, v) => logger.info(\n s\"\"\"|[info] scan chain:\n |[info] name: ${k}\n |${v.serialize(\"[info] \")}\"\"\".stripMargin) }\n\n val sc = s.flatMap{ case(k, v) => Map(k -> v.toFaultyComponent) }\n if (!targetDir.exists()) { targetDir.mkdirs() }\n val jsonFile = new FileWriter(targetDir + \"/scan-chain.json\")\n jsonFile.write(JsonProtocol.serialize(sc))\n jsonFile.close()\n\n val ax = s.foldLeft(Seq[Annotation]()){ case (a, (name, v)) =>\n val masterIn = v.masterScan.copy(name=v.masterScan.name + \".in\")\n val masterOut = v.masterScan.copy(name=v.masterScan.name + \".out\")\n val masterClk = v.masterScan.copy(name=v.masterScan.name + \".clk\")\n val masterEn = v.masterScan.copy(name=v.masterScan.name + \".en\")\n\n val masterAnnotations = Seq(\n SourceAnnotation(masterClk, \"scan_clk\"),\n SourceAnnotation(masterEn, \"scan_en\"))\n\n // [todo] This is not deterministic\n val chain: Seq[ComponentName] = masterOut +: v.injectors\n .flatMap{ case (k, _) => Seq(v.slaveIn(k), v.slaveOut(k)) }\n .toSeq :+ masterIn\n\n val annotations = chain\n .grouped(2).zipWithIndex\n .flatMap{ case (Seq(l, r), i) =>\n Seq(SourceAnnotation(l, s\"scan_${name}_$i\"),\n SinkAnnotation(r, s\"scan_${name}_$i\")) }\n\n a ++ masterAnnotations ++ annotations\n }\n\n state.copy(annotations = ((state.annotations.toSeq ++ ax).toSet -- myAnnos.toSet).toSeq)\n }\n }\n}\n", "groundtruth": " |${injectors.map{ case (k, v) => s\"${tab} ${v.name}, ${k.module.name}, ${slaveIn(k).module.name}.${slaveIn(k).name}, ${slaveOut(k).module.name}.${slaveOut(k).name}\"}.mkString(\"\\n\")}\n", "crossfile_context": ""}
{"task_id": "chiffre", "path": "chiffre/src/test/scala/chiffreTests/InstrumentationSpec.scala", "left_context": "// Copyright 2018 IBM\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\npackage chiffreTests\n\nimport chisel3._\nimport chisel3.iotesters.ChiselFlatSpec\nimport chisel3.stage.ChiselStage\nimport chiffre.{InjectorInfo, ChiffreController, ChiffreInjector, ChiffreInjectee}\nimport chiffre.passes.{ScanChainAnnotation, ScanChainDescriptionAnnotation, FaultInjectionAnnotation}\nimport chiffre.inject.{Injector, LfsrInjector32}\n\nclass DummyController extends Module with ChiffreController {\n val io = IO(new Bundle{})\n val scanId = \"dummy\"\n}\n\nclass DummyInjector extends Injector(1) with ChiffreInjector {\n val scanId = \"dummy\"\n val info = EmptyInjectorInfo\n}\n\nclass DummyInjectee extends Module with ChiffreInjectee {\n val io = IO(new Bundle{})\n val x = Reg(UInt(1.W))\n isFaulty(x, \"dummy\", classOf[LfsrInjector32])\n}\n\nclass InstrumentationSpec extends ChiselFlatSpec {\n behavior of \"ChiffreController annotation\"\n\n it should \"emit a ScanChainAnnotation\" in {\n val circuit = ChiselStage.elaborate(new DummyController)\n circuit.annotations.map(_.toFirrtl).collect{ case a: ScanChainAnnotation => a }.size should be (1)\n }\n", "right_context": "", "groundtruth": "\n behavior of \"Chiffree Injectee annotation\"\n\n it should \"emit an annotation\" in {\n val circuit = ChiselStage.elaborate(new DummyInjectee)\n", "crossfile_context": ""}
{"task_id": "chiffre", "path": "chiffre/src/test/scala/chiffreTests/inject/StuckAtInjectorSpec.scala", "left_context": "// Copyright 2018 IBM\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\npackage chiffreTests.inject\n\nimport chiffre.inject.{StuckAtInjector, StuckAtInjectorInfo, Mask, StuckAt}\nimport chisel3.iotesters.{ChiselFlatSpec, Driver}\n\nclass StuckAtTester(dut: StuckAtInjector) extends InjectorTester(dut) {\n require(dut.bitWidth == 8)\n val mask = BigInt(\"11110000\", 2)\n val stuckAt = BigInt(\"00110000\", 2)\n val in = BigInt(\"01010101\", 2)\n val faulty = BigInt(\"00110101\", 2)\n\n dut.info.fields.foreach {\n case m: Mask => m.bind(mask)\n case s: StuckAt => s.bind(stuckAt)\n }\n\n poke(dut.io.scan.en, 0)\n poke(dut.io.in, in)\n load(dut.info)\n poke(dut.io.scan.en, 1)\n step(1)\n poke(dut.io.scan.en, 0)\n step(1)\n\n val fault = peek(dut.io.out)\n assert(fault == faulty, s\"Expected to see $faulty, but got $fault\")\n\n poke(dut.io.scan.en, 1)\n step(1)\n poke(dut.io.scan.en, 0)\n val noFault = peek(dut.io.out)\n assert(noFault == in, s\"Expected to see $in, but got $noFault\")\n}\n\nclass StuckAtInjectorSpec extends ChiselFlatSpec {\n behavior of \"StuckAtInjectorInfo\"\n\n it should \"be the expected width\" in {\n val x = StuckAtInjectorInfo(1337)\n x.width should be (1337 * 2)\n }\n\n behavior of \"StuckAtInjector\"\n\n it should \"be able to cycle a configuration\" in {\n Driver(() => new StuckAtInjector(13)) { dut => new InjectorCycleTester(dut) }\n }\n\n it should \"make a signal stuck when enabled\" in {\n", "right_context": " }\n}\n", "groundtruth": " Driver(() => new StuckAtInjector(8)) { dut => new StuckAtTester(dut) }\n", "crossfile_context": ""}
{"task_id": "diagrammer", "path": "diagrammer/src/main/scala/dotvisualizer/RenderSvg.scala", "left_context": "// SPDX-License-Identifier: Apache-2.0\n\npackage dotvisualizer\n\nimport java.io.{File, PrintWriter}\n\nimport scala.concurrent.ExecutionContext.Implicits.global\nimport scala.concurrent.duration.Duration\nimport scala.concurrent.{blocking, Await, Future, TimeoutException}\nimport scala.sys.process._\n\nclass RenderSvg(dotProgram: String = \"dot\", dotTimeOut: Int = 7) {\n def render(fileName: String): Unit = {\n if (dotProgram != \"none\") {\n if (fileName.isEmpty) {\n println(s\"Tried to call render program $dotProgram without a filename\")\n } else if (!new File(fileName).exists()) {\n println(s\"Tried to call render program $dotProgram on non existent file $fileName\")\n } else {\n val dotProcessString = s\"$dotProgram -Tsvg -O $fileName\"\n val process = Process(dotProcessString).run()\n val processFuture = Future(blocking(process.exitValue()))\n try {\n Await.result(processFuture, Duration(dotTimeOut, \"sec\"))\n } catch {\n case _: TimeoutException =>\n println(s\"Rendering timed out after $dotTimeOut seconds on $fileName with command $dotProcessString\")\n println(s\"You can try increasing with the --dot-timeout seconds flag\")\n process.destroy()\n val printWriter = new PrintWriter(new File(fileName + \".svg\"))\n printWriter.print(s\"\"\"\n", "right_context": " | -->\n |\n |\n |\n |TopLevel \n | \n |\n |\n |\n |Sorry, Rendering timed out on this file, Use Back to return.\n |You can try increasing the timeout with the --dot-timeout seconds flag\n | \n | \n |Sorry, Rendering timed out on this file, Use Back to return \n | \n | \n | \n \"\"\".stripMargin)\n printWriter.close()\n\n }\n }\n }\n }\n\n}\n", "groundtruth": " |\n", "crossfile_context": ""}
{"task_id": "diagrammer", "path": "diagrammer/src/main/scala/dotvisualizer/ToLoFirrtl.scala", "left_context": "// SPDX-License-Identifier: Apache-2.0\n\npackage dotvisualizer\n\nimport firrtl.CompilerUtils.getLoweringTransforms\nimport firrtl.Mappers._\nimport firrtl.PrimOps.Dshl\nimport firrtl._\nimport firrtl.ir._\nimport firrtl.options.{Dependency, Phase}\nimport firrtl.stage.{FirrtlCircuitAnnotation, Forms}\nimport firrtl.transforms.BlackBoxSourceHelper\n\n/**\n * Use these lowering transforms to prepare circuit for compiling\n */\nclass ToLoFirrtl extends Phase {\n private val targets = Forms.LowFormOptimized ++ Seq(\n Dependency(passes.RemoveValidIf),\n Dependency(passes.memlib.VerilogMemDelays),\n Dependency(passes.SplitExpressions),\n Dependency[firrtl.transforms.LegalizeAndReductionsTransform],\n Dependency[firrtl.transforms.ConstantPropagation],\n Dependency[firrtl.transforms.CombineCats],\n Dependency(passes.CommonSubexpressionElimination),\n Dependency[firrtl.transforms.DeadCodeElimination]\n )\n\n private def compiler = new firrtl.stage.transforms.Compiler(targets, currentState = Nil)\n private val transforms = compiler.flattenedTransformOrder\n\n override def transform(annotationSeq: AnnotationSeq): AnnotationSeq = {\n\n annotationSeq.flatMap {\n case FirrtlCircuitAnnotation(circuit) =>\n val state = CircuitState(circuit, annotationSeq)\n val newState = transforms.foldLeft(state) {\n case (prevState, transform) => transform.runTransform(prevState)\n }\n Some(FirrtlCircuitAnnotation(newState.circuit))\n case other =>\n Some(other)\n }\n }\n}\n\n/**\n * Workaround for https://github.com/freechipsproject/firrtl/issues/498 from @jackkoenig\n */\nclass FixupOps extends Transform with DependencyAPIMigration {\n override def prerequisites = Seq.empty\n\n override def optionalPrerequisites = Seq.empty\n\n override def optionalPrerequisiteOf = Seq.empty\n\n override def invalidates(a: Transform) = false\n\n private def onExpr(expr: Expression): Expression =\n expr.map(onExpr) match {\n case prim @ DoPrim(Dshlw, _, _, _) => prim.copy(op = Dshl)\n case other => other\n }\n private def onStmt(stmt: Statement): Statement = stmt.map(onStmt).map(onExpr)\n", "right_context": " def execute(state: CircuitState): CircuitState = {\n state.copy(circuit = state.circuit.map(onMod))\n }\n}\n", "groundtruth": " private def onMod(mod: DefModule): DefModule = mod.map(onStmt)\n", "crossfile_context": ""}
{"task_id": "diagrammer", "path": "diagrammer/src/main/scala/dotvisualizer/dotnodes/LiteralNode.scala", "left_context": "// SPDX-License-Identifier: Apache-2.0\n\npackage dotvisualizer.dotnodes\n\ncase class LiteralNode(name: String, value: BigInt, parentOpt: Option[DotNode]) extends DotNode {\n", "right_context": "", "groundtruth": " def render: String = {\n s\"\"\"$absoluteName [shape=\"circle\" style=\"filled\" BGCOLOR=\"#C0C0C0\" label=\"$value\"]\n \"\"\".stripMargin\n }\n", "crossfile_context": ""}
{"task_id": "diagrammer", "path": "diagrammer/src/main/scala/dotvisualizer/dotnodes/PrimOpNode.scala", "left_context": "// SPDX-License-Identifier: Apache-2.0\n\npackage dotvisualizer.dotnodes\n\nobject PrimOpNode {\n /* the pseudoHash is necessary because case classes with identical args have identical hashes */\n var pseudoHash: Long = 0\n def hash: Long = {\n pseudoHash += 1\n pseudoHash\n }\n\n val BlackDot = \"●\"\n}\n\ncase class BinaryOpNode(\n name: String,\n parentOpt: Option[DotNode],\n arg0ValueOpt: Option[String],\n arg1ValueOpt: Option[String])\n extends DotNode {\n\n def in1: String = s\"$absoluteName:in1\"\n def in2: String = s\"$absoluteName:in2\"\n", "right_context": " override val asRhs: String = s\"$absoluteName:out\"\n\n def render: String = {\n s\"\"\"\n |$absoluteName [shape = \"plaintext\" label=<\n |
\n | \n | ${arg0ValueOpt.getOrElse(PrimOpNode.BlackDot)} \n | $name \n | ${PrimOpNode.BlackDot} \n | \n | \n | ${arg1ValueOpt.getOrElse(PrimOpNode.BlackDot)} \n | \n |
>];\n \"\"\".stripMargin\n }\n}\n\ncase class UnaryOpNode(name: String, parentOpt: Option[DotNode]) extends DotNode {\n def in1: String = s\"$absoluteName:in1\"\n override val absoluteName: String = s\"op_${name}_${PrimOpNode.hash}\"\n override val asRhs: String = s\"$absoluteName:out\"\n\n def render: String = {\n s\"\"\"\n |$absoluteName [shape = \"plaintext\" label=<\n |\n | \n | ● \n | $name \n | ● \n | \n |
>];\n \"\"\".stripMargin\n }\n}\n\ncase class OneArgOneParamOpNode(name: String, parentOpt: Option[DotNode], value: BigInt) extends DotNode {\n def in1: String = s\"$absoluteName:in1\"\n override val absoluteName: String = s\"op_${name}_${PrimOpNode.hash}\"\n override val asRhs: String = s\"$absoluteName:out\"\n\n def render: String = {\n s\"\"\"\n |$absoluteName [shape = \"plaintext\" label=<\n |\n | \n | ● \n | $name \n | ● \n | \n | \n | $value \n | \n |
>];\n \"\"\".stripMargin\n }\n}\ncase class OneArgTwoParamOpNode(\n name: String,\n parentOpt: Option[DotNode],\n value1: BigInt,\n value2: BigInt)\n extends DotNode {\n def in1: String = s\"$absoluteName:in1\"\n override val absoluteName: String = s\"op_${name}_${PrimOpNode.hash}\"\n override val asRhs: String = s\"$absoluteName:out\"\n\n def render: String = {\n s\"\"\"\n |$absoluteName [shape = \"plaintext\" label=<\n |\n | \n | ● \n | $name \n | ● \n | \n | \n | ($value1, $value2) \n | \n |
>];\n \"\"\".stripMargin\n }\n}\n", "groundtruth": " override val absoluteName: String = s\"op_${name}_${PrimOpNode.hash}\"\n", "crossfile_context": ""}
{"task_id": "diagrammer", "path": "diagrammer/src/main/scala/dotvisualizer/stage/DiagrammerPhase.scala", "left_context": "// SPDX-License-Identifier: Apache-2.0\n\npackage dotvisualizer.stage\n\nimport dotvisualizer.stage.phase.{\n CheckPhase,\n GenerateDotFilePhase,\n GetFirrtlCircuitPhase,\n OptionallyBuildTargetDirPhase\n}\nimport firrtl.options.phases.DeletedWrapper\nimport firrtl.options.{Dependency, Phase, PhaseManager}\n\nclass DiagrammerPhase extends PhaseManager(DiagrammerPhase.targets) {\n\n override val wrappers = Seq((a: Phase) => DeletedWrapper(a))\n\n}\n\nobject DiagrammerPhase {\n\n", "right_context": " )\n}\n", "groundtruth": " val targets: Seq[PhaseManager.PhaseDependency] = Seq(\n Dependency[CheckPhase],\n Dependency[GetFirrtlCircuitPhase],\n", "crossfile_context": ""}
{"task_id": "diagrammer", "path": "diagrammer/src/main/scala/dotvisualizer/stage/phase/GenerateDotFilePhase.scala", "left_context": "// SPDX-License-Identifier: Apache-2.0\n\npackage dotvisualizer.stage.phase\n\nimport java.io.{File, PrintWriter}\n\nimport dotvisualizer.RenderSvg\nimport dotvisualizer.stage.{\n DotTimeoutSecondsAnnotation,\n JustTopLevelAnnotation,\n OpenCommandAnnotation,\n SetRenderProgramAnnotation\n}\nimport dotvisualizer.transforms.{MakeDiagramGroup, ModuleLevelDiagrammer}\nimport firrtl.options.{Dependency, Phase, TargetDirAnnotation}\nimport firrtl.stage.FirrtlCircuitAnnotation\nimport firrtl.{AnnotationSeq, CircuitState}\n\nimport scala.sys.process._\n\nclass GenerateDotFilePhase extends Phase {\n", "right_context": "\n override def optionalPrerequisites = Seq.empty\n\n override def optionalPrerequisiteOf = Seq.empty\n\n override def invalidates(a: Phase) = false\n\n /**\n * Make a simple css file that controls highlighting\n *\n * @param targetDir where to put the css\n */\n def addCss(targetDir: String): Unit = {\n val file = new File(s\"$targetDir/styles.css\")\n val printWriter = new PrintWriter(file)\n printWriter.println(\n \"\"\"\n |.edge:hover * {\n | stroke: #ff0000;\n |}\n |.edge:hover polygon {\n | fill: #ff0000;\n |}\n \"\"\".stripMargin\n )\n printWriter.close()\n }\n\n /**\n * Open an svg file using the open program\n *\n * @param fileName file to be opened\n * @param openProgram program to use\n */\n def show(fileName: String, openProgram: String): Unit = {\n if (openProgram.nonEmpty && openProgram != \"none\") {\n val openProcessString = s\"$openProgram $fileName.svg\"\n openProcessString.!!\n } else {\n println(s\"\"\"There is no program identified which will render the svg files.\"\"\")\n println(s\"\"\"The file to start with is $fileName.svg, open it in the appropriate viewer\"\"\")\n println(s\"\"\"Specific module views should be in the same directory as $fileName.svg\"\"\")\n }\n }\n\n override def transform(annotationSeq: AnnotationSeq): AnnotationSeq = {\n val targetDir = annotationSeq.collectFirst { case TargetDirAnnotation(dir) => dir }.get\n val firrtlCircuit = annotationSeq.collectFirst { case FirrtlCircuitAnnotation(circuit) => circuit }.get\n val circuitState = CircuitState(firrtlCircuit, annotationSeq)\n\n addCss(targetDir)\n\n val dotProgram = annotationSeq.collectFirst {\n case SetRenderProgramAnnotation(program) => program\n }.getOrElse(\"dot\")\n\n val dotTimeOut = annotationSeq.collectFirst {\n case DotTimeoutSecondsAnnotation(secs) => secs\n }.getOrElse(7)\n\n val renderer = new RenderSvg(dotProgram, dotTimeOut)\n\n if (annotationSeq.exists { case JustTopLevelAnnotation => true; case _ => false }) {\n val justTopLevelTransform = new ModuleLevelDiagrammer(renderer)\n justTopLevelTransform.execute(circuitState)\n } else {\n val transform = new MakeDiagramGroup(renderer)\n transform.execute(circuitState)\n }\n\n val fileName = s\"$targetDir/${circuitState.circuit.main}_hierarchy.dot\"\n val openProgram = annotationSeq.collectFirst {\n case OpenCommandAnnotation(program) => program\n }.getOrElse(\"open\")\n\n show(fileName, openProgram)\n\n annotationSeq\n }\n}\n", "groundtruth": " override def prerequisites = Seq(Dependency[OptionallyBuildTargetDirPhase])\n", "crossfile_context": ""}
{"task_id": "diagrammer", "path": "diagrammer/src/main/scala/dotvisualizer/stage/phase/OptionallyBuildTargetDirPhase.scala", "left_context": "// SPDX-License-Identifier: Apache-2.0\n\npackage dotvisualizer.stage.phase\n\nimport java.io.File\n\nimport dotvisualizer.stage.DiagrammerException\nimport firrtl.options.{Dependency, Phase, TargetDirAnnotation}\nimport firrtl.stage.FirrtlCircuitAnnotation\nimport firrtl.{AnnotationSeq, FileUtils}\n\nclass OptionallyBuildTargetDirPhase extends Phase {\n override def prerequisites = Seq(Dependency[GetFirrtlCircuitPhase])\n\n override def optionalPrerequisites = Seq.empty\n\n override def optionalPrerequisiteOf = Seq.empty\n\n override def invalidates(a: Phase) = false\n\n override def transform(annotationSeq: AnnotationSeq): AnnotationSeq = {\n val newAnnotations: AnnotationSeq = if (annotationSeq.exists(_.isInstanceOf[TargetDirAnnotation])) {\n annotationSeq\n } else {\n val circuit = annotationSeq.collectFirst { case FirrtlCircuitAnnotation(circuit) => circuit }.get\n val targetDir = s\"test_run_dir/${circuit.main}\"\n annotationSeq :+ TargetDirAnnotation(targetDir)\n }\n\n newAnnotations.foreach {\n case TargetDirAnnotation(targetDir) =>\n val targetDirFile = new File(targetDir)\n if (targetDirFile.exists()) {\n if (!targetDirFile.isDirectory) {\n", "right_context": " }\n } else {\n FileUtils.makeDirectory(targetDir)\n if (!targetDirFile.exists()) {\n\n }\n }\n case _ =>\n }\n newAnnotations\n }\n}\n", "groundtruth": " throw new DiagrammerException(s\"Error: Target dir ${targetDir} exists and is not a directory\")\n", "crossfile_context": ""}
{"task_id": "diagrammer", "path": "diagrammer/src/main/scala/dotvisualizer/transforms/MakeDiagramGroup.scala", "left_context": "// SPDX-License-Identifier: Apache-2.0\n\npackage dotvisualizer.transforms\n\nimport dotvisualizer._\nimport dotvisualizer.stage.StartModuleNameAnnotation\nimport firrtl.options.TargetDirAnnotation\nimport firrtl.{CircuitForm, CircuitState, DependencyAPIMigration, LowForm, Transform}\n\nimport scala.collection.mutable\n\nclass MakeDiagramGroup(renderSvg: RenderSvg) extends Transform with DependencyAPIMigration {\n override def prerequisites = Seq.empty\n", "right_context": " override def invalidates(a: Transform) = false\n\n /**\n * Creates a series of diagrams starting with the startModule and continuing\n * through all descendant sub-modules.\n * @param state the state to be diagrammed\n * @return\n */\n\n override def execute(state: CircuitState): CircuitState = {\n\n val targetDir = state.annotations.collectFirst { case TargetDirAnnotation(dir) => dir }.getOrElse {\n s\"test_run_dir/${state.circuit.main}/\"\n }\n\n val startModule = state.annotations.collectFirst {\n case StartModuleNameAnnotation(moduleName) => moduleName\n }.getOrElse(state.circuit.main)\n\n val queue = new mutable.Queue[String]()\n val modulesSeen = new mutable.HashSet[String]()\n\n val pass_remove_gen = new RemoveTempWires()\n var cleanedState = pass_remove_gen.execute(state)\n\n val pass_top_level = new ModuleLevelDiagrammer(renderSvg)\n pass_top_level.execute(cleanedState)\n\n queue += startModule // set top level of diagram tree\n\n while (queue.nonEmpty) {\n val moduleName = queue.dequeue()\n if (!modulesSeen.contains(moduleName)) {\n\n val updatedAnnotations = {\n state.annotations.filterNot { x =>\n x.isInstanceOf[StartModuleNameAnnotation]\n } :+ StartModuleNameAnnotation(moduleName)\n }\n val stateToDiagram = CircuitState(cleanedState.circuit, state.form, updatedAnnotations)\n\n val pass = new MakeOneDiagram(renderSvg)\n pass.execute(stateToDiagram)\n\n queue ++= pass.subModulesFound.map(module => module.name)\n renderSvg.render(s\"$targetDir/$moduleName.dot\")\n }\n modulesSeen += moduleName\n }\n\n // we return the original state, all transform work is just in the interest of diagramming\n state\n }\n}\n", "groundtruth": "\n override def optionalPrerequisites = Seq.empty\n\n", "crossfile_context": ""}
{"task_id": "diagrammer", "path": "diagrammer/src/main/scala/dotvisualizer/transforms/RemoveTempWires.scala", "left_context": "// SPDX-License-Identifier: Apache-2.0\n\npackage dotvisualizer.transforms\n\nimport dotvisualizer.ToLoFirrtl\nimport dotvisualizer.stage.DiagrammerException\nimport firrtl.ir._\nimport firrtl.stage.FirrtlCircuitAnnotation\nimport firrtl.{\n CircuitForm,\n CircuitState,\n DependencyAPIMigration,\n FileUtils,\n LowForm,\n Parser,\n Transform,\n WRef,\n WSubField,\n WSubIndex\n}\n\nimport scala.collection.mutable\n\nclass RemoveTempWires extends Transform with DependencyAPIMigration {\n override def prerequisites = Seq.empty\n\n override def optionalPrerequisites = Seq.empty\n\n override def optionalPrerequisiteOf = Seq.empty\n\n override def invalidates(a: Transform) = false\n\n /**\n * Foreach Module in a firrtl circuit\n * Find all the DefNodes with temp names and render their expression\n * Remove all the found dev nodes\n * recursively replace their references with their associated expression\n * @param state to be altered\n * @return\n */\n\n def execute(state: CircuitState): CircuitState = {\n\n val c = state.circuit\n\n /**\n * removes all references to temp wires in module\n * @param module the module to be altered\n * @return\n */\n def removeTempWiresFromModule(module: Module): Module = {\n\n val toRemove = new mutable.HashMap[String, Expression]()\n\n /**\n * Saves reference to the expression associated\n * with a temp wire associated with a Node statement\n * @param s statement to be checked\n */\n def collectTempExpressions(s: Statement): Unit = s match {\n case block: Block =>\n block.stmts.foreach { substatement =>\n collectTempExpressions(substatement)\n }\n\n case node: DefNode =>\n if (node.name.startsWith(RemoveTempWires.GenPrefix) || node.name.startsWith(RemoveTempWires.TempPrefix)) {\n\n if (toRemove.contains(node.name)) {\n println(s\"Houston we have a problem, ${node.name} already marked for removal\")\n }\n toRemove(node.name) = node.value\n None\n }\n case _ => //do nothing\n }\n\n /**\n * recursively find any references to temp wires in the expression and replace the\n * references with the associated expression\n * @param e expression to be altered\n * @return\n */\n def removeGen(e: Expression): Expression = {\n e match {\n case wire: WRef =>\n if (\n (wire.name.startsWith(RemoveTempWires.GenPrefix) ||\n wire.name.startsWith(RemoveTempWires.TempPrefix)) && toRemove.contains(wire.name)\n ) {\n val new_node = toRemove(wire.name)\n removeGen(new_node)\n } else {\n wire\n }\n case wire: WSubField =>\n if (\n (wire.name.startsWith(RemoveTempWires.GenPrefix) ||\n wire.name.startsWith(RemoveTempWires.TempPrefix)) && toRemove.contains(wire.name)\n ) {\n val new_node = toRemove(wire.name)\n removeGen(new_node)\n } else {\n wire\n }\n case wire: WSubIndex =>\n wire.mapExpr(removeGen)\n case ee => ee.mapExpr(removeGen)\n }\n }\n\n /**\n * Removes node definition statements for temp wires\n * @param s statement to be altered\n * @return\n */\n def removeGenStatement(s: Statement): Option[Statement] = {\n s match {\n case block: Block =>\n", "right_context": " if (node.name.startsWith(RemoveTempWires.GenPrefix) || node.name.startsWith(RemoveTempWires.TempPrefix)) {\n None\n } else {\n Some(node.mapExpr(removeGen))\n }\n case other: Statement =>\n Some(other.mapExpr(removeGen))\n case _ => Some(s) //do nothing\n }\n }\n\n collectTempExpressions(module.body)\n val moduleWithTempExpressionsRemmoved = removeGenStatement(module.body)\n module.copy(body = moduleWithTempExpressionsRemmoved.get)\n }\n\n val newModules = c.modules.map {\n case m: Module => removeTempWiresFromModule(m)\n case otherMod => otherMod\n }\n\n state.copy(circuit = Circuit(c.info, newModules, c.main))\n }\n}\n\nobject RemoveTempWires {\n val GenPrefix = \"_GEN_\"\n val TempPrefix = \"_T_\"\n\n def main(args: Array[String]): Unit = {\n args.headOption match {\n case Some(fileName) =>\n val firrtlSource = FileUtils.getLines(fileName).mkString(\"\\n\")\n val annos = (new ToLoFirrtl).transform(Seq(FirrtlCircuitAnnotation(Parser.parse(firrtlSource))))\n val firrtl = annos.collectFirst { case FirrtlCircuitAnnotation(c) => c }.getOrElse {\n throw new DiagrammerException(\"Error: could not process supplied firrtl\")\n }\n\n val grapher = new RemoveTempWires\n\n val newState = grapher.execute(CircuitState(firrtl, Seq.empty))\n println(s\"${newState.circuit.serialize}\")\n\n case _ =>\n }\n }\n}\n", "groundtruth": " val result = Some(Block(block.stmts.flatMap { substatement =>\n removeGenStatement(substatement)\n }))\n", "crossfile_context": ""}
{"task_id": "diagrammer", "path": "diagrammer/src/test/scala/dotvisualizer/PrintfSpec.scala", "left_context": "// SPDX-License-Identifier: Apache-2.0\n\npackage dotvisualizer\n\nimport chisel3._\nimport chisel3.stage.ChiselGeneratorAnnotation\nimport dotvisualizer.stage._\nimport firrtl.FileUtils\nimport firrtl.annotations.Annotation\nimport firrtl.options.TargetDirAnnotation\nimport org.scalatest.freespec.AnyFreeSpec\nimport org.scalatest.matchers.should.Matchers\n\nimport java.io.{ByteArrayOutputStream, PrintStream}\n\nclass HasPrintf extends Module {\n val in = IO(Input(Bool()))\n val out = IO(Output(Bool()))\n out := in\n printf(\"in %d, out %d\\n\", in, out)\n}\nclass PrintfSpec extends AnyFreeSpec with Matchers {\n\n \"printfs can now be rendered\" - {\n\n def makeDotFile(showPrintfs: Boolean): String = {\n val targetDir = s\"test_run_dir/has_printf_$showPrintfs\"\n val annos = Seq(\n TargetDirAnnotation(targetDir),\n ChiselGeneratorAnnotation(() => new HasPrintf),\n RankElementsAnnotation,\n RankDirAnnotation(\"TB\"),\n OpenCommandAnnotation(\"\")\n", "right_context": " else { Seq.empty[Annotation] })\n val outputBuf = new ByteArrayOutputStream()\n Console.withOut(new PrintStream(outputBuf)) {\n (new DiagrammerStage).transform(annos)\n }\n val output = outputBuf.toString\n output should include(s\"creating dot file test_run_dir/has_printf_$showPrintfs/HasPrintf.dot\")\n\n FileUtils.getText(s\"$targetDir/HasPrintf.dot\")\n }\n\n \"showPrintfs=true will render printfs in dot file\" in {\n val dotText = makeDotFile(showPrintfs = true)\n\n dotText should include(\"struct_cluster_HasPrintf_printf_\")\n dotText should include(\"\"\"printf(\"in %d, out %d\\n\")\"\"\")\n }\n\n \"default behavior will not render printfs in dot file\" in {\n val dotText = makeDotFile(showPrintfs = false)\n\n dotText.contains(\"struct_cluster_HasPrintf_printf_\") should be(false)\n dotText.contains(\"\"\"printf(\"in %d, out %d\\n\")\"\"\") should be(false)\n }\n }\n}\n", "groundtruth": " ) ++ (if (showPrintfs) { Seq(ShowPrintfsAnnotation) }\n", "crossfile_context": ""}
{"task_id": "dana", "path": "dana/src/main/scala/dana/ActivationFunction.scala", "left_context": "// See LICENSE.BU for license details.\n// See LICENSE.IBM for license details.\n\npackage dana\n\nimport chisel3._\nimport chisel3.util._\nimport cde._\n\nimport dana.abi._\n\nclass ActivationFunctionReq(implicit p: Parameters) extends DanaBundle()(p) {\n val decimal = UInt(decimalPointWidth.W)\n val steepness = UInt(steepnessWidth.W)\n // Differentiate activation function requests vs. error function\n // requests\n val activationFunction = UInt(log2Up(18).W) // [TODO] fragile\n val in = SInt(elementWidth.W)\n}\n\nclass ActivationFunctionReqLearn(implicit p: Parameters)\n extends ActivationFunctionReq()(p) {\n val afType = UInt(log2Up(2).W) // [TODO] fragile\n val errorFunction = UInt(p(GlobalInfo).error_function.W)\n}\n\nclass ActivationFunctionResp(implicit p: Parameters) extends DanaBundle()(p) {\n val out = SInt(elementWidth.W)\n}\n\nclass ActivationFunctionInterface(implicit p: Parameters) extends DanaBundle()(p) {\n val req = Flipped(Valid(new ActivationFunctionReq))\n val resp = Valid(new ActivationFunctionResp)\n}\n\nclass ActivationFunctionInterfaceLearn(implicit p: Parameters)\n extends ActivationFunctionInterface()(p) {\n override val req = Flipped(Valid(new ActivationFunctionReqLearn))\n}\n\nclass DSP(implicit p: Parameters) extends DanaModule()(p) {\n val io = IO(new Bundle {\n val a = Input(SInt(elementWidth.W))\n val b = Input(SInt(elementWidth.W))\n val c = Input(UInt(elementWidth.W))\n val d = Output(SInt(elementWidth.W))\n })\n io.d := (((io.a * io.b) >> io.c)(elementWidth - 1, 0)).asSInt\n}\n\nclass ActivationFunction(id: Int = 0)(implicit p: Parameters) extends DanaModule()(p) {\n lazy val io = (new ActivationFunctionInterface)\n override val printfSigil = \"dana.PE[\" + id + \"]: \"\n\n // Temporary values\n val inD0 = Wire(SInt(elementWidth.W))\n val decimal = Wire(UInt())\n val out = Reg(init = 0.S(elementWidth.W))\n\n val _xmin = -1420910720.S // -54B16080\n val _x1 = -790391808.S // -2F1C6C00\n val _x2 = -294906496.S // -1193EA80\n val _x3 = 294906496.S // 1193EA80\n val _x4 = 790391808.S // 2F1C6C00\n val _xmax = 1420910720.S // 54b16080\n val _sigy0 = 10737418.S // 00A3D70A\n val _sigy1 = 107374184.S // 06666668\n val _sigy2 = 536870912.S // 20000000\n val _sigy3 = 1610612736.S // 60000000\n val _sigy4 = 2040109440.S // 79999980\n val _sigy5 = 2136746240.S // 7F5C2900\n val _slope1 = 164567525.S // 09CF19E5\n val _slope2 = 930741212.S // 3779FBDC\n val _slope3 = 1954723819.S // 7482B7EB\n val _slope4 = 930741280.S // 3779FC20\n val _slope5 = 164567500.S // 09CF19CC\n val _symy0 = -2126008831.S // -7EB851FF\n val _symy1 = -1932735232.S // -73333300\n val _symy2 = -1073741824.S // -40000000\n val _symy3 = 1073741824.S // 40000000\n val _symy4 = 1932735232.S // 73333300\n val _symy5 = 2126008831.S // 7EB851FF\n // Chisel (or Scala) has a problem with creating UInts that use the\n // full bit width when specifying the value as an integer, e.g., the\n // string assignment that will be interpreted as hex works, but the\n // below assignment to the full width sslope3 does not work\n val _sslope1 = \"h139E343F\".U // 139E343F\n val _sslope2 = \"h6EF3F751\".U // 6EF3F751\n val _sslope3 = \"hE9056FD7\".U // E9056FD7\n val _sslope4 = \"h6EF3F751\".U // 6EF3F751\n val _sslope5 = \"h139E343F\".U // 139E343F\n\n val xmin = _xmin >> (29.U-io.req.bits.decimal-decimalPointOffset.U)\n val x1 = _x1 >> (29.U-io.req.bits.decimal-decimalPointOffset.U)\n val x2 = _x2 >> (29.U-io.req.bits.decimal-decimalPointOffset.U)\n val x3 = _x3 >> (29.U-io.req.bits.decimal-decimalPointOffset.U)\n val x4 = _x4 >> (29.U-io.req.bits.decimal-decimalPointOffset.U)\n val xmax = _xmax >> (29.U-io.req.bits.decimal-decimalPointOffset.U)\n val sigy0 = _sigy0 >> (31.U-io.req.bits.decimal-decimalPointOffset.U)\n val sigy1 = _sigy1 >> (31.U-io.req.bits.decimal-decimalPointOffset.U)\n val sigy2 = _sigy2 >> (31.U-io.req.bits.decimal-decimalPointOffset.U)\n val sigy3 = _sigy3 >> (31.U-io.req.bits.decimal-decimalPointOffset.U)\n val sigy4 = _sigy4 >> (31.U-io.req.bits.decimal-decimalPointOffset.U)\n val sigy5 = _sigy5 >> (31.U-io.req.bits.decimal-decimalPointOffset.U)\n val slope1 = _slope1 >>(32.U-io.req.bits.decimal-decimalPointOffset.U)\n val slope2 = _slope2 >>(32.U-io.req.bits.decimal-decimalPointOffset.U)\n val slope3 = _slope3 >>(32.U-io.req.bits.decimal-decimalPointOffset.U)\n val slope4 = _slope4 >>(32.U-io.req.bits.decimal-decimalPointOffset.U)\n val slope5 = _slope5 >>(32.U-io.req.bits.decimal-decimalPointOffset.U)\n val symy0 = _symy0 >> (31.U-io.req.bits.decimal-decimalPointOffset.U)\n val symy1 = _symy1 >> (31.U-io.req.bits.decimal-decimalPointOffset.U)\n val symy2 = _symy2 >> (31.U-io.req.bits.decimal-decimalPointOffset.U)\n val symy3 = _symy3 >> (31.U-io.req.bits.decimal-decimalPointOffset.U)\n val symy4 = _symy4 >> (31.U-io.req.bits.decimal-decimalPointOffset.U)\n val symy5 = _symy5 >> (31.U-io.req.bits.decimal-decimalPointOffset.U)\n val sslope1= _sslope1>>(32.U-io.req.bits.decimal-decimalPointOffset.U)\n val sslope2= _sslope2>>(32.U-io.req.bits.decimal-decimalPointOffset.U)\n val sslope3= _sslope3>>(32.U-io.req.bits.decimal-decimalPointOffset.U)\n val sslope4= _sslope4>>(32.U-io.req.bits.decimal-decimalPointOffset.U)\n val sslope5= _sslope5>>(32.U-io.req.bits.decimal-decimalPointOffset.U)\n\n decimal := decimalPointOffset.U((decimalPointWidth + log2Up(decimalPointOffset)).W) + io.req.bits.decimal\n\n // DSP Unit\n val dsp = Module(new DSP).io\n def DSP(a: SInt, b: SInt, c: UInt) {\n dsp.a := a\n dsp.b := b\n dsp.c := c\n }\n\n // All activation functions currently take two cycles, so the output\n // valid signal is delayed by two cycles.\n val ioVal_d0 = Reg(next = io.req.valid)\n val ioVal_d1 = Reg(next = ioVal_d0)\n io.resp.bits.out := out\n io.resp.valid := ioVal_d1\n val dataIn = RegNext(io.req.bits.in)\n\n when (ioVal_d1) {\n printfInfo(\"af(0x%x) = 0x%x\\n\", dataIn, out)\n }\n\n def applySteepness(x: SInt, steepness: UInt): SInt = {\n val tmp = Wire(SInt())\n when (steepness < steepnessOffset.U) {\n tmp := x >> (steepnessOffset.U - steepness)\n } .elsewhen (steepness === steepnessOffset.U) {\n tmp := x\n } .otherwise {\n tmp := x << (steepness - steepnessOffset.U)\n }\n tmp\n }\n\n val one = 1.S(elementWidth.W) << decimal\n val negOne = -1.S(elementWidth.W) << decimal\n val seventeen = 17.S(elementWidth.W) << decimal\n val negSeventeen = -17.S(elementWidth.W) << decimal\n val offsetX = Wire(SInt(elementWidth.W))\n val offsetSigY = Wire(SInt(elementWidth.W))\n val offsetSymY = Wire(SInt(elementWidth.W))\n val slopeSig = Wire(SInt(elementWidth.W))\n val slopeSym = Wire(SInt(elementWidth.W))\n when(inD0 < xmin) {\n offsetX := 0.S\n offsetSigY := 0.S\n offsetSymY := negOne\n slopeSig := 0.S\n slopeSym := 0.S\n } .elsewhen((xmin <= inD0) && (inD0 < x1)) {\n offsetX := xmin\n offsetSigY := sigy0\n offsetSymY := symy0\n slopeSig := slope1\n slopeSym := sslope1.asSInt\n } .elsewhen((x1 <= inD0) && (inD0 < x2)) {\n offsetX := x1\n offsetSigY := sigy1\n offsetSymY := symy1\n slopeSig := slope2\n slopeSym := sslope2.asSInt\n } .elsewhen((x2 <= inD0) && (inD0 < x3)) {\n offsetX := x2\n offsetSigY := sigy2\n offsetSymY := symy2\n slopeSig := slope3\n slopeSym := sslope3.asSInt\n } .elsewhen((x3 <= inD0) && (inD0 < x4)) {\n offsetX := x3\n offsetSigY := sigy3\n offsetSymY := symy3\n slopeSig := slope4\n slopeSym := sslope4.asSInt\n } .elsewhen((xmin <= inD0) && (inD0 < xmax)) {\n offsetX := x4\n offsetSigY := sigy4\n offsetSymY := symy4\n slopeSig := slope5\n slopeSym := sslope5.asSInt\n } .otherwise {\n offsetX := 0.S\n offsetSigY := one\n offsetSymY := one\n slopeSig := 0.S\n slopeSym := 0.S\n }\n\n // [TODO] You can probably remove this---by default `out` gets a\n // garbage value (a very big integer) which should be visibile in\n // the output\n DSP(slopeSym, inD0-offsetX, decimal)\n out := dsp.d + offsetSymY\n inD0 := applySteepness(dataIn, io.req.bits.steepness)\n // FANN_LINEAR\n switch (io.req.bits.activationFunction) {\n is (e_FANN_LINEAR) {\n out := inD0\n } // FANN_THRESHOLD\n is (e_FANN_THRESHOLD) {\n when (inD0 <= 0.S) { out := 0.S\n", "right_context": " } // FANN_THRESHOLD_SYMMETRIC\n is (e_FANN_THRESHOLD_SYMMETRIC) {\n when (inD0 < 0.S) {\n out := negOne\n } .elsewhen(inD0 === 0.S) {\n out := 0.S\n } .otherwise {\n out := one }\n } // FANN_SIGMOID and STEPWISE\n is (e_FANN_SIGMOID) {\n DSP(slopeSig, inD0-offsetX, decimal)\n out := dsp.d + offsetSigY\n }\n is (e_FANN_SIGMOID_STEPWISE) {\n DSP(slopeSig, inD0-offsetX, decimal)\n out := dsp.d + offsetSigY\n }\n }\n}\n\nclass ActivationFunctionLearn(id: Int = 0)(implicit p: Parameters)\n extends ActivationFunction(id)(p) {\n override lazy val io = (new ActivationFunctionInterfaceLearn)\n\n // atanh specific\n // Binary Point: 31\n val _atanh_x0 = -2147483433.S // -0.9999999\n val _atanh_x1 = -2138482164.S // -0.9958083573500538\n val _atanh_x2 = -1876440389.S // -0.8737856469351458\n val _atanh_x3 = 1876440379.S // 0.873785642278533\n val _atanh_x4 = 2138482162.S // 0.9958083564187312\n val _atanh_x5 = 2147483433.S // 0.9999999\n // Binary Point: 26\n val _atanh_y0 = -1128183406.S // -16.81124278204462\n val _atanh_y1 = -413773911.S // -6.165711741243977\n val _atanh_y2 = -181041891.S // -2.6977343972924133\n val _atanh_y3 = 181041888.S // 2.697734357912798\n val _atanh_y4 = 413773896.S // 6.165711518591778\n val _atanh_y5 = 1128183406.S // 16.81124278204462\n // Binary Point: 19\n val _atanh_s1 = 1331568027.U // 2539.7644566343943\n val _atanh_s2 = 14900660.U // 28.42075325289503\n val _atanh_s3 = 1618692.U // 3.087409817560523\n val _atanh_s4 = 14900659.U // 28.420750883269488\n val _atanh_s5 = 1331567759.U // 2539.763945441386\n // Binary Point: 31\n val atanh_x0 = _atanh_x0 >> (31.U-io.req.bits.decimal-decimalPointOffset.U)\n val atanh_x1 = _atanh_x1 >> (31.U-io.req.bits.decimal-decimalPointOffset.U)\n val atanh_x2 = _atanh_x2 >> (31.U-io.req.bits.decimal-decimalPointOffset.U)\n val atanh_x3 = _atanh_x3 >> (31.U-io.req.bits.decimal-decimalPointOffset.U)\n val atanh_x4 = _atanh_x4 >> (31.U-io.req.bits.decimal-decimalPointOffset.U)\n val atanh_x5 = _atanh_x5 >> (31.U-io.req.bits.decimal-decimalPointOffset.U)\n // Binary Point: 26\n val atanh_y0 = _atanh_y0 >> (26.U-io.req.bits.decimal-decimalPointOffset.U)\n val atanh_y1 = _atanh_y1 >> (26.U-io.req.bits.decimal-decimalPointOffset.U)\n val atanh_y2 = _atanh_y2 >> (26.U-io.req.bits.decimal-decimalPointOffset.U)\n val atanh_y3 = _atanh_y3 >> (26.U-io.req.bits.decimal-decimalPointOffset.U)\n val atanh_y4 = _atanh_y4 >> (26.U-io.req.bits.decimal-decimalPointOffset.U)\n val atanh_y5 = _atanh_y5 >> (26.U-io.req.bits.decimal-decimalPointOffset.U)\n // Binary Point: 19\n val atanh_s1 = _atanh_s1 >> (19.U-io.req.bits.decimal-decimalPointOffset.U)\n val atanh_s2 = _atanh_s2 >> (19.U-io.req.bits.decimal-decimalPointOffset.U)\n val atanh_s3 = _atanh_s3 >> (19.U-io.req.bits.decimal-decimalPointOffset.U)\n val atanh_s4 = _atanh_s4 >> (19.U-io.req.bits.decimal-decimalPointOffset.U)\n val atanh_s5 = _atanh_s5 >> (19.U-io.req.bits.decimal-decimalPointOffset.U)\n\n // Atanh error function\n val atanhOffsetX = Wire(SInt(elementWidth.W))\n val atanhOffsetY = Wire(SInt(elementWidth.W))\n val atanhSlope = Wire(SInt(elementWidth.W))\n when (dataIn < atanh_x0) {\n atanhOffsetX := 0.S\n atanhOffsetY := negSeventeen\n atanhSlope := 0.S\n } .elsewhen ((atanh_x0 <= dataIn) && (dataIn < atanh_x1)) {\n atanhOffsetX := atanh_x0\n atanhOffsetY := atanh_y0\n atanhSlope := atanh_s1.asSInt\n } .elsewhen ((atanh_x1 <= dataIn) && (dataIn < atanh_x2)) {\n atanhOffsetX := atanh_x1\n atanhOffsetY := atanh_y1\n atanhSlope := atanh_s2.asSInt\n } .elsewhen ((atanh_x2 <= dataIn) && (dataIn < atanh_x3)) {\n atanhOffsetX := atanh_x2\n atanhOffsetY := atanh_y2\n atanhSlope := atanh_s3.asSInt\n } .elsewhen ((atanh_x3 <= dataIn) && (dataIn < atanh_x4)) {\n atanhOffsetX := atanh_x3\n atanhOffsetY := atanh_y3\n atanhSlope := atanh_s4.asSInt\n } .elsewhen ((atanh_x4 <= dataIn) && (dataIn < atanh_x5)) {\n atanhOffsetX := atanh_x4\n atanhOffsetY := atanh_y4\n atanhSlope := atanh_s5.asSInt\n } .otherwise {\n atanhOffsetX := 0.S\n atanhOffsetY := seventeen\n atanhSlope := 0.S\n }\n\n when (io.req.bits.afType === e_AF_DO_ERROR_FUNCTION) {\n switch (io.req.bits.errorFunction) {\n is (e_FANN_ERRORFUNC_LINEAR) {\n out := dataIn\n }\n is (e_FANN_ERRORFUNC_TANH) {\n DSP(atanhSlope, dataIn-atanhOffsetX, decimal)\n out := dsp.d + atanhOffsetY\n }\n }\n }\n}\n", "groundtruth": " } .otherwise { out := one }\n", "crossfile_context": ""}
{"task_id": "dana", "path": "dana/src/main/scala/dana/ProcessingElement.scala", "left_context": "// See LICENSE.BU for license details.\n// See LICENSE.IBM for license details.\n\npackage dana\n\nimport Chisel._\nimport cde._\n\nimport dana.abi._\n\nclass ProcessingElementReq(implicit p: Parameters) extends DanaBundle()(p) {\n val numWeights = UInt(p(NeuronInfo).num_weights.W)\n val index = UInt(log2Up(peTableNumEntries).W)\n val decimalPoint = UInt(decimalPointWidth.W)\n val steepness = UInt(steepnessWidth.W)\n val activationFunction = UInt(activationFunctionWidth.W)\n val iBlock = Vec(elementsPerBlock, SInt(elementWidth.W))\n val wBlock = Vec(elementsPerBlock, SInt(elementWidth.W))\n val bias = SInt(elementWidth.W)\n}\n\nclass ProcessingElementReqLearn(implicit p: Parameters)\n extends ProcessingElementReq()(p) {\n val errorFunction = UInt(p(GlobalInfo).error_function.W)\n val learningRate = UInt(elementWidth.W)\n val weightDecay = SInt(elementWidth.W)\n val learnReg = SInt(elementWidth.W)\n val stateLearn = UInt(log2Up(8).W) // [TODO] fragile\n val inLast = Bool()\n val inFirst = Bool()\n val dw_in = SInt(elementWidth.W)\n val tType = UInt(log2Up(3).W)\n}\n\nclass ProcessingElementResp(implicit p: Parameters) extends DanaBundle()(p) {\n val data = SInt(elementWidth.W)\n val state = UInt(log2Up(PE_states.size).W)\n val index = UInt(log2Up(peTableNumEntries).W)\n val incWriteCount = Bool()\n}\n\nclass ProcessingElementRespLearn(implicit p: Parameters)\n extends ProcessingElementResp()(p) {\n val dataBlock = Vec(elementsPerBlock, SInt(elementWidth.W))\n val error = SInt(elementWidth.W)\n val resetWeightPtr = Bool()\n}\n\nclass ProcessingElementInterface(implicit p: Parameters) extends DanaBundle()(p) {\n // The Processing Element Interface consists of three main\n // components: requests from the PE Table (really kicks to do\n // something), responses to the PE Table, and semi-static data which\n // th PE Table manages and is used by the PEs for computation.\n val req = Flipped(Decoupled(new ProcessingElementReq))\n val resp = Decoupled(new ProcessingElementResp)\n}\n\nclass ProcessingElementInterfaceLearn(implicit p: Parameters)\n extends ProcessingElementInterface()(p) {\n override val req = Flipped(Decoupled(new ProcessingElementReqLearn))\n override val resp = Decoupled(new ProcessingElementRespLearn)\n}\n\nclass ProcessingElement(id: Int = 0)(implicit p: Parameters) extends DanaModule()(p) {\n override val printfSigil = \"dana.PE[\" + id + \"]: \"\n\n // Interface to the PE Table\n lazy val io = IO(new ProcessingElementInterface)\n\n // Activation Function module\n lazy val af = Module(new ActivationFunction(id))\n\n val index = Reg(UInt(p(NeuronInfo).num_weights.W))\n val acc = Reg(SInt(elementWidth.W))\n val dataOut = Reg(SInt(elementWidth.W))\n val reqSent = Reg(Bool())\n val eleIndex = index(log2Up(elementsPerBlock) - 1, 0)\n\n val state = Reg(UInt(log2Up(PE_states.size).W),\n init = PE_states('e_PE_UNALLOCATED))\n val nextState = Wire(UInt(log2Up(PE_states.size).W))\n nextState := state\n\n // Local state storage. Any and all of these are possible kludges\n // which could be implemented more cleanly.\n val hasBias = Reg(Bool())\n val steepness = steepnessOffset.U - io.req.bits.steepness\n val decimal = decimalPointOffset.U((decimalPointWidth + 1).W) +\n io.req.bits.decimalPoint\n val one = 1.S << decimal\n\n def applySteepness(x: SInt, steepness: UInt): SInt = {\n val tmp = Wire(SInt())\n when (steepness < (steepnessOffset).U) {\n tmp := x >> ((steepnessOffset).U - steepness)\n } .elsewhen (steepness === (steepnessOffset).U) {\n tmp := x\n } .otherwise {\n tmp := x << (steepness - (steepnessOffset).U)\n }\n tmp\n }\n\n // DSP Unit\n val dsp = Module(new DSP).io\n def DSP(a: SInt, b: SInt, c: UInt) {\n dsp.a := a\n dsp.b := b\n dsp.c := c\n }\n DSP(0.S, 0.S, 0.U)\n\n // Default values\n acc := acc\n reqSent := reqSent\n io.req.ready := Bool(false)\n io.resp.valid := Bool(false)\n io.resp.bits.state := state\n io.resp.bits.index := io.req.bits.index\n io.resp.bits.data := dataOut\n io.resp.bits.incWriteCount := Bool(false)\n index := index\n // Activation function unit default values\n af.io.req.valid := Bool(false)\n af.io.req.bits.in := (0).S\n af.io.req.bits.decimal := io.req.bits.decimalPoint\n af.io.req.bits.steepness := io.req.bits.steepness\n af.io.req.bits.activationFunction := io.req.bits.activationFunction\n\n state := state\n // Jump to nextState when we are able to get a request out\n def reqNoResp() = {\n when (io.req.valid) { state := nextState }\n }\n // Jump to nextState when we get a request out and we receive a\n // response\n def reqWaitForResp() = {\n when (!reqSent) {\n io.resp.valid := true.B\n reqSent := io.req.valid\n } .elsewhen (io.req.valid) {\n reqSent := false.B\n state := nextState }}\n def reqAf() = {\n when (!reqSent) {\n af.io.req.valid := true.B\n reqSent := true.B\n } .elsewhen (af.io.resp.valid) {\n reqSent := false.B\n state := nextState }}\n\n // State-driven logic\n switch (state) {\n is (PE_states('e_PE_UNALLOCATED)) {\n nextState := PE_states('e_PE_GET_INFO)\n reqNoResp()\n io.req.ready := true.B\n hasBias := false.B\n index := 0.U\n reqSent := false.B\n }\n is (PE_states('e_PE_GET_INFO)) {\n dataOut := 0.S\n index := 0.U\n nextState := PE_states('e_PE_REQUEST_INPUTS_AND_WEIGHTS)\n reqWaitForResp()\n }\n is (PE_states('e_PE_REQUEST_INPUTS_AND_WEIGHTS)) {\n // If hasBias is false, then this is the first time we're in this\n // state and we need to load the bias into the accumulator\n hasBias := true.B\n when (hasBias === false.B) {\n acc := io.req.bits.bias\n }\n nextState := PE_states('e_PE_RUN)\n reqWaitForResp()\n }\n is (PE_states('e_PE_RUN)) {\n when (index === (io.req.bits.numWeights - 1.U)) {\n state := PE_states('e_PE_ACTIVATION_FUNCTION)\n } .elsewhen (eleIndex === (elementsPerBlock - 1).U) {\n state := PE_states('e_PE_REQUEST_INPUTS_AND_WEIGHTS)\n }\n DSP(io.req.bits.iBlock(eleIndex), io.req.bits.wBlock(eleIndex), decimal)\n acc := acc + dsp.d\n index := index + 1.U\n printfInfo(\"run 0x%x + (0x%x * 0x%x) >> 0x%x = 0x%x\\n\",\n acc, io.req.bits.iBlock(eleIndex), io.req.bits.wBlock(eleIndex),\n decimal, acc + dsp.d)\n", "right_context": " dataOut := Mux(af.io.resp.valid, af.io.resp.bits.out, dataOut)\n }\n is (PE_states('e_PE_DONE)) {\n nextState := PE_states('e_PE_UNALLOCATED)\n reqNoResp()\n io.resp.bits.incWriteCount := true.B\n io.resp.valid := true.B\n }\n }\n\n assert (!(state === PE_states('e_PE_ERROR)), printfSigil ++\n \"is in error state\\n\")\n}\n\nclass ProcessingElementLearn(id: Int = 0)(implicit p: Parameters)\n extends ProcessingElement(id)(p) {\n override lazy val io = IO(new ProcessingElementInterfaceLearn)\n override lazy val af = Module(new ActivationFunctionLearn(id))\n\n val weightWB = Reg(Vec(elementsPerBlock, SInt(elementWidth.W)))\n val derivative = Reg(SInt(elementWidth.W)) //delta\n val errorOut = Reg(SInt(elementWidth.W)) //ek\n val mse = Reg(SInt(elementWidth.W))\n val dwWritebackDone = Reg(Bool())\n val stateLearn = io.req.bits.stateLearn\n\n // Defaults\n derivative := derivative\n io.resp.bits.dataBlock := weightWB\n io.resp.bits.error := errorOut\n io.resp.bits.resetWeightPtr := false.B\n af.io.req.bits.afType := e_AF_DO_ACTIVATION_FUNCTION\n af.io.req.bits.errorFunction := io.req.bits.errorFunction\n\n switch (state) {\n is (PE_states('e_PE_UNALLOCATED)) {\n dwWritebackDone := false.B\n }\n is (PE_states('e_PE_GET_INFO)) {\n nextState := PE_states('e_PE_REQUEST_OUTPUTS_ERROR_BACKPROP)\n when (stateLearn === e_TTABLE_STATE_FEEDFORWARD ||\n stateLearn === e_TTABLE_STATE_LEARN_FEEDFORWARD ||\n ((stateLearn === e_TTABLE_STATE_LEARN_WEIGHT_UPDATE) &&\n (io.req.bits.tType === e_TTYPE_BATCH))) {\n nextState := PE_states('e_PE_REQUEST_INPUTS_AND_WEIGHTS)\n }\n reqWaitForResp()\n }\n is (PE_states('e_PE_REQUEST_INPUTS_AND_WEIGHTS)) {\n when (io.req.bits.tType === e_TTYPE_BATCH) {\n when (stateLearn === e_TTABLE_STATE_LEARN_ERROR_BACKPROP ||\n dwWritebackDone) {\n nextState := PE_states('e_PE_RUN_UPDATE_SLOPE)\n } .elsewhen (stateLearn === e_TTABLE_STATE_LEARN_WEIGHT_UPDATE) {\n nextState := PE_states('e_PE_RUN_WEIGHT_UPDATE) }\n } .elsewhen (io.req.bits.tType === e_TTYPE_INCREMENTAL) {\n when (stateLearn === e_TTABLE_STATE_LEARN_ERROR_BACKPROP ||\n dwWritebackDone) {\n nextState := PE_states('e_PE_RUN_UPDATE_SLOPE) }}\n reqWaitForResp()\n }\n is (PE_states('e_PE_RUN)) {\n when (index === (io.req.bits.numWeights - 1.U)) {\n state := PE_states('e_PE_ACTIVATION_FUNCTION)\n } .elsewhen (eleIndex === (elementsPerBlock - 1).U) {\n state := PE_states('e_PE_REQUEST_INPUTS_AND_WEIGHTS)\n }\n DSP(io.req.bits.iBlock(eleIndex), io.req.bits.wBlock(eleIndex), decimal)\n acc := acc + dsp.d\n index := index + 1.U\n }\n is (PE_states('e_PE_ACTIVATION_FUNCTION)) {\n af.io.req.bits.afType := e_AF_DO_ACTIVATION_FUNCTION\n }\n is (PE_states('e_PE_DONE)) {\n when (io.req.bits.inLast &&\n stateLearn === e_TTABLE_STATE_LEARN_FEEDFORWARD) {\n nextState := PE_states('e_PE_COMPUTE_DERIVATIVE)\n } .otherwise {\n nextState := PE_states('e_PE_UNALLOCATED)\n }\n reqNoResp()\n io.resp.bits.resetWeightPtr := true.B\n }\n is (PE_states('e_PE_COMPUTE_DERIVATIVE)){\n state := Mux((stateLearn === e_TTABLE_STATE_LEARN_ERROR_BACKPROP),\n PE_states('e_PE_COMPUTE_DELTA), PE_states('e_PE_REQUEST_EXPECTED_OUTPUT))\n\n val af = io.req.bits.activationFunction\n when (af === e_FANN_LINEAR) {\n printfWarn(\"Linear activation function untested\\n\")\n when (steepness < steepnessOffset.U) {\n derivative := one >> (steepnessOffset.U - steepness)\n printfInfo(\"derivative linear: 0x%x\\n\",\n one >> (steepnessOffset.U - steepness))\n } .elsewhen (steepness === steepnessOffset.U) {\n derivative := one\n printfInfo(\"derivative linear: 0x%x\\n\", one)\n } .otherwise {\n derivative := one << (steepness - steepnessOffset.U)\n printfInfo(\"derivative linear: 0x%x\\n\",\n one << (steepness - steepnessOffset.U))\n }\n } .elsewhen (af === e_FANN_SIGMOID || af === e_FANN_SIGMOID_STEPWISE) {\n DSP(dataOut, one - dataOut, decimal + steepness - 1.U)\n derivative := dsp.d\n printfInfo(\"derivative sigmoid: 0x%x\\n\", dsp.d)\n } .elsewhen (af === e_FANN_SIGMOID_SYMMETRIC ||\n af === e_FANN_SIGMOID_SYMMETRIC_STEPWISE) {\n val steepness = io.req.bits.steepness\n DSP(dataOut, dataOut, decimal)\n when (steepness < steepnessOffset.U) {\n derivative := (one - dsp.d) >> (steepnessOffset.U - steepness)\n printfInfo(\"derivative sigmoid symmetric: 0x%x\\n\",\n (one - dsp.d) >> (steepnessOffset.U - steepness))\n } .elsewhen (steepness === steepnessOffset.U) {\n derivative := one - dsp.d\n printfInfo(\"derivative sigmoid symmetric: 0x%x\\n\",\n one - dsp.d)\n } .otherwise {\n derivative := (one - dsp.d) << (steepness - steepnessOffset.U)\n printfInfo(\"derivative sigmoid symmetric: 0x%x\\n\",\n (one - dsp.d) << (steepness - steepnessOffset.U))\n }\n }\n }\n is (PE_states('e_PE_REQUEST_EXPECTED_OUTPUT)) {\n nextState := PE_states('e_PE_COMPUTE_ERROR)\n reqWaitForResp()\n }\n is (PE_states('e_PE_COMPUTE_ERROR)) {\n val error = io.req.bits.learnReg - dataOut\n val errorSym = error >> 1.U\n // Divide by 2 should be conditional on being in a symmetric\n when (io.req.bits.activationFunction === e_FANN_SIGMOID_SYMMETRIC ||\n io.req.bits.activationFunction === e_FANN_SIGMOID_SYMMETRIC_STEPWISE) {\n errorOut := errorSym\n DSP(errorSym, errorSym, decimal)\n mse := dsp.d\n // mse := (errorSym * errorSym) >> decimal\n printfInfo(\"errorOut and Error square set to 0x%x and 0x%x\\n\",\n errorSym, dsp.d)\n } .otherwise {\n errorOut := error\n DSP(error, error, decimal)\n mse := dsp.d\n // mse := (error * error) >> decimal\n printfInfo(\"errorOut and Error square set to 0x%x and 0x%x\\n\",\n error, dsp.d)\n }\n state := PE_states('e_PE_ERROR_FUNCTION)\n }\n is (PE_states('e_PE_ERROR_FUNCTION)) {\n reqAf()\n nextState := PE_states('e_PE_COMPUTE_DELTA)\n af.io.req.bits.in := errorOut\n af.io.req.bits.afType := e_AF_DO_ERROR_FUNCTION\n errorOut := Mux(af.io.resp.valid, af.io.resp.bits.out, errorOut)\n when (af.io.resp.valid) {\n printfInfo(\"errFn(0x%x) = 0x%x\\n\", errorOut, af.io.resp.bits.out)\n }\n }\n is (PE_states('e_PE_COMPUTE_DELTA)){\n // Reset the index in preparation for doing the deltas in the\n // previous layer\n val der = Mux(derivative === 0.S, 1.S, derivative)\n index := 0.U\n\n switch(stateLearn){\n is(e_TTABLE_STATE_LEARN_FEEDFORWARD){\n DSP(der, errorOut, decimal)\n errorOut := dsp.d\n // errorOut := (der * errorOut) >> decimal\n printfInfo(\"delta (output) 0x%x * 0x%x = 0x%x\\n\",\n der, errorOut, dsp.d)\n state := PE_states('e_PE_ERROR_BACKPROP_REQUEST_WEIGHTS)\n }\n is(e_TTABLE_STATE_LEARN_ERROR_BACKPROP){\n DSP(der, io.req.bits.dw_in, decimal)\n errorOut := dsp.d\n // errorOut := (der * io.req.bits.dw_in) >> decimal\n printfInfo(\"sees errFn*derivative 0x%x\\n\", dsp.d)\n when(io.req.bits.inFirst) {\n state := PE_states('e_PE_REQUEST_INPUTS_AND_WEIGHTS)\n }.otherwise {\n state := PE_states('e_PE_ERROR_BACKPROP_REQUEST_WEIGHTS)\n }\n }\n }\n }\n is (PE_states('e_PE_ERROR_BACKPROP_REQUEST_WEIGHTS)) {\n nextState := PE_states('e_PE_ERROR_BACKPROP_DELTA_WEIGHT_MUL)\n reqWaitForResp()\n }\n is (PE_states('e_PE_ERROR_BACKPROP_DELTA_WEIGHT_MUL)) {\n // Loop over all the weights in the weight buffer, multiplying\n // these by their delta\n when (index === (io.req.bits.numWeights - 1.U) ||\n eleIndex === (elementsPerBlock - 1).U) {\n state := PE_states('e_PE_ERROR_BACKPROP_WEIGHT_WB)\n }\n DSP(errorOut, io.req.bits.wBlock(eleIndex), decimal)\n weightWB(eleIndex) := dsp.d\n // weightWB(eleIndex) := (errorOut * io.req.bits.wBlock(eleIndex)) >>\n // decimal\n printfInfo(\"d*weight (0x%x * 0x%x) >> 0x%x = 0x%x\\n\",\n errorOut, io.req.bits.wBlock(eleIndex), decimal,\n dsp.d)\n index := index + 1.U\n }\n is (PE_states('e_PE_ERROR_BACKPROP_WEIGHT_WB)) {\n when (io.req.valid) {\n when (index === io.req.bits.numWeights) {\n index := 0.U\n state := PE_states('e_PE_REQUEST_INPUTS_AND_WEIGHTS)\n io.resp.bits.resetWeightPtr := true.B\n } .otherwise {\n state := PE_states('e_PE_ERROR_BACKPROP_REQUEST_WEIGHTS)\n }\n }\n dwWritebackDone := true.B\n io.resp.valid := true.B\n }\n is (PE_states('e_PE_REQUEST_OUTPUTS_ERROR_BACKPROP)) {\n nextState := PE_states('e_PE_REQUEST_DELTA_WEIGHT_PRODUCT_ERROR_BACKPROP)\n reqWaitForResp()\n }\n is (PE_states('e_PE_REQUEST_DELTA_WEIGHT_PRODUCT_ERROR_BACKPROP)) {\n dataOut := io.req.bits.learnReg\n nextState := PE_states('e_PE_COMPUTE_DERIVATIVE)\n reqWaitForResp()\n }\n is(PE_states('e_PE_RUN_UPDATE_SLOPE)){\n // val delta = Mux(io.req.bits.inFirst, errorOut, io.req.bits.learnReg)\n val delta = errorOut\n // [TODO] This is actually an element index!\n val inLastElement = (index === (io.req.bits.numWeights - 1.U) ||\n eleIndex === (elementsPerBlock - 1).U)\n index := index + 1.U\n when (inLastElement) {\n state := PE_states('e_PE_SLOPE_WB)\n when (io.req.bits.tType === e_TTYPE_INCREMENTAL) {\n state := PE_states('e_PE_RUN_WEIGHT_UPDATE)\n // Reset any modifications that have been made to the index\n // as this will be reused during weight update\n // [TODO] #54: Does this actually work?\n index := index(index.getWidth - 1, log2Up(elementsPerBlock)) ##\n 0.U(log2Up(elementsPerBlock).W)\n }\n }\n DSP(delta, io.req.bits.iBlock(eleIndex), decimal)\n weightWB(eleIndex) := dsp.d\n printfInfo(\"update slope 0x%x * 0x%x = 0x%x\\n\",\n delta, io.req.bits.iBlock(eleIndex),\n dsp.d)\n }\n is(PE_states('e_PE_SLOPE_WB)){\n // val delta = Mux(io.req.bits.inFirst, errorOut, io.req.bits.learnReg)\n val delta = errorOut\n nextState := Mux(index === io.req.bits.numWeights,\n PE_states('e_PE_SLOPE_BIAS_WB),\n PE_states('e_PE_REQUEST_INPUTS_AND_WEIGHTS))\n reqNoResp()\n io.resp.valid := true.B\n // Setup the bias to be written back (bias is in delta!)\n dataOut := delta\n }\n is (PE_states('e_PE_SLOPE_BIAS_WB)) {\n nextState := PE_states('e_PE_UNALLOCATED)\n reqNoResp()\n io.resp.valid := true.B\n printfInfo(\"bias wb: 0x%x\\n\", dataOut)\n }\n is (PE_states('e_PE_RUN_WEIGHT_UPDATE)){\n when (index === (io.req.bits.numWeights - 1.U) ||\n eleIndex === (elementsPerBlock - 1).U) {\n state := PE_states('e_PE_WEIGHT_UPDATE_WRITE_BACK)\n }\n val weightDecay = (-io.req.bits.wBlock(eleIndex) * io.req.bits.weightDecay) >>\n decimal\n printfInfo(\"weight decay %d: -1 * 0x%x * 0x%x = 0x%x\\n\",\n eleIndex,\n io.req.bits.wBlock(eleIndex), io.req.bits.weightDecay, weightDecay)\n\n when (io.req.bits.tType === e_TTYPE_BATCH) {\n DSP(io.req.bits.iBlock(eleIndex), io.req.bits.learningRate.asSInt,\n decimal)\n weightWB(eleIndex) := dsp.d + weightDecay\n printfInfo(\"weight update %d: 0x%x * 0x%x + 0x%x = 0x%x\\n\",\n eleIndex,\n io.req.bits.iBlock(eleIndex), io.req.bits.learningRate.asSInt,\n weightDecay, dsp.d + weightDecay)\n } .otherwise {\n // [TODO] #54: we're doing incremental learning here, so the\n // source is coming from weightWB\n DSP(weightWB(eleIndex), io.req.bits.learningRate.asSInt, decimal)\n weightWB(eleIndex) := dsp.d + weightDecay\n printfInfo(\"weight update %d: 0x%x * 0x%x + 0x%x = 0x%x\\n\",\n eleIndex,\n weightWB(eleIndex), io.req.bits.learningRate, weightDecay,\n dsp.d + weightDecay)\n }\n index := index + 1.U\n }\n is (PE_states('e_PE_WEIGHT_UPDATE_WRITE_BACK)){\n when (io.req.valid) {\n printfInfo(\"weight update writeback index/numWeights 0x%x/0x%x\\n\",\n index, io.req.bits.numWeights)\n // [TODO] #54: cleanup all this mux nonsense to make it\n // readable. Also, the transition here for the bias update is\n // likely incorrect when doing incremental learning. I think we\n // need to jump into the _d0 state and make sure that the bias\n // is loaded into dw_in prior to that.\n state := PE_states('e_PE_REQUEST_INPUTS_AND_WEIGHTS)\n when (index === io.req.bits.numWeights) {\n when (io.req.bits.tType === e_TTYPE_BATCH) {\n state := PE_states('e_PE_WEIGHT_UPDATE_REQUEST_BIAS)\n } .otherwise {\n state := PE_states('e_PE_WEIGHT_UPDATE_COMPUTE_BIAS)\n }\n }\n }\n io.resp.valid := true.B\n }\n is (PE_states('e_PE_WEIGHT_UPDATE_REQUEST_BIAS)) {\n when (!reqSent) {\n io.resp.valid := true.B\n reqSent := io.req.valid\n } .elsewhen (io.req.valid) {\n reqSent := false.B\n state := PE_states('e_PE_WEIGHT_UPDATE_COMPUTE_BIAS)\n }\n }\n is (PE_states('e_PE_WEIGHT_UPDATE_COMPUTE_BIAS)) {\n state := PE_states('e_PE_WEIGHT_UPDATE_WRITE_BIAS)\n val biasSlope = Mux(io.req.bits.tType === e_TTYPE_BATCH,\n io.req.bits.dw_in, errorOut)\n DSP(biasSlope, io.req.bits.learningRate.asSInt, decimal)\n dataOut := dsp.d\n printfInfo(\"biasSlope scale 0x%x * 0x%x = 0x%x\\n\",\n biasSlope, io.req.bits.learningRate.asSInt, dsp.d)\n }\n is (PE_states('e_PE_WEIGHT_UPDATE_WRITE_BIAS)) {\n when (io.req.valid) { state := PE_states('e_PE_UNALLOCATED) }\n io.resp.valid := true.B\n }\n }\n\n // Assertions\n\n // [TODO] #54: disallow specific states for certain transaction types\n assert(!(io.req.bits.tType === e_TTYPE_INCREMENTAL &&\n (state === PE_states('e_PE_SLOPE_WB) ||\n state === PE_states('e_PE_SLOPE_BIAS_WB))),\n printfSigil ++ \"PE entered a disallowed state for incremental learning\")\n}\n", "groundtruth": " }\n is (PE_states('e_PE_ACTIVATION_FUNCTION)) {\n reqAf()\n", "crossfile_context": ""}
{"task_id": "dana", "path": "dana/src/main/scala/dana/RegisterFile.scala", "left_context": "// See LICENSE.BU for license details.\n// See LICENSE.IBM for license details.\n\npackage dana\n\nimport chisel3._\nimport chisel3.util._\nimport scala.math.pow\nimport xfiles.{TransactionTableNumEntries}\nimport cde._\n\nimport dana.abi._\n\nclass RegisterFileInterface(implicit p: Parameters) extends DanaStatusIO()(p) {\n lazy val pe = Flipped(new PERegisterFileInterface)\n val control = Flipped(new ControlRegisterFileInterface)\n val tTable = Flipped(new TTableRegisterFileInterface)\n}\n\nclass RegisterFileInterfaceLearn(implicit p: Parameters)\n extends RegisterFileInterface()(p) {\n override lazy val pe = Flipped(new PERegisterFileInterfaceLearn)\n}\n\nclass RegisterFileState(implicit p: Parameters) extends DanaBundle()(p) {\n val valid = Bool()\n val totalWrites = UInt(p(GlobalInfo).total_neurons.W)\n val countWrites = UInt(p(GlobalInfo).total_neurons.W)\n}\n\nclass RegisterFileBase[SramIf <: SRAMElementInterface](\n genSram: => Vec[SramIf])(implicit p: Parameters)\n extends DanaModule()(p) {\n lazy val io = IO(new RegisterFileInterface)\n override val printfSigil = \"dana.RegFile: \"\n val mem = genSram\n\n val state = Reg(Vec(transactionTableNumEntries * 2, new RegisterFileState))\n val stateToggle = Reg(Vec(transactionTableNumEntries, UInt(1.W)))\n val tTableRespValid = Reg(Bool())\n val tTableRespTIdx = Reg(UInt(log2Up(transactionTableNumEntries).W))\n val tTableRespAddr = Reg(UInt(log2Up(p(ScratchpadElements)).W))\n\n // Default values for SRAMs\n for (transaction <- 0 until transactionTableNumEntries) {\n for (port <- 0 until mem(transaction).numPorts) {\n mem(transaction).we(port) := false.B\n mem(transaction).re(port) := false.B\n mem(transaction).din(port) := 0.U\n mem(transaction).dinElement(port) := 0.U\n mem(transaction).addr(port) := 0.U\n }\n }\n // Default Control interface values\n io.control.req.ready := true.B\n io.control.resp.valid := false.B\n io.control.resp.bits.tIdx := 0.U\n // Default Transaction Table interface values\n io.tTable.resp.valid := false.B\n io.tTable.resp.bits.data := 0.U\n\n // Requests from the Processing Element Table\n when (io.pe.req.valid) {\n // Take action based on whether this is a write or a read\n val tIdx = io.pe.req.bits.tIdx\n val sIdx = io.pe.req.bits.tIdx ## io.pe.req.bits.location\n when (io.pe.req.bits.isWrite) { // This is a Write\n mem(tIdx).we(0) := true.B\n mem(tIdx).addr(0) := io.pe.req.bits.addr\n mem(tIdx).dinElement(0) := io.pe.req.bits.data.asUInt\n printfInfo(\"PE write element tIdx/Addr/Data 0x%x/0x%x/0x%x\\n\",\n tIdx, io.pe.req.bits.addr, io.pe.req.bits.data)\n // Increment the write count and generate a response to the\n // control module if this puts us at the write count\n when (io.pe.req.bits.incWriteCount) {\n state(sIdx).countWrites := state(sIdx).countWrites + 1.U\n printfInfo(\"write count loc/seen/expected 0x%x/0x%x/0x%x\\n\",\n sIdx, state(sIdx).countWrites + 1.U, state(sIdx).totalWrites)\n when (state(sIdx).countWrites === state(sIdx).totalWrites - 1.U) {\n io.control.resp.valid := true.B\n io.control.resp.bits.tIdx := tIdx\n }\n }\n } .otherwise { // This is a read\n mem(tIdx).re(0) := true.B\n mem(tIdx).addr(0) := io.pe.req.bits.addr\n printfInfo(\"PE read tIdx/Addr 0x%x/0x%x\\n\", tIdx,\n io.pe.req.bits.addr)\n }\n }\n\n // Requests from the Control module\n when (io.control.req.valid) {\n val tIdx = io.control.req.bits.tIdx\n val location = io.control.req.bits.location\n state(tIdx << 1.U | location).valid := true.B\n state(tIdx << 1.U | location).totalWrites :=\n io.control.req.bits.totalWrites\n state(tIdx << 1.U | location).countWrites := 0.U\n printfInfo(\"Control req tIdx/location/totalWrites 0x%x/0x%x/0x%x\\n\",\n tIdx, location, io.control.req.bits.totalWrites)\n }\n\n // Requests form the Transaction Table\n when (io.tTable.req.valid) {\n val tIdx = io.tTable.req.bits.tidIdx\n switch (io.tTable.req.bits.reqType) {\n is (e_TTABLE_REGFILE_WRITE) {\n printfInfo(\"Saw TTable write idx/Addr/Data 0x%x/0x%x/0x%x\\n\",\n tIdx, io.tTable.req.bits.addr, io.tTable.req.bits.data)\n mem(tIdx).we(0) := true.B\n mem(tIdx).dinElement(0) := io.tTable.req.bits.data\n mem(tIdx).addr(0) := io.tTable.req.bits.addr\n }\n is (e_TTABLE_REGFILE_READ) {\n printfInfo(\"Saw TTable read Addr 0x%x\\n\",\n io.tTable.req.bits.addr)\n mem(tIdx).re(0) := true.B\n mem(tIdx).dinElement(0) := io.tTable.req.bits.data\n mem(tIdx).addr(0) := io.tTable.req.bits.addr\n }\n }\n }\n\n val readReqValid_d0 = Reg(next = io.pe.req.valid && !io.pe.req.bits.isWrite)\n val peIndex_d0 = Reg(next = io.pe.req.bits.peIndex)\n val tIndex_d0 = Reg(next = io.pe.req.bits.tIdx)\n\n io.pe.resp.valid := readReqValid_d0\n io.pe.resp.bits.peIndex := peIndex_d0\n io.pe.resp.bits.data := mem(tIndex_d0).dout(0)\n when (io.pe.resp.valid) {\n printfInfo(\"PE resp PE/Data 0x%x/0x%x\\n\",\n io.pe.resp.bits.peIndex, io.pe.resp.bits.data);\n }\n // Transaction Table Response\n tTableRespValid := io.tTable.req.valid &&\n io.tTable.req.bits.reqType === e_TTABLE_REGFILE_READ\n tTableRespTIdx := io.tTable.req.bits.tidIdx\n tTableRespAddr := io.tTable.req.bits.addr\n when (tTableRespValid) {\n val memDataVec = Vec((0 until elementsPerBlock).map(i =>\n (mem(tTableRespTIdx).dout(0))(elementWidth * (i + 1) - 1, elementWidth * i)))\n io.tTable.resp.valid := true.B\n io.tTable.resp.bits.data :=\n memDataVec(tTableRespAddr(log2Up(elementsPerBlock)-1,0))\n printfInfo(\"Returning data to TTable 0x%x\\n\",\n io.tTable.resp.bits.data)\n }\n\n // Reset\n when (reset) {for (i <- 0 until transactionTableNumEntries * 2) {\n state(i).valid := false.B}}\n\n // Assertions\n\n // The number of writes that we've seen should never be greater than\n", "right_context": " \"The total writes to a Regsiter File entry exceeded the number expected\")\n\n // A request to change the total number of writes should only happen\n // to a state entry marked as valid if it's countWrites is equal to\n // the totalWrites.\n assert(!(io.control.req.valid &&\n state(io.control.req.bits.tIdx << 1.U |\n io.control.req.bits.location).valid &&\n (state(io.control.req.bits.tIdx << 1.U |\n io.control.req.bits.location).countWrites =/=\n state(io.control.req.bits.tIdx << 1.U |\n io.control.req.bits.location).totalWrites)), printfSigil ++\n \"RegFile totalWrites being changed when valid && (countWrites != totalWrites)\")\n\n // We shouldn't be trying to write data outside of the bounds of the\n // memory\n (0 until transactionTableNumEntries).map(i =>\n assert(!(mem(i).addr(0) >= p(ScratchpadElements).U), printfSigil ++\n \"RegFile address (read or write) is out of bounds\"))\n\n}\n\nclass RegisterFile(implicit p: Parameters) extends RegisterFileBase (\n Vec.fill(p(TransactionTableNumEntries))(Module(new SRAMElement(\n dataWidth = p(BitsPerBlock),\n sramDepth = pow(2, log2Up(p(RegFileNumBlocks))).toInt,\n numPorts = 1,\n elementWidth = p(DanaDataBits))).io))(p)\n\nclass RegisterFileLearn(implicit p: Parameters) extends RegisterFileBase (\n Vec.fill(p(TransactionTableNumEntries))(Module(new SRAMElementIncrement(\n dataWidth = p(BitsPerBlock),\n sramDepth = pow(2, log2Up(p(RegFileNumBlocks))).toInt,\n numPorts = 1,\n elementWidth = p(DanaDataBits))).io))(p) {\n override lazy val io = IO(new RegisterFileInterfaceLearn)\n\n val readReqType_d0 = Reg(next = io.pe.req.bits.reqType)\n io.pe.resp.bits.reqType := readReqType_d0\n\n for (transaction <- 0 until transactionTableNumEntries) {\n for (port <- 0 until mem(transaction).numPorts) {\n mem(transaction).wType(port) := 0.U\n }\n }\n\n when (io.pe.req.valid) {\n // Take action based on whether this is a write or a read\n val tIdx = io.pe.req.bits.tIdx\n val sIdx = io.pe.req.bits.tIdx ## io.pe.req.bits.location\n when (io.pe.req.bits.isWrite) { // This is a Write\n mem(tIdx).addr(0) := io.pe.req.bits.addr\n switch (io.pe.req.bits.reqType) {\n is (e_PE_WRITE_ELEMENT) {\n mem(tIdx).wType(0) := 0.U\n mem(tIdx).dinElement(0) := io.pe.req.bits.data.asUInt\n printfInfo(\"PE write element tIdx/Addr/Data 0x%x/0x%x/0x%x\\n\",\n tIdx, io.pe.req.bits.addr, io.pe.req.bits.data)\n }\n is (e_PE_WRITE_BLOCK_NEW) {\n mem(tIdx).wType(0) := 1.U\n mem(tIdx).din(0) := io.pe.req.bits.dataBlock\n printfInfo(\"PE write block new tIdx/Addr/Data 0x%x/0x%x/0x%x\\n\",\n tIdx, io.pe.req.bits.addr, io.pe.req.bits.dataBlock)\n }\n is (e_PE_WRITE_BLOCK_ACC) {\n mem(tIdx).wType(0) := 2.U\n mem(tIdx).din(0) := io.pe.req.bits.dataBlock\n printfInfo(\"PE write block inc tIdx/Addr/Data 0x%x/0x%x/0x%x\\n\",\n tIdx, io.pe.req.bits.addr, io.pe.req.bits.dataBlock)\n }\n // Kludge to kill the write _if_ we're just incrementing the\n // write count\n is (e_PE_INCREMENT_WRITE_COUNT) {\n printfInfo(\"PE increment write count\\n\")\n mem(tIdx).we(0) := false.B\n }\n }\n }\n }\n}\n", "groundtruth": " // the number of expected writes.\n assert(!Vec((0 until transactionTableNumEntries * 2).map(\n i => (state(i).valid &&\n", "crossfile_context": ""}
{"task_id": "dana", "path": "dana/src/main/scala/dana/util/Util.scala", "left_context": "// See LICENSE.IBM for license details.\n\npackage dana.util\n\nimport chisel3._\n\nobject divUp {\n def apply(dividend: Int, divisor: Int): Int = {\n (dividend + divisor - 1) / divisor}\n}\n\nobject packInfo {\n", "right_context": "", "groundtruth": " def apply(epb: Int, pes: Int, cache: Int): Int = {\n var x = epb << (6 + 4);\n x = x | pes << 4;\n x = x | cache;\n x}\n", "crossfile_context": ""}
{"task_id": "dana", "path": "dana/src/main/scala/standalone/XFilesTests.scala", "left_context": "// See LICENSE.IBM for license details.\n\npackage xfiles.standalone\n\nimport chisel3._\nimport chisel3.util._\nimport cde._\nimport xfiles.XFilesUserRequests\n\n", "right_context": "", "groundtruth": "abstract class XFilesTests(implicit p: Parameters) extends XFilesTester {\n // New Transaction\n\n\n", "crossfile_context": ""}
{"task_id": "dana", "path": "dana/src/main/scala/util/QueueAf.scala", "left_context": "// See LICENSE.BU for license details.\n\npackage xfiles\n\nimport chisel3._\nimport chisel3.util._\n\nclass QueueIOAf[T <: Data](gen: T, entries: Int) extends QueueIO[T](gen, entries) {\n val almostFull = Output(Bool())\n", "right_context": "}\n\nclass QueueAf[T <: Data](gen: T, entries: Int, almostFullEntries: Int,\n pipe: Boolean = false, flow: Boolean = false,\n override_reset: Option[Bool] = None)\n extends Module(override_reset = override_reset) {\n\n val io = IO(new QueueIOAf(gen, entries))\n val queue = Module(new Queue(gen, entries, pipe, flow, override_reset))\n\n io.enq <> queue.io.enq\n io.deq <> queue.io.deq\n io.count := queue.io.count\n io.almostFull := queue.io.count >= almostFullEntries.U\n}\n", "groundtruth": " override def cloneType = new QueueIOAf(gen, entries).asInstanceOf[this.type]\n", "crossfile_context": ""}
{"task_id": "dana", "path": "dana/src/main/scala/util/SRAM.scala", "left_context": "// See LICENSE.BU for license details.\n// See LICENSE.IBM for license details.\n\npackage dana\n\nimport chisel3._\nimport chisel3.util._\n\nclass SRAMInterface(\n val dataWidth: Int,\n val numReadPorts: Int,\n val numWritePorts: Int,\n val numReadWritePorts: Int,\n val sramDepth: Int\n) extends Bundle {\n override def cloneType = new SRAMInterface(\n dataWidth = dataWidth,\n numReadPorts = numReadPorts,\n numWritePorts = numWritePorts,\n numReadWritePorts = numReadWritePorts,\n sramDepth = sramDepth\n ).asInstanceOf[this.type]\n // Data Input\n val din = Input(Vec(numReadWritePorts, UInt(dataWidth.W)))\n val dinW = Input(Vec(numWritePorts, UInt(dataWidth.W)))\n // Data Output\n val dout = Output(Vec(numReadWritePorts, UInt(dataWidth.W)))\n val doutR = Output(Vec(numReadPorts, UInt(dataWidth.W)))\n // Addresses\n val addr = Input(Vec(numReadWritePorts, UInt(log2Up(sramDepth).W)))\n val addrR = Input(Vec(numReadPorts, UInt(log2Up(sramDepth).W)))\n val addrW = Input(Vec(numWritePorts, UInt(log2Up(sramDepth).W)))\n // Write enable\n val we = Input(Vec(numReadWritePorts, Bool()))\n val weW = Input(Vec(numWritePorts, Bool()))\n // Read enable\n val re = Input(Vec(numReadWritePorts, Bool()))\n val reR = Input(Vec(numReadPorts, Bool()))\n}\n\nclass SRAM (\n val id: Int = 0,\n val dataWidth: Int = 8,\n val sramDepth: Int = 64,\n val numReadPorts: Int = 0,\n val numWritePorts: Int = 0,\n val numReadWritePorts: Int = 2,\n val initSwitch: Int = -1,\n val elementsPerBlock: Int = -1\n) extends Module {\n val io = IO(new SRAMInterface(\n numReadPorts = numReadPorts,\n numWritePorts = numWritePorts,\n numReadWritePorts = numReadWritePorts,\n dataWidth = dataWidth,\n sramDepth = sramDepth))\n\n val mem = SeqMem(sramDepth, UInt(dataWidth.W))\n\n for (i <- 0 until numReadWritePorts) {\n", "right_context": " when (io.re(i)) { io.dout(i) := mem(io.addr(i)) }}\n\n for (i <- 0 until numReadPorts) {\n when (io.reR(i)) { io.doutR(i) := mem(io.addrR(i)) }}\n\n for (i <- 0 until numWritePorts) {\n when (io.weW(i)) { mem(io.addrW(i)) := io.dinW(i) }}\n}\n\nclass SRAMSinglePortInterface(\n val dataWidth: Int,\n val sramDepth: Int\n) extends Bundle {\n override def cloneType = new SRAMDualPortInterface(\n dataWidth = dataWidth,\n sramDepth = sramDepth).asInstanceOf[this.type]\n val we = Output(Bool())\n val din = Output(UInt(dataWidth.W))\n val addr = Output(UInt(log2Up(sramDepth).W))\n val dout = Input(UInt(dataWidth.W))\n}\n\nclass SRAMDualPortInterface(\n val dataWidth: Int,\n val sramDepth: Int\n) extends Bundle {\n override def cloneType = new SRAMDualPortInterface(\n dataWidth = dataWidth,\n sramDepth = sramDepth).asInstanceOf[this.type]\n val we = Output(Vec(2, Bool()))\n val din = Output(Vec(2, UInt(dataWidth.W)))\n val addr = Output(Vec(2, UInt(log2Up(sramDepth).W)))\n val dout = Input(Vec(2, UInt(dataWidth.W)))\n}\n\nclass SRAMDualPort(\n val dataWidth: Int,\n val sramDepth: Int\n) extends Module {\n val io = Flipped(new SRAMDualPortInterface(\n dataWidth = dataWidth,\n sramDepth = sramDepth))\n val sram = Module(new SRAM(\n dataWidth = dataWidth,\n numReadPorts = 0,\n numWritePorts = 0,\n numReadWritePorts = 2,\n initSwitch = -1,\n elementsPerBlock = -1,\n sramDepth = sramDepth)).io\n\n for (i <- 0 until 2) {\n sram.we(i) := io.we(i)\n sram.din(i) := io.din(i)\n sram.addr(i) := io.addr(i)\n io.dout(i) := sram.dout(i)\n }\n}\n", "groundtruth": " when (io.we(i)) { mem(io.addr(i)) := io.din(i) }\n", "crossfile_context": ""}
{"task_id": "dana", "path": "dana/src/main/scala/util/SRAMBlockIncrement.scala", "left_context": "// See LICENSE.BU for license details.\n// See LICENSE.IBM for license details.\n\npackage dana\n\nimport chisel3._\nimport chisel3.util._\n\n// SRAMBlock variant that allows for element _and_ block writes with\n// the option of writing a block that is accumualted with the elements\n// of the existing block. Forwarding is allowable for all cases.\n\n// This uses both write enable (we) and write type (wType) input\n// lines. The write type is defined as follows:\n// 0: element write (like SRAMBlock0\n// 1: block write overwriting old block\n// 2: block write accumulating element-wise with old block\n\nclass SRAMBlockIncrementInterface (\n override val dataWidth: Int,\n override val sramDepth: Int,\n override val numPorts: Int,\n val elementWidth: Int\n) extends SRAMVariantInterface(dataWidth, sramDepth, numPorts) {\n override def cloneType = new SRAMBlockIncrementInterface(\n dataWidth = dataWidth,\n sramDepth = sramDepth,\n numPorts = numPorts,\n elementWidth = elementWidth).asInstanceOf[this.type]\n val inc = Input(Vec(numPorts, Bool()))\n}\n\nclass WritePendingBlockIncrementBundle (\n val elementWidth: Int,\n val dataWidth: Int,\n val sramDepth: Int\n) extends Bundle {\n override def cloneType = new WritePendingBlockIncrementBundle (\n elementWidth = elementWidth,\n dataWidth = dataWidth,\n sramDepth = sramDepth).asInstanceOf[this.type]\n val valid = Bool()\n val inc = Bool()\n val data = UInt(dataWidth.W)\n val addr = UInt(log2Up(sramDepth).W)\n}\n\n// A special instance of the generic SRAM that allows for masked\n// writes to the SRAM. Reads happen normally, but writes happen using\n// a 2-cyle read-modify-write operation. Due to the nature of this\n// operation, each write port needs an associated read port.\n// Consequently, this only has RW ports.\nclass SRAMBlockIncrement (\n override val id: Int = 0,\n override val dataWidth: Int = 32,\n override val sramDepth: Int = 64,\n override val numPorts: Int = 1,\n val elementWidth: Int = 8\n) extends SRAMVariant(id, dataWidth, sramDepth, numPorts) {\n override lazy val io = IO(new SRAMBlockIncrementInterface(\n dataWidth = dataWidth,\n sramDepth = sramDepth,\n numPorts = numPorts,\n elementWidth = elementWidth))\n\n val elementsPerBlock = divUp(dataWidth, elementWidth)\n\n", "right_context": " def writeBlock(a: Vec[UInt], b: UInt) {\n val bTupled = (((x: Int, y: Int) => b.apply(x, y)) tupled)\n (0 until elementsPerBlock).map(j => a(j) := bTupled(index(j))) }\n def writeBlockIncrement(a: Vec[UInt], b: UInt, c: UInt) {\n val bTupled = (((x: Int, y: Int) => b.apply(x, y)) tupled)\n val cTupled = (((x: Int, y: Int) => c.apply(x, y)) tupled)\n (0 until elementsPerBlock).map(j => a(j) :=\n bTupled(index(j)) + cTupled(index(j))) }\n\n val writePending = Reg(Vec(numPorts, new WritePendingBlockIncrementBundle(\n elementWidth = elementWidth,\n dataWidth = dataWidth,\n sramDepth = sramDepth)))\n\n val tmp0 = Wire(Vec(numPorts, Vec(elementsPerBlock, UInt(elementWidth.W))))\n val tmp1 = Wire(Vec(numPorts, Vec(elementsPerBlock, UInt(elementWidth.W))))\n val forwarding = Wire(Vec(numPorts, Bool()))\n\n // Combinational Logic\n for (i <- 0 until numPorts) {\n val fwd = (io.we(i) && writePending(i).valid &&\n io.addr(i) === writePending(i).addr)\n\n // Connections to the sram\n sram.weW(i) := writePending(i).valid\n sram.dinW(i) := tmp1(i).asUInt\n sram.addrW(i) := writePending(i).addr\n sram.addrR(i) := io.addr(i)\n sram.reR(i) := io.re(i) || (io.we(i) && !fwd)\n io.dout(i) := sram.doutR(i)\n\n // Defaults\n val doutRTupled = (((x: Int, y: Int) => sram.doutR(i)(x, y)) tupled)\n (0 until elementsPerBlock).map(j => tmp0(i)(j) := doutRTupled(index(j)))\n tmp1(i) := tmp0(i)\n forwarding(i) := fwd\n\n // Handle a pending write if one exists\n when (writePending(i).valid) {\n when (!writePending(i).inc) {\n writeBlock(tmp0(i), writePending(i).data)\n } .otherwise {\n writeBlockIncrement(tmp0(i), writePending(i).data, sram.doutR(i)) }\n\n // Deal with forwarding\n when (forwarding(i)) {\n when (!io.inc(i)) {\n writeBlock(tmp0(i), io.din(i))\n } .otherwise {\n writeBlockIncrement(tmp1(i), tmp0(i).asUInt, io.din(i)) }}\n\n printf(\"[INFO] SramBloInc: WRITE port/inc?/fwd?/fwdInc? 0x%x/0x%x/0x%x/0x%x\\n\",\n i.U, writePending(i).inc, forwarding(i), io.inc(i))\n printf(\"[INFO] DATA addr/dataOld/dataNew 0x%x/0x%x/0x%x\\n\",\n writePending(i).addr, sram.doutR(i), tmp1(i).asUInt) }}\n\n // Sequential Logic\n for (i <- 0 until numPorts) {\n // Assign the pending write data\n writePending(i).valid := false.B\n when ((io.we(i)) && (forwarding(i) === false.B)) {\n writePending(i).valid := true.B\n writePending(i).inc := io.inc(i)\n writePending(i).data := io.din(i)\n writePending(i).addr := io.addr(i) }}\n}\n", "groundtruth": " def index(j: Int): (Int, Int) = (elementWidth*(j+1) - 1, elementWidth * j)\n", "crossfile_context": ""}
{"task_id": "dana", "path": "dana/src/main/scala/util/SRAMElementCounter.scala", "left_context": "// See LICENSE.BU for license details.\n// See LICENSE.IBM for license details.\n\npackage dana\n\nimport chisel3._\nimport chisel3.util._\n\n// [TODO] This module is currently non-working. It was an initial\n// solution to the problem of dealing with random writes from the\n// Processing Elements and needing to maintain a record of which\n// entries were valid. Knowledge of valid entries is necessary to\n// ensure that subsequent PE reads are only reading valid data. This\n// approach introduces metadata into each SRAM block that contains the\n// number of valid entries in that block.\n\nclass SRAMElementCounterResp (\n val sramDepth: Int\n) extends Bundle {\n", "right_context": "}\n\nclass SRAMElementCounterInterface (\n val dataWidth: Int,\n val sramDepth: Int,\n val numPorts: Int,\n val elementWidth: Int\n) extends Bundle {\n override def cloneType = new SRAMElementInterface(\n dataWidth = dataWidth,\n sramDepth = sramDepth,\n numPorts = numPorts,\n elementWidth = elementWidth).asInstanceOf[this.type]\n val we = Output(Vec(numPorts, Bool()))\n val din = Output(Vec(numPorts, UInt(elementWidth.W)))\n val addr = Output(Vec(numPorts, UInt(log2Up(sramDepth * dataWidth / elementWidth).W)))\n val dout = Input(Vec(numPorts, UInt(dataWidth.W)))\n // lastBlock sets which is the last block in the SRAM\n val lastBlock = Input(Vec(numPorts, UInt(log2Up(sramDepth).W)))\n // lastCount sets the number of elements in the last block\n val lastCount = Input(Vec(numPorts, UInt((log2Up(dataWidth / elementWidth) + 1).W)))\n val resp = Vec(numPorts, Decoupled(new SRAMElementCounterResp (\n sramDepth = sramDepth)) )\n}\n\n\n// write (i.e., SRAMElement), but also includes a count of the number\n// of valid elements in each block. When a block is determined to be\n// completely valid, this module generates an output update signal\n// indicating which block is now valid.\nclass SRAMElementCounter (\n val dataWidth: Int = 32,\n val sramDepth: Int = 64,\n val elementWidth: Int = 8,\n val numPorts: Int = 1\n) extends Module {\n val io = IO(Flipped(new SRAMElementCounterInterface(\n dataWidth = dataWidth,\n sramDepth = sramDepth,\n numPorts = numPorts,\n elementWidth = elementWidth\n )))\n val sram = Module(new SRAM(\n dataWidth = dataWidth + log2Up(dataWidth / elementWidth) + 1,\n sramDepth = sramDepth,\n numReadPorts = numPorts,\n numWritePorts = numPorts,\n numReadWritePorts = 0\n ))\n\n val addr = Vec(numPorts, new Bundle{\n val addrHi = UInt(log2Up(sramDepth).W)\n val addrLo = UInt(log2Up(dataWidth / elementWidth).W)})\n\n val writePending = Reg(Vec(numPorts, new WritePendingBundle(\n elementWidth = elementWidth,\n dataWidth = dataWidth,\n sramDepth = sramDepth)))\n\n val tmp = Vec(numPorts, Vec(dataWidth/elementWidth, UInt(elementWidth.W)))\n val count = Vec(numPorts, UInt((log2Up(dataWidth / elementWidth) + 1).W))\n val forwarding = Vec(numPorts, Bool())\n\n // Combinational Logic\n for (i <- 0 until numPorts) {\n // Assign the addresses\n addr(i).addrHi := io.addr(i)(\n log2Up(sramDepth * dataWidth / elementWidth) - 1,\n log2Up(dataWidth / elementWidth))\n addr(i).addrLo := io.addr(i)(\n log2Up(dataWidth / elementWidth) - 1, 0)\n // Connections to the sram\n sram.io.weW(i) := writePending(i).valid\n // Explicit data and count assignments\n sram.io.dinW(i) := 0.U\n sram.io.dinW(i)(sramDepth - 1, 0) := tmp(i)\n sram.io.dinW(i)(sramDepth + log2Up(dataWidth/elementWidth) + 1 - 1) :=\n count(i) + 1.U + forwarding(i)\n sram.io.addrR(i) := addr(i).addrHi\n io.dout(i) := sram.io.doutR(i)(dataWidth - 1, 0)\n // Defaults\n io.resp(i).valid := false.B\n io.resp(i).bits.index := 0.U\n forwarding(i) := false.B\n tmp(i) := sram.io.doutR(i)(dataWidth - 1, 0)\n count(i) := sram.io.doutR(i)(\n dataWidth + log2Up(dataWidth/elementWidth) + 1 - 1, dataWidth)\n sram.io.addrW(i) := writePending(i).addrHi\n when (writePending(i).valid) {\n for (j <- 0 until dataWidth / elementWidth) {\n when (j.U === writePending(i).addrLo) {\n tmp(i)(j) := writePending(i).data\n } .elsewhen(addr(i).addrHi === writePending(i).addrHi &&\n io.we(i) &&\n j.U === addr(i).addrLo) {\n tmp(i)(j) := io.din(i)\n forwarding(i) := true.B\n } .otherwise {\n tmp(i)(j) := sram.io.doutR(i)((j+1) * elementWidth - 1, j * elementWidth)\n }\n }\n // Generate a response if we've filled up an entry. An entry is\n // full if it's count is equal to the number of elementsPerBlock\n // or if it's the last count in the last block (this covers the\n // case of a partially filled last block).\n when (count(i) + 1.U + forwarding(i) === (dataWidth / elementWidth).U ||\n (count(i) + 1.U + forwarding(i) === io.lastCount(i) &&\n writePending(i).addrHi === io.lastBlock(i))) {\n io.resp(i).valid := true.B\n io.resp(i).bits.index := writePending(i).addrHi\n sram.io.dinW(i)(sramDepth + log2Up(dataWidth/elementWidth) + 1 - 1) := 0.U\n }\n }\n }\n\n // Sequential Logic\n for (i <- 0 until numPorts) {\n // Assign the pending write data\n writePending(i).valid := false.B\n when ((io.we(i)) && (forwarding(i) === false.B)) {\n writePending(i).valid := true.B\n writePending(i).data := io.din(i)\n writePending(i).addrHi := addr(i).addrHi\n writePending(i).addrLo := addr(i).addrLo\n }\n }\n\n // Assertions\n assert(isPow2(dataWidth / elementWidth),\n \"dataWidth/elementWidth must be a power of 2\")\n}\n", "groundtruth": " override def cloneType = new SRAMElementCounterResp (\n sramDepth = sramDepth).asInstanceOf[this.type]\n", "crossfile_context": ""}
{"task_id": "dana", "path": "dana/src/main/scala/util/SRAMElementIncrement.scala", "left_context": "// See LICENSE.BU for license details.\n// See LICENSE.IBM for license details.\n\npackage dana\n\nimport chisel3._\nimport chisel3.util._\n\n// SRAMElement variant that allows for element _and_ block writes with\n// the option of writing a block that is accumualted with the elements\n// of the existing block. Forwarding is allowable for all cases.\n\n// This uses both write enable (we) and write type (wType) input\n// lines. The write type is defined as follows:\n// 0: element write (like SRAMElement0\n// 1: block write overwriting old block\n// 2: block write accumulating element-wise with old block\n\nclass SRAMElementIncrementInterface (\n override val dataWidth: Int,\n override val sramDepth: Int,\n override val numPorts: Int,\n override val elementWidth: Int\n) extends SRAMElementInterface(dataWidth, sramDepth, numPorts, elementWidth) {\n override def cloneType = new SRAMElementIncrementInterface(\n dataWidth = dataWidth,\n sramDepth = sramDepth,\n numPorts = numPorts,\n elementWidth = elementWidth).asInstanceOf[this.type]\n val wType = Input(Vec(numPorts, UInt(log2Up(3).W)))\n}\n\nclass WritePendingIncrementBundle (\n val elementWidth: Int,\n val dataWidth: Int,\n val sramDepth: Int\n) extends Bundle {\n override def cloneType = new WritePendingIncrementBundle (\n elementWidth = elementWidth,\n dataWidth = dataWidth,\n sramDepth = sramDepth).asInstanceOf[this.type]\n val valid = Bool()\n val wType = UInt(log2Up(3).W)\n val dataElement = UInt(elementWidth.W)\n val dataBlock = UInt(dataWidth.W)\n val addrHi = UInt(log2Up(sramDepth).W)\n val addrLo = UInt(log2Up(dataWidth / elementWidth).W)\n}\n\n// A special instance of the generic SRAM that allows for masked\n// writes to the SRAM. Reads happen normally, but writes happen using\n// a 2-cyle read-modify-write operation. Due to the nature of this\n// operation, each write port needs an associated read port.\n// Consequently, this only has RW ports.\nclass SRAMElementIncrement (\n override val id: Int = 0,\n override val dataWidth: Int = 32,\n override val sramDepth: Int = 64,\n override val numPorts: Int = 1,\n val elementWidth: Int = 8\n) extends SRAMVariant(id, dataWidth, sramDepth, numPorts) {\n override lazy val io = IO(new SRAMElementIncrementInterface(\n dataWidth = dataWidth,\n sramDepth = sramDepth,\n numPorts = numPorts,\n elementWidth = elementWidth\n ))\n\n val elementsPerBlock = divUp(dataWidth, elementWidth)\n\n", "right_context": " def writeBlock(a: Vec[UInt], b: UInt) {\n val bTupled = (((x: Int, y: Int) => b.apply(x, y)) tupled)\n (0 until elementsPerBlock).map(j => a(j) := bTupled(index(j))) }\n def writeBlockIncrement(a: Vec[UInt], b: UInt, c: UInt) {\n val bTupled = (((x: Int, y: Int) => b.apply(x, y)) tupled)\n val cTupled = (((x: Int, y: Int) => c.apply(x, y)) tupled)\n (0 until elementsPerBlock).map(j => a(j) :=\n bTupled(index(j)) + cTupled(index(j))) }\n\n class AddrBundle(\n val sramDepth: Int,\n val elementsPerBlock: Int\n ) extends Bundle {\n val addrHi = UInt(log2Up(sramDepth).W)\n val addrLo = UInt(log2Up(elementsPerBlock).W)\n override def cloneType = new AddrBundle(\n sramDepth = sramDepth,\n elementsPerBlock = elementsPerBlock).asInstanceOf[this.type]\n }\n\n val addr = Wire(Vec(numPorts, new AddrBundle(sramDepth,elementsPerBlock)))\n\n val writePending = Reg(Vec(numPorts, new WritePendingIncrementBundle(\n elementWidth = elementWidth,\n dataWidth = dataWidth,\n sramDepth = sramDepth)))\n\n val tmp0 = Wire(Vec(numPorts,Vec(elementsPerBlock,UInt(elementWidth.W))))\n val tmp1 = Wire(Vec(numPorts,Vec(elementsPerBlock,UInt(elementWidth.W))))\n val forwarding = Wire(Vec(numPorts, Bool()))\n\n // Combinational Logic\n for (i <- 0 until numPorts) {\n // Assign the addresses: addrHi->block address, addrLo->element address\n addr(i).addrHi := io.addr(i)(\n log2Up(sramDepth * elementsPerBlock) - 1, log2Up(elementsPerBlock))\n addr(i).addrLo := io.addr(i)(log2Up(elementsPerBlock) - 1, 0)\n\n val fwd = (io.we(i) && writePending(i).valid &&\n addr(i).addrHi === writePending(i).addrHi)\n\n // Connections to the sram\n sram.weW(i) := writePending(i).valid\n sram.reR(i) := io.re(i) || (io.we(i) && !fwd)\n sram.dinW(i) := tmp1(i).asUInt\n sram.addrW(i) := writePending(i).addrHi\n sram.addrR(i) := addr(i).addrHi\n io.dout(i) := sram.doutR(i)\n\n // Defaults\n val doutRTupled = (((x: Int, y: Int) => sram.doutR(i)(x, y)) tupled)\n (0 until elementsPerBlock).map(j => tmp0(i)(j) := doutRTupled(index(j)))\n tmp1(i) := tmp0(i)\n forwarding(i) := fwd\n\n // Deal with a pending write if one exists\n when (writePending(i).valid) {\n // Write pending data to tmp0\n switch (writePending(i).wType) {\n is (0.U) {\n writeElement(tmp0(i), writePending(i).addrLo, writePending(i).dataElement) }\n is (1.U) {\n writeBlock(tmp0(i), writePending(i).dataBlock) }\n is (2.U) {\n writeBlockIncrement(tmp0(i), sram.doutR(i), writePending(i).dataBlock) }}\n\n // Handle forwarding by updating tmp1\n when (forwarding(i)) {\n switch (io.wType(i)) {\n is (0.U) {\n writeElement(tmp1(i), addr(i).addrLo, io.dinElement(i)) }\n is (1.U) {\n writeBlock(tmp1(i), io.din(i)) }\n is (2.U) {\n writeBlockIncrement(tmp1(i), tmp0(i).asUInt, io.din(i)) }}}\n\n printf(\"[INFO] SramEleInc: WRITE port/type/fwd?/fwdType 0x%x/0x%x/0x%x/0x%x\\n\",\n i.U, writePending(i).wType, forwarding(i), io.wType(i))\n printf(\"[INFO] DATA addr/dataOld/dataNew 0x%x/0x%x/0x%x\\n\",\n writePending(i).addrHi##writePending(i).addrLo, sram.doutR(i),\n tmp1(i).asUInt)\n }\n }\n\n // Sequential Logic\n for (i <- 0 until numPorts) {\n // Assign the pending write data\n writePending(i).valid := false.B\n when ((io.we(i)) && (forwarding(i) === false.B)) {\n writePending(i).valid := true.B\n writePending(i).wType := io.wType(i)\n writePending(i).dataElement := io.dinElement(i)\n writePending(i).dataBlock := io.din(i)\n writePending(i).addrHi := addr(i).addrHi\n writePending(i).addrLo := addr(i).addrLo\n }\n }\n\n // Assertions\n\n // We only define write types up through 2\n assert(!Vec((0 until numPorts).map(i =>\n io.we(i) && io.wType(i) > 2.U)).contains(true.B),\n \"SRAMElementIncrement saw unsupported wType > 2\")\n}\n", "groundtruth": " def index(j: Int): (Int, Int) = (elementWidth*(j+1) - 1, elementWidth * j)\n", "crossfile_context": ""}
{"task_id": "riscv-mini-five-stage", "path": "riscv-mini-five-stage/src/main/scala/riscv_mini_five_stage/IF_ID_Register.scala", "left_context": "/*\n* Filename : IF_ID_Register.scala\n* Date : 02-01-2019\n* Author : SunnyChen\n*\n* Pipeline register between IF stage and ID stage\n* */\n\npackage riscv_mini_five_stage\n\nimport chisel3._\n\nclass IF_ID_Registerio extends Bundle with Config {\n val if_pc = Input(UInt(WLEN.W))\n val if_inst = Input(UInt(WLEN.W))\n val if_id_write = Input(UInt(IF_ID_WRITE_SIG_LEN.W))\n val if_flush = Input(UInt(IF_ID_FLUSH_SIG_LEN.W))\n val if_pc_4 = Input(UInt(WLEN.W))\n val id_rs1 = Output(UInt(REG_LEN.W))\n val id_rs2 = Output(UInt(REG_LEN.W))\n", "right_context": "}\n\nclass IF_ID_Register extends Module with Config {\n val io = IO(new IF_ID_Registerio)\n\n val pc_reg = RegInit(0.U(WLEN.W))\n val inst_reg = RegInit(0.U(WLEN.W))\n val pc_4_reg = RegInit(0.U(WLEN.W))\n\n pc_reg := Mux(io.if_flush.toBool(), 0.U(WLEN.W),\n Mux(io.if_id_write.toBool(), io.if_pc, pc_reg))\n\n inst_reg := Mux(io.if_flush.toBool(), 0.U(WLEN.W),\n Mux(io.if_id_write.toBool(), io.if_inst, inst_reg))\n\n pc_4_reg := Mux(io.if_flush.toBool(), 0.U(WLEN.W),\n Mux(io.if_id_write.toBool(), io.if_pc_4, pc_4_reg))\n\n io.id_pc := pc_reg\n io.id_pc_4 := pc_4_reg\n io.id_inst := inst_reg\n io.id_rs1 := inst_reg(19,15)\n io.id_rs2 := inst_reg(24,20)\n}\n\nobject IF_ID_Register extends App {\n chisel3.Driver.execute(args, () => new IF_ID_Register)\n}\n", "groundtruth": " val id_pc = Output(UInt(WLEN.W))\n val id_pc_4 = Output(UInt(WLEN.W))\n", "crossfile_context": ""}
{"task_id": "riscv-mini-five-stage", "path": "riscv-mini-five-stage/src/main/scala/riscv_mini_five_stage/InstCache.scala", "left_context": "/*\n* Filename : InstCache.scala\n* Date : 02-01-2019\n* Author : SunnyChen\n*\n* Instruction cache for my processor, I treat it as a combinational logic\n* 02-01-2019 - test cache, 128B, 32 Words, implemented use Mem\n* 17-01-2019 - test cache, 256B, 64 Words, implemented use Mem\n* */\n\npackage riscv_mini_five_stage\n\nimport chisel3._\nimport chisel3.util.Cat\nimport chisel3.util.experimental.loadMemoryFromFile\n\nclass InstCacheio extends Bundle with Config {\n val addr = Input(UInt(WLEN.W))\n val inst = Output(UInt(WLEN.W))\n}\n\n/*\n* Instruction cache is a ROM\n* This is just a test cache which has a very small size ROM\n* */\nclass InstCache extends Module with Config {\n val io = IO(new InstCacheio)\n\n // INST_CACHE_LEN Byte and INST_CACHE_LEN / 4 Words\n val cache = Mem(INST_CACHE_LEN, UInt(BLEN.W))\n\n // Instructions details in \"instructions_test.exe\"\n loadMemoryFromFile(cache, \"initmem/instcache.txt\")\n\n io.inst := Cat(cache(io.addr), cache(io.addr + 1.U), cache(io.addr + 2.U), cache(io.addr + 3.U))\n}\n\n", "right_context": "", "groundtruth": "object InstCache extends App {\n chisel3.Driver.execute(args, () => new InstCache)\n}\n", "crossfile_context": ""}
{"task_id": "riscv-mini-five-stage", "path": "riscv-mini-five-stage/src/main/scala/riscv_mini_five_stage/PC.scala", "left_context": "/*\n* Filename : PC.scala\n* Date : 02-01-2019\n* Author : SunnyChen\n*\n* Program Counter for my processor\n* */\n\npackage riscv_mini_five_stage\n\nimport chisel3._\n\nclass PCio extends Bundle with Config {\n val addr_input = Input(UInt(WLEN.W))\n val pc_write = Input(UInt(PC_WRITE_SIG_LEN.W))\n val pc_out = Output(UInt(WLEN.W))\n}\n\nabstract class PC_template extends Module with Config {\n val io = IO(new PCio)\n}\n\nclass PC extends PC_template {\n val PC_reg = RegInit(0.U(WLEN.W))\n\n PC_reg := Mux(io.pc_write.toBool(), io.addr_input, PC_reg)\n io.pc_out := PC_reg\n}\n\n", "right_context": "", "groundtruth": "object PC extends App {\n chisel3.Driver.execute(args, () => new PC)\n}\n", "crossfile_context": ""}
{"task_id": "riscv-mini-five-stage", "path": "riscv-mini-five-stage/src/test/scala/riscv_mini_five_stage_test/ALU_Test.scala", "left_context": "package riscv_mini_five_stage\n\nimport chisel3._\nimport chisel3.iotesters\nimport chisel3.iotesters.PeekPokeTester\nimport chisel3.util\nimport org.scalatest.{FlatSpec, Matchers}\n\nclass ALU_Test(c: ALU) extends PeekPokeTester(c) {\n var src_a = 10\n var src_b = 20\n var aluop = 0\n\n for(i <- 0 to 3) {\n poke(c.io.Src_A, src_a)\n poke(c.io.Src_B, src_b)\n poke(c.io.ALUOp, aluop)\n peek(c.io.Sum)\n peek(c.io.Conflag)\n step(1)\n aluop = aluop + 1\n }\n}\n\nclass ALU_Spce extends FlatSpec with Matchers {\n iotesters.Driver.execute((Array(\"--backend-name\", \"verilator\")), () => new ALU) {\n c => new ALU_Test(c)\n }\n\n", "right_context": "", "groundtruth": " iotesters.Driver.execute((Array(\"--is-verbose\")), () => new ALU) {\n c => new ALU_Test(c)\n }\n", "crossfile_context": ""}
{"task_id": "riscv-mini-five-stage", "path": "riscv-mini-five-stage/src/test/scala/riscv_mini_five_stage_test/Addr_Buffer_Test.scala", "left_context": "package riscv_mini_five_stage\n\nimport chisel3._\nimport chisel3.util._\nimport chisel3.iotesters._\nimport org.scalatest.{FlatSpec, Matchers}\n\nclass Addr_Buffer_Test(c: Addr_Buffer) extends PeekPokeTester(c) {\n var addr = 10\n var record = 1\n for(i <- 1 to 20) {\n if((i > 3 && i < 8) || (i > 10)) {\n record = 0\n }\n if(i == 5){\n poke(c.io.flush, 1)\n }else {\n poke(c.io.flush, 0)\n }\n", "right_context": " addr = addr + 1\n\n }\n}\n\nclass Addr_Buffer_Spec extends FlatSpec with Matchers {\n iotesters.Driver.execute(Array(\"--backend-name\", \"verilator\"), () => new Addr_Buffer) {\n c => new Addr_Buffer_Test(c)\n }\n\n iotesters.Driver.execute(Array(\"--is-verbose\"), () => new Addr_Buffer) {\n c => new Addr_Buffer_Test(c)\n }\n}\n", "groundtruth": " poke(c.io.addr_input, addr)\n poke(c.io.record, record)\n peek(c.io.front)\n", "crossfile_context": ""}
{"task_id": "riscv-mini-five-stage", "path": "riscv-mini-five-stage/src/test/scala/riscv_mini_five_stage_test/Datapath_Test.scala", "left_context": "package riscv_mini_five_stage\n\nimport chisel3._\nimport chisel3.iotesters._\nimport chisel3.util\nimport org.scalatest.{FlatSpec, Matchers}\n\nclass Datapath_Test(c: Datapath) extends PeekPokeTester(c) {\n var rs2_out = 10\n var imm = Integer.parseInt(\"0000001D\",16)\n var pc = Integer.parseInt(\"0000010E\", 16)\n var alu_src = 0\n\n poke(c.io.ex_datapathio.ex_rs2_out, rs2_out)\n poke(c.io.ex_datapathio.ex_imm, imm)\n poke(c.io.ex_datapathio.ex_pc, pc)\n poke(c.io.ex_datapathio.ex_ALU_Src, alu_src)\n peek(c.io.ex_datapathio.alu_b_src)\n step(1)\n}\n\nclass Datapath_Spec extends FlatSpec with Matchers {\n", "right_context": " c => new Datapath_Test(c)\n }\n}", "groundtruth": " iotesters.Driver.execute(Array(\"--backend-name\", \"verilator\"), () => new Datapath) {\n c => new Datapath_Test(c)\n }\n", "crossfile_context": ""}
{"task_id": "riscv-mini-five-stage", "path": "riscv-mini-five-stage/src/test/scala/riscv_mini_five_stage_test/ID_EX_Register_Test.scala", "left_context": "package riscv_mini_five_stage\n\nimport chisel3._\nimport chisel3.iotesters\nimport chisel3.iotesters.PeekPokeTester\nimport chisel3.util._\nimport org.scalatest.{FlatSpec, Matchers}\nimport Control._\n\nclass ID_EX_Register_Test(c: ID_EX_Register) extends PeekPokeTester(c) {\n // Some test code\n}\n\nclass ID_EX_Register_Spec extends FlatSpec with Matchers {\n", "right_context": " c => new ID_EX_Register_Test(c)\n }\n}\n", "groundtruth": " iotesters.Driver.execute(Array(\"--backend-name\", \"-verilator\"), () => new ID_EX_Register) {\n c => new ID_EX_Register_Test(c)\n }\n", "crossfile_context": ""}
{"task_id": "riscv-mini-five-stage", "path": "riscv-mini-five-stage/src/test/scala/riscv_mini_five_stage_test/ImmGen_Test.scala", "left_context": "package riscv_mini_five_stage\n\nimport chisel3._\nimport chisel3.iotesters\nimport chisel3.iotesters.PeekPokeTester\nimport chisel3.util._\nimport org.scalatest.{FlatSpec, Matchers}\nimport Control._\n\nclass ImmGen_Test(c: ImmGen) extends PeekPokeTester(c) {\n var inst = Integer.parseInt(\"00000110000000001010000110000011\", 2)\n var imm_sel = IMM_I\n poke(c.io.inst_in, inst)\n poke(c.io.imm_sel, imm_sel)\n peek(c.io.imm)\n}\n\nclass ImmGen_Spec extends FlatSpec with Matchers {\n iotesters.Driver.execute(Array(\"--backend-name\", \"verilator\"), () => new ImmGen) {\n c => new ImmGen_Test(c)\n }\n\n", "right_context": "", "groundtruth": " iotesters.Driver.execute(Array(\"--is-verbose\"), () => new ImmGen) {\n c => new ImmGen_Test(c)\n }\n", "crossfile_context": ""}
{"task_id": "riscv-mini-five-stage", "path": "riscv-mini-five-stage/src/test/scala/riscv_mini_five_stage_test/RegFile_Test.scala", "left_context": "package riscv_mini_five_stage\n\nimport chisel3._\nimport chisel3.iotesters._\nimport chisel3.util\nimport org.scalatest.{FlatSpec, Matchers}\n\nclass RegFile_Test(c: RegFile) extends PeekPokeTester(c) {\n var rs1 = 1\n var rs2 = 2\n var rd = 0\n var wdata = 10\n", "right_context": " if(i == 6) {\n rs1 = rd\n rs2 = rd\n }\n\n poke(c.io.rs1, rs1)\n poke(c.io.rs2, rs2)\n poke(c.io.rd, rd)\n poke(c.io.wdata, wdata)\n poke(c.io.regwrite, 1)\n step(1)\n rd = rd + 1\n wdata = wdata + 1\n }\n}\n\nclass RegFile_Spec extends FlatSpec with Matchers {\n iotesters.Driver.execute(Array(\"--backend-name\", \"verilator\"), () => new RegFile) {\n c => new RegFile_Test(c)\n }\n\n iotesters.Driver.execute(Array(\"--is-verbose\"), () => new RegFile) {\n c => new RegFile_Test(c)\n }\n}", "groundtruth": " for(i <- 1 to 10) {\n", "crossfile_context": ""}
{"task_id": "riscv-mini-five-stage", "path": "riscv-mini-five-stage/src/test/scala/riscv_mini_five_stage_test/Tile_Test.scala", "left_context": "package riscv_mini_five_stage\n\nimport chisel3._\nimport chisel3.iotesters\nimport chisel3.iotesters.PeekPokeTester\nimport chisel3.util\nimport org.scalatest.{FlatSpec, Matchers}\n\nclass Tile_Test(c: Tile) extends PeekPokeTester(c) {\n for(i <- 0 to 2000) {\n // Input\n peek(c.io.if_pc_out)\n peek(c.io.if_next_pc)\n peek(c.io.id_rs1)\n peek(c.io.id_rs2)\n peek(c.io.id_rs1_out)\n peek(c.io.id_rs2_out)\n peek(c.io.ex_rs1_out)\n peek(c.io.ex_rs2_out)\n peek(c.io.ex_alu_sum)\n peek(c.io.ex_alu_conflag)\n peek(c.io.ex_rd)\n peek(c.io.mem_rd)\n peek(c.io.mem_alu_sum)\n peek(c.io.mem_writedata)\n peek(c.io.mem_dataout)\n peek(c.io.wb_rd)\n peek(c.io.wb_registerwrite)\n peek(c.io.Forward_A)\n peek(c.io.Forward_B)\n peek(c.io.MemWrite_Src)\n step(1)\n }\n}\n\nclass Tile_Spec extends FlatSpec with Matchers {\n Encoding.generate_hexcode()\n\n iotesters.Driver.execute(Array(\"--backend-name\", \"verilator\"), () => new Tile) {\n c => new Tile_Test(c)\n }\n\n", "right_context": "", "groundtruth": " iotesters.Driver.execute(Array(\"--is-verbose\"), () => new Tile){\n c => new Tile_Test(c)\n }\n", "crossfile_context": ""}
{"task_id": "aes_chisel", "path": "aes_chisel/src/main/scala/aes/InvMixColumns.scala", "left_context": "package aes\n\nimport chisel3._\nimport chisel3.util._\n\n// implements InvMixColumns\nclass InvMixColumns(Pipelined: Boolean = false) extends Module {\n val io = IO(new Bundle {\n val state_in = Input(Vec(Params.StateLength, UInt(8.W)))\n val state_out = Output(Vec(Params.StateLength, UInt(8.W)))\n })\n\n /*\n val mul02 = VecInit(Array(\n 0x00.U, 0x02.U, 0x04.U, 0x06.U, 0x08.U, 0x0a.U, 0x0c.U, 0x0e.U, 0x10.U, 0x12.U, 0x14.U, 0x16.U, 0x18.U, 0x1a.U, 0x1c.U, 0x1e.U,\n 0x20.U, 0x22.U, 0x24.U, 0x26.U, 0x28.U, 0x2a.U, 0x2c.U, 0x2e.U, 0x30.U, 0x32.U, 0x34.U, 0x36.U, 0x38.U, 0x3a.U, 0x3c.U, 0x3e.U,\n 0x40.U, 0x42.U, 0x44.U, 0x46.U, 0x48.U, 0x4a.U, 0x4c.U, 0x4e.U, 0x50.U, 0x52.U, 0x54.U, 0x56.U, 0x58.U, 0x5a.U, 0x5c.U, 0x5e.U,\n 0x60.U, 0x62.U, 0x64.U, 0x66.U, 0x68.U, 0x6a.U, 0x6c.U, 0x6e.U, 0x70.U, 0x72.U, 0x74.U, 0x76.U, 0x78.U, 0x7a.U, 0x7c.U, 0x7e.U,\n 0x80.U, 0x82.U, 0x84.U, 0x86.U, 0x88.U, 0x8a.U, 0x8c.U, 0x8e.U, 0x90.U, 0x92.U, 0x94.U, 0x96.U, 0x98.U, 0x9a.U, 0x9c.U, 0x9e.U,\n 0xa0.U, 0xa2.U, 0xa4.U, 0xa6.U, 0xa8.U, 0xaa.U, 0xac.U, 0xae.U, 0xb0.U, 0xb2.U, 0xb4.U, 0xb6.U, 0xb8.U, 0xba.U, 0xbc.U, 0xbe.U,\n 0xc0.U, 0xc2.U, 0xc4.U, 0xc6.U, 0xc8.U, 0xca.U, 0xcc.U, 0xce.U, 0xd0.U, 0xd2.U, 0xd4.U, 0xd6.U, 0xd8.U, 0xda.U, 0xdc.U, 0xde.U,\n 0xe0.U, 0xe2.U, 0xe4.U, 0xe6.U, 0xe8.U, 0xea.U, 0xec.U, 0xee.U, 0xf0.U, 0xf2.U, 0xf4.U, 0xf6.U, 0xf8.U, 0xfa.U, 0xfc.U, 0xfe.U,\n 0x1b.U, 0x19.U, 0x1f.U, 0x1d.U, 0x13.U, 0x11.U, 0x17.U, 0x15.U, 0x0b.U, 0x09.U, 0x0f.U, 0x0d.U, 0x03.U, 0x01.U, 0x07.U, 0x05.U,\n 0x3b.U, 0x39.U, 0x3f.U, 0x3d.U, 0x33.U, 0x31.U, 0x37.U, 0x35.U, 0x2b.U, 0x29.U, 0x2f.U, 0x2d.U, 0x23.U, 0x21.U, 0x27.U, 0x25.U,\n 0x5b.U, 0x59.U, 0x5f.U, 0x5d.U, 0x53.U, 0x51.U, 0x57.U, 0x55.U, 0x4b.U, 0x49.U, 0x4f.U, 0x4d.U, 0x43.U, 0x41.U, 0x47.U, 0x45.U,\n 0x7b.U, 0x79.U, 0x7f.U, 0x7d.U, 0x73.U, 0x71.U, 0x77.U, 0x75.U, 0x6b.U, 0x69.U, 0x6f.U, 0x6d.U, 0x63.U, 0x61.U, 0x67.U, 0x65.U,\n 0x9b.U, 0x99.U, 0x9f.U, 0x9d.U, 0x93.U, 0x91.U, 0x97.U, 0x95.U, 0x8b.U, 0x89.U, 0x8f.U, 0x8d.U, 0x83.U, 0x81.U, 0x87.U, 0x85.U,\n 0xbb.U, 0xb9.U, 0xbf.U, 0xbd.U, 0xb3.U, 0xb1.U, 0xb7.U, 0xb5.U, 0xab.U, 0xa9.U, 0xaf.U, 0xad.U, 0xa3.U, 0xa1.U, 0xa7.U, 0xa5.U,\n 0xdb.U, 0xd9.U, 0xdf.U, 0xdd.U, 0xd3.U, 0xd1.U, 0xd7.U, 0xd5.U, 0xcb.U, 0xc9.U, 0xcf.U, 0xcd.U, 0xc3.U, 0xc1.U, 0xc7.U, 0xc5.U,\n 0xfb.U, 0xf9.U, 0xff.U, 0xfd.U, 0xf3.U, 0xf1.U, 0xf7.U, 0xf5.U, 0xeb.U, 0xe9.U, 0xef.U, 0xed.U, 0xe3.U, 0xe1.U, 0xe7.U, 0xe5.U))\n\n val mul03 = VecInit(Array(\n 0x00.U, 0x03.U, 0x06.U, 0x05.U, 0x0c.U, 0x0f.U, 0x0a.U, 0x09.U, 0x18.U, 0x1b.U, 0x1e.U, 0x1d.U, 0x14.U, 0x17.U, 0x12.U, 0x11.U,\n 0x30.U, 0x33.U, 0x36.U, 0x35.U, 0x3c.U, 0x3f.U, 0x3a.U, 0x39.U, 0x28.U, 0x2b.U, 0x2e.U, 0x2d.U, 0x24.U, 0x27.U, 0x22.U, 0x21.U,\n 0x60.U, 0x63.U, 0x66.U, 0x65.U, 0x6c.U, 0x6f.U, 0x6a.U, 0x69.U, 0x78.U, 0x7b.U, 0x7e.U, 0x7d.U, 0x74.U, 0x77.U, 0x72.U, 0x71.U,\n 0x50.U, 0x53.U, 0x56.U, 0x55.U, 0x5c.U, 0x5f.U, 0x5a.U, 0x59.U, 0x48.U, 0x4b.U, 0x4e.U, 0x4d.U, 0x44.U, 0x47.U, 0x42.U, 0x41.U,\n 0xc0.U, 0xc3.U, 0xc6.U, 0xc5.U, 0xcc.U, 0xcf.U, 0xca.U, 0xc9.U, 0xd8.U, 0xdb.U, 0xde.U, 0xdd.U, 0xd4.U, 0xd7.U, 0xd2.U, 0xd1.U,\n 0xf0.U, 0xf3.U, 0xf6.U, 0xf5.U, 0xfc.U, 0xff.U, 0xfa.U, 0xf9.U, 0xe8.U, 0xeb.U, 0xee.U, 0xed.U, 0xe4.U, 0xe7.U, 0xe2.U, 0xe1.U,\n 0xa0.U, 0xa3.U, 0xa6.U, 0xa5.U, 0xac.U, 0xaf.U, 0xaa.U, 0xa9.U, 0xb8.U, 0xbb.U, 0xbe.U, 0xbd.U, 0xb4.U, 0xb7.U, 0xb2.U, 0xb1.U,\n 0x90.U, 0x93.U, 0x96.U, 0x95.U, 0x9c.U, 0x9f.U, 0x9a.U, 0x99.U, 0x88.U, 0x8b.U, 0x8e.U, 0x8d.U, 0x84.U, 0x87.U, 0x82.U, 0x81.U,\n 0x9b.U, 0x98.U, 0x9d.U, 0x9e.U, 0x97.U, 0x94.U, 0x91.U, 0x92.U, 0x83.U, 0x80.U, 0x85.U, 0x86.U, 0x8f.U, 0x8c.U, 0x89.U, 0x8a.U,\n 0xab.U, 0xa8.U, 0xad.U, 0xae.U, 0xa7.U, 0xa4.U, 0xa1.U, 0xa2.U, 0xb3.U, 0xb0.U, 0xb5.U, 0xb6.U, 0xbf.U, 0xbc.U, 0xb9.U, 0xba.U,\n 0xfb.U, 0xf8.U, 0xfd.U, 0xfe.U, 0xf7.U, 0xf4.U, 0xf1.U, 0xf2.U, 0xe3.U, 0xe0.U, 0xe5.U, 0xe6.U, 0xef.U, 0xec.U, 0xe9.U, 0xea.U,\n 0xcb.U, 0xc8.U, 0xcd.U, 0xce.U, 0xc7.U, 0xc4.U, 0xc1.U, 0xc2.U, 0xd3.U, 0xd0.U, 0xd5.U, 0xd6.U, 0xdf.U, 0xdc.U, 0xd9.U, 0xda.U,\n 0x5b.U, 0x58.U, 0x5d.U, 0x5e.U, 0x57.U, 0x54.U, 0x51.U, 0x52.U, 0x43.U, 0x40.U, 0x45.U, 0x46.U, 0x4f.U, 0x4c.U, 0x49.U, 0x4a.U,\n 0x6b.U, 0x68.U, 0x6d.U, 0x6e.U, 0x67.U, 0x64.U, 0x61.U, 0x62.U, 0x73.U, 0x70.U, 0x75.U, 0x76.U, 0x7f.U, 0x7c.U, 0x79.U, 0x7a.U,\n 0x3b.U, 0x38.U, 0x3d.U, 0x3e.U, 0x37.U, 0x34.U, 0x31.U, 0x32.U, 0x23.U, 0x20.U, 0x25.U, 0x26.U, 0x2f.U, 0x2c.U, 0x29.U, 0x2a.U,\n 0x0b.U, 0x08.U, 0x0d.U, 0x0e.U, 0x07.U, 0x04.U, 0x01.U, 0x02.U, 0x13.U, 0x10.U, 0x15.U, 0x16.U, 0x1f.U, 0x1c.U, 0x19.U, 0x1a.U))\n*/\n\n val mul09 = VecInit(Array(\n 0x00.U, 0x09.U, 0x12.U, 0x1b.U, 0x24.U, 0x2d.U, 0x36.U, 0x3f.U, 0x48.U, 0x41.U, 0x5a.U, 0x53.U, 0x6c.U, 0x65.U, 0x7e.U, 0x77.U,\n 0x90.U, 0x99.U, 0x82.U, 0x8b.U, 0xb4.U, 0xbd.U, 0xa6.U, 0xaf.U, 0xd8.U, 0xd1.U, 0xca.U, 0xc3.U, 0xfc.U, 0xf5.U, 0xee.U, 0xe7.U,\n 0x3b.U, 0x32.U, 0x29.U, 0x20.U, 0x1f.U, 0x16.U, 0x0d.U, 0x04.U, 0x73.U, 0x7a.U, 0x61.U, 0x68.U, 0x57.U, 0x5e.U, 0x45.U, 0x4c.U,\n 0xab.U, 0xa2.U, 0xb9.U, 0xb0.U, 0x8f.U, 0x86.U, 0x9d.U, 0x94.U, 0xe3.U, 0xea.U, 0xf1.U, 0xf8.U, 0xc7.U, 0xce.U, 0xd5.U, 0xdc.U,\n 0x76.U, 0x7f.U, 0x64.U, 0x6d.U, 0x52.U, 0x5b.U, 0x40.U, 0x49.U, 0x3e.U, 0x37.U, 0x2c.U, 0x25.U, 0x1a.U, 0x13.U, 0x08.U, 0x01.U,\n 0xe6.U, 0xef.U, 0xf4.U, 0xfd.U, 0xc2.U, 0xcb.U, 0xd0.U, 0xd9.U, 0xae.U, 0xa7.U, 0xbc.U, 0xb5.U, 0x8a.U, 0x83.U, 0x98.U, 0x91.U,\n 0x4d.U, 0x44.U, 0x5f.U, 0x56.U, 0x69.U, 0x60.U, 0x7b.U, 0x72.U, 0x05.U, 0x0c.U, 0x17.U, 0x1e.U, 0x21.U, 0x28.U, 0x33.U, 0x3a.U,\n 0xdd.U, 0xd4.U, 0xcf.U, 0xc6.U, 0xf9.U, 0xf0.U, 0xeb.U, 0xe2.U, 0x95.U, 0x9c.U, 0x87.U, 0x8e.U, 0xb1.U, 0xb8.U, 0xa3.U, 0xaa.U,\n 0xec.U, 0xe5.U, 0xfe.U, 0xf7.U, 0xc8.U, 0xc1.U, 0xda.U, 0xd3.U, 0xa4.U, 0xad.U, 0xb6.U, 0xbf.U, 0x80.U, 0x89.U, 0x92.U, 0x9b.U,\n 0x7c.U, 0x75.U, 0x6e.U, 0x67.U, 0x58.U, 0x51.U, 0x4a.U, 0x43.U, 0x34.U, 0x3d.U, 0x26.U, 0x2f.U, 0x10.U, 0x19.U, 0x02.U, 0x0b.U,\n 0xd7.U, 0xde.U, 0xc5.U, 0xcc.U, 0xf3.U, 0xfa.U, 0xe1.U, 0xe8.U, 0x9f.U, 0x96.U, 0x8d.U, 0x84.U, 0xbb.U, 0xb2.U, 0xa9.U, 0xa0.U,\n 0x47.U, 0x4e.U, 0x55.U, 0x5c.U, 0x63.U, 0x6a.U, 0x71.U, 0x78.U, 0x0f.U, 0x06.U, 0x1d.U, 0x14.U, 0x2b.U, 0x22.U, 0x39.U, 0x30.U,\n 0x9a.U, 0x93.U, 0x88.U, 0x81.U, 0xbe.U, 0xb7.U, 0xac.U, 0xa5.U, 0xd2.U, 0xdb.U, 0xc0.U, 0xc9.U, 0xf6.U, 0xff.U, 0xe4.U, 0xed.U,\n 0x0a.U, 0x03.U, 0x18.U, 0x11.U, 0x2e.U, 0x27.U, 0x3c.U, 0x35.U, 0x42.U, 0x4b.U, 0x50.U, 0x59.U, 0x66.U, 0x6f.U, 0x74.U, 0x7d.U,\n 0xa1.U, 0xa8.U, 0xb3.U, 0xba.U, 0x85.U, 0x8c.U, 0x97.U, 0x9e.U, 0xe9.U, 0xe0.U, 0xfb.U, 0xf2.U, 0xcd.U, 0xc4.U, 0xdf.U, 0xd6.U,\n 0x31.U, 0x38.U, 0x23.U, 0x2a.U, 0x15.U, 0x1c.U, 0x07.U, 0x0e.U, 0x79.U, 0x70.U, 0x6b.U, 0x62.U, 0x5d.U, 0x54.U, 0x4f.U, 0x46.U))\n\n val mul11 = VecInit(Array(\n 0x00.U, 0x0b.U, 0x16.U, 0x1d.U, 0x2c.U, 0x27.U, 0x3a.U, 0x31.U, 0x58.U, 0x53.U, 0x4e.U, 0x45.U, 0x74.U, 0x7f.U, 0x62.U, 0x69.U,\n 0xb0.U, 0xbb.U, 0xa6.U, 0xad.U, 0x9c.U, 0x97.U, 0x8a.U, 0x81.U, 0xe8.U, 0xe3.U, 0xfe.U, 0xf5.U, 0xc4.U, 0xcf.U, 0xd2.U, 0xd9.U,\n 0x7b.U, 0x70.U, 0x6d.U, 0x66.U, 0x57.U, 0x5c.U, 0x41.U, 0x4a.U, 0x23.U, 0x28.U, 0x35.U, 0x3e.U, 0x0f.U, 0x04.U, 0x19.U, 0x12.U,\n 0xcb.U, 0xc0.U, 0xdd.U, 0xd6.U, 0xe7.U, 0xec.U, 0xf1.U, 0xfa.U, 0x93.U, 0x98.U, 0x85.U, 0x8e.U, 0xbf.U, 0xb4.U, 0xa9.U, 0xa2.U,\n 0xf6.U, 0xfd.U, 0xe0.U, 0xeb.U, 0xda.U, 0xd1.U, 0xcc.U, 0xc7.U, 0xae.U, 0xa5.U, 0xb8.U, 0xb3.U, 0x82.U, 0x89.U, 0x94.U, 0x9f.U,\n 0x46.U, 0x4d.U, 0x50.U, 0x5b.U, 0x6a.U, 0x61.U, 0x7c.U, 0x77.U, 0x1e.U, 0x15.U, 0x08.U, 0x03.U, 0x32.U, 0x39.U, 0x24.U, 0x2f.U,\n 0x8d.U, 0x86.U, 0x9b.U, 0x90.U, 0xa1.U, 0xaa.U, 0xb7.U, 0xbc.U, 0xd5.U, 0xde.U, 0xc3.U, 0xc8.U, 0xf9.U, 0xf2.U, 0xef.U, 0xe4.U,\n 0x3d.U, 0x36.U, 0x2b.U, 0x20.U, 0x11.U, 0x1a.U, 0x07.U, 0x0c.U, 0x65.U, 0x6e.U, 0x73.U, 0x78.U, 0x49.U, 0x42.U, 0x5f.U, 0x54.U,\n 0xf7.U, 0xfc.U, 0xe1.U, 0xea.U, 0xdb.U, 0xd0.U, 0xcd.U, 0xc6.U, 0xaf.U, 0xa4.U, 0xb9.U, 0xb2.U, 0x83.U, 0x88.U, 0x95.U, 0x9e.U,\n 0x47.U, 0x4c.U, 0x51.U, 0x5a.U, 0x6b.U, 0x60.U, 0x7d.U, 0x76.U, 0x1f.U, 0x14.U, 0x09.U, 0x02.U, 0x33.U, 0x38.U, 0x25.U, 0x2e.U,\n 0x8c.U, 0x87.U, 0x9a.U, 0x91.U, 0xa0.U, 0xab.U, 0xb6.U, 0xbd.U, 0xd4.U, 0xdf.U, 0xc2.U, 0xc9.U, 0xf8.U, 0xf3.U, 0xee.U, 0xe5.U,\n 0x3c.U, 0x37.U, 0x2a.U, 0x21.U, 0x10.U, 0x1b.U, 0x06.U, 0x0d.U, 0x64.U, 0x6f.U, 0x72.U, 0x79.U, 0x48.U, 0x43.U, 0x5e.U, 0x55.U,\n 0x01.U, 0x0a.U, 0x17.U, 0x1c.U, 0x2d.U, 0x26.U, 0x3b.U, 0x30.U, 0x59.U, 0x52.U, 0x4f.U, 0x44.U, 0x75.U, 0x7e.U, 0x63.U, 0x68.U,\n 0xb1.U, 0xba.U, 0xa7.U, 0xac.U, 0x9d.U, 0x96.U, 0x8b.U, 0x80.U, 0xe9.U, 0xe2.U, 0xff.U, 0xf4.U, 0xc5.U, 0xce.U, 0xd3.U, 0xd8.U,\n 0x7a.U, 0x71.U, 0x6c.U, 0x67.U, 0x56.U, 0x5d.U, 0x40.U, 0x4b.U, 0x22.U, 0x29.U, 0x34.U, 0x3f.U, 0x0e.U, 0x05.U, 0x18.U, 0x13.U,\n 0xca.U, 0xc1.U, 0xdc.U, 0xd7.U, 0xe6.U, 0xed.U, 0xf0.U, 0xfb.U, 0x92.U, 0x99.U, 0x84.U, 0x8f.U, 0xbe.U, 0xb5.U, 0xa8.U, 0xa3.U))\n\n val mul13 = VecInit(Array(\n 0x00.U, 0x0d.U, 0x1a.U, 0x17.U, 0x34.U, 0x39.U, 0x2e.U, 0x23.U, 0x68.U, 0x65.U, 0x72.U, 0x7f.U, 0x5c.U, 0x51.U, 0x46.U, 0x4b.U,\n 0xd0.U, 0xdd.U, 0xca.U, 0xc7.U, 0xe4.U, 0xe9.U, 0xfe.U, 0xf3.U, 0xb8.U, 0xb5.U, 0xa2.U, 0xaf.U, 0x8c.U, 0x81.U, 0x96.U, 0x9b.U,\n 0xbb.U, 0xb6.U, 0xa1.U, 0xac.U, 0x8f.U, 0x82.U, 0x95.U, 0x98.U, 0xd3.U, 0xde.U, 0xc9.U, 0xc4.U, 0xe7.U, 0xea.U, 0xfd.U, 0xf0.U,\n 0x6b.U, 0x66.U, 0x71.U, 0x7c.U, 0x5f.U, 0x52.U, 0x45.U, 0x48.U, 0x03.U, 0x0e.U, 0x19.U, 0x14.U, 0x37.U, 0x3a.U, 0x2d.U, 0x20.U,\n 0x6d.U, 0x60.U, 0x77.U, 0x7a.U, 0x59.U, 0x54.U, 0x43.U, 0x4e.U, 0x05.U, 0x08.U, 0x1f.U, 0x12.U, 0x31.U, 0x3c.U, 0x2b.U, 0x26.U,\n 0xbd.U, 0xb0.U, 0xa7.U, 0xaa.U, 0x89.U, 0x84.U, 0x93.U, 0x9e.U, 0xd5.U, 0xd8.U, 0xcf.U, 0xc2.U, 0xe1.U, 0xec.U, 0xfb.U, 0xf6.U,\n 0xd6.U, 0xdb.U, 0xcc.U, 0xc1.U, 0xe2.U, 0xef.U, 0xf8.U, 0xf5.U, 0xbe.U, 0xb3.U, 0xa4.U, 0xa9.U, 0x8a.U, 0x87.U, 0x90.U, 0x9d.U,\n 0x06.U, 0x0b.U, 0x1c.U, 0x11.U, 0x32.U, 0x3f.U, 0x28.U, 0x25.U, 0x6e.U, 0x63.U, 0x74.U, 0x79.U, 0x5a.U, 0x57.U, 0x40.U, 0x4d.U,\n 0xda.U, 0xd7.U, 0xc0.U, 0xcd.U, 0xee.U, 0xe3.U, 0xf4.U, 0xf9.U, 0xb2.U, 0xbf.U, 0xa8.U, 0xa5.U, 0x86.U, 0x8b.U, 0x9c.U, 0x91.U,\n 0x0a.U, 0x07.U, 0x10.U, 0x1d.U, 0x3e.U, 0x33.U, 0x24.U, 0x29.U, 0x62.U, 0x6f.U, 0x78.U, 0x75.U, 0x56.U, 0x5b.U, 0x4c.U, 0x41.U,\n 0x61.U, 0x6c.U, 0x7b.U, 0x76.U, 0x55.U, 0x58.U, 0x4f.U, 0x42.U, 0x09.U, 0x04.U, 0x13.U, 0x1e.U, 0x3d.U, 0x30.U, 0x27.U, 0x2a.U,\n 0xb1.U, 0xbc.U, 0xab.U, 0xa6.U, 0x85.U, 0x88.U, 0x9f.U, 0x92.U, 0xd9.U, 0xd4.U, 0xc3.U, 0xce.U, 0xed.U, 0xe0.U, 0xf7.U, 0xfa.U,\n 0xb7.U, 0xba.U, 0xad.U, 0xa0.U, 0x83.U, 0x8e.U, 0x99.U, 0x94.U, 0xdf.U, 0xd2.U, 0xc5.U, 0xc8.U, 0xeb.U, 0xe6.U, 0xf1.U, 0xfc.U,\n 0x67.U, 0x6a.U, 0x7d.U, 0x70.U, 0x53.U, 0x5e.U, 0x49.U, 0x44.U, 0x0f.U, 0x02.U, 0x15.U, 0x18.U, 0x3b.U, 0x36.U, 0x21.U, 0x2c.U,\n 0x0c.U, 0x01.U, 0x16.U, 0x1b.U, 0x38.U, 0x35.U, 0x22.U, 0x2f.U, 0x64.U, 0x69.U, 0x7e.U, 0x73.U, 0x50.U, 0x5d.U, 0x4a.U, 0x47.U,\n 0xdc.U, 0xd1.U, 0xc6.U, 0xcb.U, 0xe8.U, 0xe5.U, 0xf2.U, 0xff.U, 0xb4.U, 0xb9.U, 0xae.U, 0xa3.U, 0x80.U, 0x8d.U, 0x9a.U, 0x97.U))\n\n val mul14 = VecInit(Array(\n 0x00.U, 0x0e.U, 0x1c.U, 0x12.U, 0x38.U, 0x36.U, 0x24.U, 0x2a.U, 0x70.U, 0x7e.U, 0x6c.U, 0x62.U, 0x48.U, 0x46.U, 0x54.U, 0x5a.U,\n 0xe0.U, 0xee.U, 0xfc.U, 0xf2.U, 0xd8.U, 0xd6.U, 0xc4.U, 0xca.U, 0x90.U, 0x9e.U, 0x8c.U, 0x82.U, 0xa8.U, 0xa6.U, 0xb4.U, 0xba.U,\n 0xdb.U, 0xd5.U, 0xc7.U, 0xc9.U, 0xe3.U, 0xed.U, 0xff.U, 0xf1.U, 0xab.U, 0xa5.U, 0xb7.U, 0xb9.U, 0x93.U, 0x9d.U, 0x8f.U, 0x81.U,\n 0x3b.U, 0x35.U, 0x27.U, 0x29.U, 0x03.U, 0x0d.U, 0x1f.U, 0x11.U, 0x4b.U, 0x45.U, 0x57.U, 0x59.U, 0x73.U, 0x7d.U, 0x6f.U, 0x61.U,\n 0xad.U, 0xa3.U, 0xb1.U, 0xbf.U, 0x95.U, 0x9b.U, 0x89.U, 0x87.U, 0xdd.U, 0xd3.U, 0xc1.U, 0xcf.U, 0xe5.U, 0xeb.U, 0xf9.U, 0xf7.U,\n 0x4d.U, 0x43.U, 0x51.U, 0x5f.U, 0x75.U, 0x7b.U, 0x69.U, 0x67.U, 0x3d.U, 0x33.U, 0x21.U, 0x2f.U, 0x05.U, 0x0b.U, 0x19.U, 0x17.U,\n 0x76.U, 0x78.U, 0x6a.U, 0x64.U, 0x4e.U, 0x40.U, 0x52.U, 0x5c.U, 0x06.U, 0x08.U, 0x1a.U, 0x14.U, 0x3e.U, 0x30.U, 0x22.U, 0x2c.U,\n 0x96.U, 0x98.U, 0x8a.U, 0x84.U, 0xae.U, 0xa0.U, 0xb2.U, 0xbc.U, 0xe6.U, 0xe8.U, 0xfa.U, 0xf4.U, 0xde.U, 0xd0.U, 0xc2.U, 0xcc.U,\n 0x41.U, 0x4f.U, 0x5d.U, 0x53.U, 0x79.U, 0x77.U, 0x65.U, 0x6b.U, 0x31.U, 0x3f.U, 0x2d.U, 0x23.U, 0x09.U, 0x07.U, 0x15.U, 0x1b.U,\n 0xa1.U, 0xaf.U, 0xbd.U, 0xb3.U, 0x99.U, 0x97.U, 0x85.U, 0x8b.U, 0xd1.U, 0xdf.U, 0xcd.U, 0xc3.U, 0xe9.U, 0xe7.U, 0xf5.U, 0xfb.U,\n 0x9a.U, 0x94.U, 0x86.U, 0x88.U, 0xa2.U, 0xac.U, 0xbe.U, 0xb0.U, 0xea.U, 0xe4.U, 0xf6.U, 0xf8.U, 0xd2.U, 0xdc.U, 0xce.U, 0xc0.U,\n 0x7a.U, 0x74.U, 0x66.U, 0x68.U, 0x42.U, 0x4c.U, 0x5e.U, 0x50.U, 0x0a.U, 0x04.U, 0x16.U, 0x18.U, 0x32.U, 0x3c.U, 0x2e.U, 0x20.U,\n 0xec.U, 0xe2.U, 0xf0.U, 0xfe.U, 0xd4.U, 0xda.U, 0xc8.U, 0xc6.U, 0x9c.U, 0x92.U, 0x80.U, 0x8e.U, 0xa4.U, 0xaa.U, 0xb8.U, 0xb6.U,\n 0x0c.U, 0x02.U, 0x10.U, 0x1e.U, 0x34.U, 0x3a.U, 0x28.U, 0x26.U, 0x7c.U, 0x72.U, 0x60.U, 0x6e.U, 0x44.U, 0x4a.U, 0x58.U, 0x56.U,\n 0x37.U, 0x39.U, 0x2b.U, 0x25.U, 0x0f.U, 0x01.U, 0x13.U, 0x1d.U, 0x47.U, 0x49.U, 0x5b.U, 0x55.U, 0x7f.U, 0x71.U, 0x63.U, 0x6d.U,\n 0xd7.U, 0xd9.U, 0xcb.U, 0xc5.U, 0xef.U, 0xe1.U, 0xf3.U, 0xfd.U, 0xa7.U, 0xa9.U, 0xbb.U, 0xb5.U, 0x9f.U, 0x91.U, 0x83.U, 0x8d.U))\n\n val tmp_state = Wire(Vec(Params.StateLength, UInt(8.W)))\n\n tmp_state(0) := mul14(io.state_in(0)) ^ mul11(io.state_in(1)) ^ mul13(io.state_in(2)) ^ mul09(io.state_in(3))\n tmp_state(1) := mul09(io.state_in(0)) ^ mul14(io.state_in(1)) ^ mul11(io.state_in(2)) ^ mul13(io.state_in(3))\n tmp_state(2) := mul13(io.state_in(0)) ^ mul09(io.state_in(1)) ^ mul14(io.state_in(2)) ^ mul11(io.state_in(3))\n tmp_state(3) := mul11(io.state_in(0)) ^ mul13(io.state_in(1)) ^ mul09(io.state_in(2)) ^ mul14(io.state_in(3))\n\n tmp_state(4) := mul14(io.state_in(4)) ^ mul11(io.state_in(5)) ^ mul13(io.state_in(6)) ^ mul09(io.state_in(7))\n tmp_state(5) := mul09(io.state_in(4)) ^ mul14(io.state_in(5)) ^ mul11(io.state_in(6)) ^ mul13(io.state_in(7))\n tmp_state(6) := mul13(io.state_in(4)) ^ mul09(io.state_in(5)) ^ mul14(io.state_in(6)) ^ mul11(io.state_in(7))\n tmp_state(7) := mul11(io.state_in(4)) ^ mul13(io.state_in(5)) ^ mul09(io.state_in(6)) ^ mul14(io.state_in(7))\n\n tmp_state(8) := mul14(io.state_in(8)) ^ mul11(io.state_in(9)) ^ mul13(io.state_in(10)) ^ mul09(io.state_in(11))\n tmp_state(9) := mul09(io.state_in(8)) ^ mul14(io.state_in(9)) ^ mul11(io.state_in(10)) ^ mul13(io.state_in(11))\n tmp_state(10) := mul13(io.state_in(8)) ^ mul09(io.state_in(9)) ^ mul14(io.state_in(10)) ^ mul11(io.state_in(11))\n tmp_state(11) := mul11(io.state_in(8)) ^ mul13(io.state_in(9)) ^ mul09(io.state_in(10)) ^ mul14(io.state_in(11))\n\n tmp_state(12) := mul14(io.state_in(12)) ^ mul11(io.state_in(13)) ^ mul13(io.state_in(14)) ^ mul09(io.state_in(15))\n tmp_state(13) := mul09(io.state_in(12)) ^ mul14(io.state_in(13)) ^ mul11(io.state_in(14)) ^ mul13(io.state_in(15))\n tmp_state(14) := mul13(io.state_in(12)) ^ mul09(io.state_in(13)) ^ mul14(io.state_in(14)) ^ mul11(io.state_in(15))\n tmp_state(15) := mul11(io.state_in(12)) ^ mul13(io.state_in(13)) ^ mul09(io.state_in(14)) ^ mul14(io.state_in(15))\n\n if (Pipelined) {\n io.state_out := ShiftRegister(tmp_state, 1)\n } else {\n io.state_out := tmp_state\n }\n}\n\nobject InvMixColumns {\n", "right_context": "}", "groundtruth": " def apply(Pipelined: Boolean = false): InvMixColumns = Module(new InvMixColumns(Pipelined))\n", "crossfile_context": ""}
{"task_id": "aes_chisel", "path": "aes_chisel/src/main/scala/aes/MixColumns.scala", "left_context": "package aes\n\nimport chisel3._\nimport chisel3.util._\n\n// implements MixColumns\nclass MixColumns(Pipelined: Boolean = false) extends Module {\n val io = IO(new Bundle {\n val state_in = Input(Vec(Params.StateLength, UInt(8.W)))\n val state_out = Output(Vec(Params.StateLength, UInt(8.W)))\n })\n\n val mul02 = VecInit(Array(\n 0x00.U, 0x02.U, 0x04.U, 0x06.U, 0x08.U, 0x0a.U, 0x0c.U, 0x0e.U, 0x10.U, 0x12.U, 0x14.U, 0x16.U, 0x18.U, 0x1a.U, 0x1c.U, 0x1e.U,\n 0x20.U, 0x22.U, 0x24.U, 0x26.U, 0x28.U, 0x2a.U, 0x2c.U, 0x2e.U, 0x30.U, 0x32.U, 0x34.U, 0x36.U, 0x38.U, 0x3a.U, 0x3c.U, 0x3e.U,\n 0x40.U, 0x42.U, 0x44.U, 0x46.U, 0x48.U, 0x4a.U, 0x4c.U, 0x4e.U, 0x50.U, 0x52.U, 0x54.U, 0x56.U, 0x58.U, 0x5a.U, 0x5c.U, 0x5e.U,\n 0x60.U, 0x62.U, 0x64.U, 0x66.U, 0x68.U, 0x6a.U, 0x6c.U, 0x6e.U, 0x70.U, 0x72.U, 0x74.U, 0x76.U, 0x78.U, 0x7a.U, 0x7c.U, 0x7e.U,\n 0x80.U, 0x82.U, 0x84.U, 0x86.U, 0x88.U, 0x8a.U, 0x8c.U, 0x8e.U, 0x90.U, 0x92.U, 0x94.U, 0x96.U, 0x98.U, 0x9a.U, 0x9c.U, 0x9e.U,\n 0xa0.U, 0xa2.U, 0xa4.U, 0xa6.U, 0xa8.U, 0xaa.U, 0xac.U, 0xae.U, 0xb0.U, 0xb2.U, 0xb4.U, 0xb6.U, 0xb8.U, 0xba.U, 0xbc.U, 0xbe.U,\n 0xc0.U, 0xc2.U, 0xc4.U, 0xc6.U, 0xc8.U, 0xca.U, 0xcc.U, 0xce.U, 0xd0.U, 0xd2.U, 0xd4.U, 0xd6.U, 0xd8.U, 0xda.U, 0xdc.U, 0xde.U,\n 0xe0.U, 0xe2.U, 0xe4.U, 0xe6.U, 0xe8.U, 0xea.U, 0xec.U, 0xee.U, 0xf0.U, 0xf2.U, 0xf4.U, 0xf6.U, 0xf8.U, 0xfa.U, 0xfc.U, 0xfe.U,\n 0x1b.U, 0x19.U, 0x1f.U, 0x1d.U, 0x13.U, 0x11.U, 0x17.U, 0x15.U, 0x0b.U, 0x09.U, 0x0f.U, 0x0d.U, 0x03.U, 0x01.U, 0x07.U, 0x05.U,\n 0x3b.U, 0x39.U, 0x3f.U, 0x3d.U, 0x33.U, 0x31.U, 0x37.U, 0x35.U, 0x2b.U, 0x29.U, 0x2f.U, 0x2d.U, 0x23.U, 0x21.U, 0x27.U, 0x25.U,\n 0x5b.U, 0x59.U, 0x5f.U, 0x5d.U, 0x53.U, 0x51.U, 0x57.U, 0x55.U, 0x4b.U, 0x49.U, 0x4f.U, 0x4d.U, 0x43.U, 0x41.U, 0x47.U, 0x45.U,\n 0x7b.U, 0x79.U, 0x7f.U, 0x7d.U, 0x73.U, 0x71.U, 0x77.U, 0x75.U, 0x6b.U, 0x69.U, 0x6f.U, 0x6d.U, 0x63.U, 0x61.U, 0x67.U, 0x65.U,\n 0x9b.U, 0x99.U, 0x9f.U, 0x9d.U, 0x93.U, 0x91.U, 0x97.U, 0x95.U, 0x8b.U, 0x89.U, 0x8f.U, 0x8d.U, 0x83.U, 0x81.U, 0x87.U, 0x85.U,\n 0xbb.U, 0xb9.U, 0xbf.U, 0xbd.U, 0xb3.U, 0xb1.U, 0xb7.U, 0xb5.U, 0xab.U, 0xa9.U, 0xaf.U, 0xad.U, 0xa3.U, 0xa1.U, 0xa7.U, 0xa5.U,\n 0xdb.U, 0xd9.U, 0xdf.U, 0xdd.U, 0xd3.U, 0xd1.U, 0xd7.U, 0xd5.U, 0xcb.U, 0xc9.U, 0xcf.U, 0xcd.U, 0xc3.U, 0xc1.U, 0xc7.U, 0xc5.U,\n 0xfb.U, 0xf9.U, 0xff.U, 0xfd.U, 0xf3.U, 0xf1.U, 0xf7.U, 0xf5.U, 0xeb.U, 0xe9.U, 0xef.U, 0xed.U, 0xe3.U, 0xe1.U, 0xe7.U, 0xe5.U))\n\n val mul03 = VecInit(Array(\n 0x00.U, 0x03.U, 0x06.U, 0x05.U, 0x0c.U, 0x0f.U, 0x0a.U, 0x09.U, 0x18.U, 0x1b.U, 0x1e.U, 0x1d.U, 0x14.U, 0x17.U, 0x12.U, 0x11.U,\n 0x30.U, 0x33.U, 0x36.U, 0x35.U, 0x3c.U, 0x3f.U, 0x3a.U, 0x39.U, 0x28.U, 0x2b.U, 0x2e.U, 0x2d.U, 0x24.U, 0x27.U, 0x22.U, 0x21.U,\n 0x60.U, 0x63.U, 0x66.U, 0x65.U, 0x6c.U, 0x6f.U, 0x6a.U, 0x69.U, 0x78.U, 0x7b.U, 0x7e.U, 0x7d.U, 0x74.U, 0x77.U, 0x72.U, 0x71.U,\n 0x50.U, 0x53.U, 0x56.U, 0x55.U, 0x5c.U, 0x5f.U, 0x5a.U, 0x59.U, 0x48.U, 0x4b.U, 0x4e.U, 0x4d.U, 0x44.U, 0x47.U, 0x42.U, 0x41.U,\n 0xc0.U, 0xc3.U, 0xc6.U, 0xc5.U, 0xcc.U, 0xcf.U, 0xca.U, 0xc9.U, 0xd8.U, 0xdb.U, 0xde.U, 0xdd.U, 0xd4.U, 0xd7.U, 0xd2.U, 0xd1.U,\n 0xf0.U, 0xf3.U, 0xf6.U, 0xf5.U, 0xfc.U, 0xff.U, 0xfa.U, 0xf9.U, 0xe8.U, 0xeb.U, 0xee.U, 0xed.U, 0xe4.U, 0xe7.U, 0xe2.U, 0xe1.U,\n 0xa0.U, 0xa3.U, 0xa6.U, 0xa5.U, 0xac.U, 0xaf.U, 0xaa.U, 0xa9.U, 0xb8.U, 0xbb.U, 0xbe.U, 0xbd.U, 0xb4.U, 0xb7.U, 0xb2.U, 0xb1.U,\n 0x90.U, 0x93.U, 0x96.U, 0x95.U, 0x9c.U, 0x9f.U, 0x9a.U, 0x99.U, 0x88.U, 0x8b.U, 0x8e.U, 0x8d.U, 0x84.U, 0x87.U, 0x82.U, 0x81.U,\n 0x9b.U, 0x98.U, 0x9d.U, 0x9e.U, 0x97.U, 0x94.U, 0x91.U, 0x92.U, 0x83.U, 0x80.U, 0x85.U, 0x86.U, 0x8f.U, 0x8c.U, 0x89.U, 0x8a.U,\n 0xab.U, 0xa8.U, 0xad.U, 0xae.U, 0xa7.U, 0xa4.U, 0xa1.U, 0xa2.U, 0xb3.U, 0xb0.U, 0xb5.U, 0xb6.U, 0xbf.U, 0xbc.U, 0xb9.U, 0xba.U,\n 0xfb.U, 0xf8.U, 0xfd.U, 0xfe.U, 0xf7.U, 0xf4.U, 0xf1.U, 0xf2.U, 0xe3.U, 0xe0.U, 0xe5.U, 0xe6.U, 0xef.U, 0xec.U, 0xe9.U, 0xea.U,\n 0xcb.U, 0xc8.U, 0xcd.U, 0xce.U, 0xc7.U, 0xc4.U, 0xc1.U, 0xc2.U, 0xd3.U, 0xd0.U, 0xd5.U, 0xd6.U, 0xdf.U, 0xdc.U, 0xd9.U, 0xda.U,\n 0x5b.U, 0x58.U, 0x5d.U, 0x5e.U, 0x57.U, 0x54.U, 0x51.U, 0x52.U, 0x43.U, 0x40.U, 0x45.U, 0x46.U, 0x4f.U, 0x4c.U, 0x49.U, 0x4a.U,\n 0x6b.U, 0x68.U, 0x6d.U, 0x6e.U, 0x67.U, 0x64.U, 0x61.U, 0x62.U, 0x73.U, 0x70.U, 0x75.U, 0x76.U, 0x7f.U, 0x7c.U, 0x79.U, 0x7a.U,\n 0x3b.U, 0x38.U, 0x3d.U, 0x3e.U, 0x37.U, 0x34.U, 0x31.U, 0x32.U, 0x23.U, 0x20.U, 0x25.U, 0x26.U, 0x2f.U, 0x2c.U, 0x29.U, 0x2a.U,\n 0x0b.U, 0x08.U, 0x0d.U, 0x0e.U, 0x07.U, 0x04.U, 0x01.U, 0x02.U, 0x13.U, 0x10.U, 0x15.U, 0x16.U, 0x1f.U, 0x1c.U, 0x19.U, 0x1a.U))\n\n /*\n val mul09 = VecInit(Array(\n 0x00.U, 0x09.U, 0x12.U, 0x1b.U, 0x24.U, 0x2d.U, 0x36.U, 0x3f.U, 0x48.U, 0x41.U, 0x5a.U, 0x53.U, 0x6c.U, 0x65.U, 0x7e.U, 0x77.U,\n 0x90.U, 0x99.U, 0x82.U, 0x8b.U, 0xb4.U, 0xbd.U, 0xa6.U, 0xaf.U, 0xd8.U, 0xd1.U, 0xca.U, 0xc3.U, 0xfc.U, 0xf5.U, 0xee.U, 0xe7.U,\n 0x3b.U, 0x32.U, 0x29.U, 0x20.U, 0x1f.U, 0x16.U, 0x0d.U, 0x04.U, 0x73.U, 0x7a.U, 0x61.U, 0x68.U, 0x57.U, 0x5e.U, 0x45.U, 0x4c.U,\n 0xab.U, 0xa2.U, 0xb9.U, 0xb0.U, 0x8f.U, 0x86.U, 0x9d.U, 0x94.U, 0xe3.U, 0xea.U, 0xf1.U, 0xf8.U, 0xc7.U, 0xce.U, 0xd5.U, 0xdc.U,\n 0x76.U, 0x7f.U, 0x64.U, 0x6d.U, 0x52.U, 0x5b.U, 0x40.U, 0x49.U, 0x3e.U, 0x37.U, 0x2c.U, 0x25.U, 0x1a.U, 0x13.U, 0x08.U, 0x01.U,\n 0xe6.U, 0xef.U, 0xf4.U, 0xfd.U, 0xc2.U, 0xcb.U, 0xd0.U, 0xd9.U, 0xae.U, 0xa7.U, 0xbc.U, 0xb5.U, 0x8a.U, 0x83.U, 0x98.U, 0x91.U,\n 0x4d.U, 0x44.U, 0x5f.U, 0x56.U, 0x69.U, 0x60.U, 0x7b.U, 0x72.U, 0x05.U, 0x0c.U, 0x17.U, 0x1e.U, 0x21.U, 0x28.U, 0x33.U, 0x3a.U,\n 0xdd.U, 0xd4.U, 0xcf.U, 0xc6.U, 0xf9.U, 0xf0.U, 0xeb.U, 0xe2.U, 0x95.U, 0x9c.U, 0x87.U, 0x8e.U, 0xb1.U, 0xb8.U, 0xa3.U, 0xaa.U,\n 0xec.U, 0xe5.U, 0xfe.U, 0xf7.U, 0xc8.U, 0xc1.U, 0xda.U, 0xd3.U, 0xa4.U, 0xad.U, 0xb6.U, 0xbf.U, 0x80.U, 0x89.U, 0x92.U, 0x9b.U,\n 0x7c.U, 0x75.U, 0x6e.U, 0x67.U, 0x58.U, 0x51.U, 0x4a.U, 0x43.U, 0x34.U, 0x3d.U, 0x26.U, 0x2f.U, 0x10.U, 0x19.U, 0x02.U, 0x0b.U,\n 0xd7.U, 0xde.U, 0xc5.U, 0xcc.U, 0xf3.U, 0xfa.U, 0xe1.U, 0xe8.U, 0x9f.U, 0x96.U, 0x8d.U, 0x84.U, 0xbb.U, 0xb2.U, 0xa9.U, 0xa0.U,\n 0x47.U, 0x4e.U, 0x55.U, 0x5c.U, 0x63.U, 0x6a.U, 0x71.U, 0x78.U, 0x0f.U, 0x06.U, 0x1d.U, 0x14.U, 0x2b.U, 0x22.U, 0x39.U, 0x30.U,\n 0x9a.U, 0x93.U, 0x88.U, 0x81.U, 0xbe.U, 0xb7.U, 0xac.U, 0xa5.U, 0xd2.U, 0xdb.U, 0xc0.U, 0xc9.U, 0xf6.U, 0xff.U, 0xe4.U, 0xed.U,\n 0x0a.U, 0x03.U, 0x18.U, 0x11.U, 0x2e.U, 0x27.U, 0x3c.U, 0x35.U, 0x42.U, 0x4b.U, 0x50.U, 0x59.U, 0x66.U, 0x6f.U, 0x74.U, 0x7d.U,\n 0xa1.U, 0xa8.U, 0xb3.U, 0xba.U, 0x85.U, 0x8c.U, 0x97.U, 0x9e.U, 0xe9.U, 0xe0.U, 0xfb.U, 0xf2.U, 0xcd.U, 0xc4.U, 0xdf.U, 0xd6.U,\n 0x31.U, 0x38.U, 0x23.U, 0x2a.U, 0x15.U, 0x1c.U, 0x07.U, 0x0e.U, 0x79.U, 0x70.U, 0x6b.U, 0x62.U, 0x5d.U, 0x54.U, 0x4f.U, 0x46.U))\n\n val mul11 = VecInit(Array(\n 0x00.U, 0x0b.U, 0x16.U, 0x1d.U, 0x2c.U, 0x27.U, 0x3a.U, 0x31.U, 0x58.U, 0x53.U, 0x4e.U, 0x45.U, 0x74.U, 0x7f.U, 0x62.U, 0x69.U,\n 0xb0.U, 0xbb.U, 0xa6.U, 0xad.U, 0x9c.U, 0x97.U, 0x8a.U, 0x81.U, 0xe8.U, 0xe3.U, 0xfe.U, 0xf5.U, 0xc4.U, 0xcf.U, 0xd2.U, 0xd9.U,\n 0x7b.U, 0x70.U, 0x6d.U, 0x66.U, 0x57.U, 0x5c.U, 0x41.U, 0x4a.U, 0x23.U, 0x28.U, 0x35.U, 0x3e.U, 0x0f.U, 0x04.U, 0x19.U, 0x12.U,\n 0xcb.U, 0xc0.U, 0xdd.U, 0xd6.U, 0xe7.U, 0xec.U, 0xf1.U, 0xfa.U, 0x93.U, 0x98.U, 0x85.U, 0x8e.U, 0xbf.U, 0xb4.U, 0xa9.U, 0xa2.U,\n 0xf6.U, 0xfd.U, 0xe0.U, 0xeb.U, 0xda.U, 0xd1.U, 0xcc.U, 0xc7.U, 0xae.U, 0xa5.U, 0xb8.U, 0xb3.U, 0x82.U, 0x89.U, 0x94.U, 0x9f.U,\n 0x46.U, 0x4d.U, 0x50.U, 0x5b.U, 0x6a.U, 0x61.U, 0x7c.U, 0x77.U, 0x1e.U, 0x15.U, 0x08.U, 0x03.U, 0x32.U, 0x39.U, 0x24.U, 0x2f.U,\n 0x8d.U, 0x86.U, 0x9b.U, 0x90.U, 0xa1.U, 0xaa.U, 0xb7.U, 0xbc.U, 0xd5.U, 0xde.U, 0xc3.U, 0xc8.U, 0xf9.U, 0xf2.U, 0xef.U, 0xe4.U,\n 0x3d.U, 0x36.U, 0x2b.U, 0x20.U, 0x11.U, 0x1a.U, 0x07.U, 0x0c.U, 0x65.U, 0x6e.U, 0x73.U, 0x78.U, 0x49.U, 0x42.U, 0x5f.U, 0x54.U,\n 0xf7.U, 0xfc.U, 0xe1.U, 0xea.U, 0xdb.U, 0xd0.U, 0xcd.U, 0xc6.U, 0xaf.U, 0xa4.U, 0xb9.U, 0xb2.U, 0x83.U, 0x88.U, 0x95.U, 0x9e.U,\n 0x47.U, 0x4c.U, 0x51.U, 0x5a.U, 0x6b.U, 0x60.U, 0x7d.U, 0x76.U, 0x1f.U, 0x14.U, 0x09.U, 0x02.U, 0x33.U, 0x38.U, 0x25.U, 0x2e.U,\n 0x8c.U, 0x87.U, 0x9a.U, 0x91.U, 0xa0.U, 0xab.U, 0xb6.U, 0xbd.U, 0xd4.U, 0xdf.U, 0xc2.U, 0xc9.U, 0xf8.U, 0xf3.U, 0xee.U, 0xe5.U,\n 0x3c.U, 0x37.U, 0x2a.U, 0x21.U, 0x10.U, 0x1b.U, 0x06.U, 0x0d.U, 0x64.U, 0x6f.U, 0x72.U, 0x79.U, 0x48.U, 0x43.U, 0x5e.U, 0x55.U,\n 0x01.U, 0x0a.U, 0x17.U, 0x1c.U, 0x2d.U, 0x26.U, 0x3b.U, 0x30.U, 0x59.U, 0x52.U, 0x4f.U, 0x44.U, 0x75.U, 0x7e.U, 0x63.U, 0x68.U,\n 0xb1.U, 0xba.U, 0xa7.U, 0xac.U, 0x9d.U, 0x96.U, 0x8b.U, 0x80.U, 0xe9.U, 0xe2.U, 0xff.U, 0xf4.U, 0xc5.U, 0xce.U, 0xd3.U, 0xd8.U,\n 0x7a.U, 0x71.U, 0x6c.U, 0x67.U, 0x56.U, 0x5d.U, 0x40.U, 0x4b.U, 0x22.U, 0x29.U, 0x34.U, 0x3f.U, 0x0e.U, 0x05.U, 0x18.U, 0x13.U,\n 0xca.U, 0xc1.U, 0xdc.U, 0xd7.U, 0xe6.U, 0xed.U, 0xf0.U, 0xfb.U, 0x92.U, 0x99.U, 0x84.U, 0x8f.U, 0xbe.U, 0xb5.U, 0xa8.U, 0xa3.U))\n\n val mul13 = VecInit(Array(\n 0x00.U, 0x0d.U, 0x1a.U, 0x17.U, 0x34.U, 0x39.U, 0x2e.U, 0x23.U, 0x68.U, 0x65.U, 0x72.U, 0x7f.U, 0x5c.U, 0x51.U, 0x46.U, 0x4b.U,\n 0xd0.U, 0xdd.U, 0xca.U, 0xc7.U, 0xe4.U, 0xe9.U, 0xfe.U, 0xf3.U, 0xb8.U, 0xb5.U, 0xa2.U, 0xaf.U, 0x8c.U, 0x81.U, 0x96.U, 0x9b.U,\n 0xbb.U, 0xb6.U, 0xa1.U, 0xac.U, 0x8f.U, 0x82.U, 0x95.U, 0x98.U, 0xd3.U, 0xde.U, 0xc9.U, 0xc4.U, 0xe7.U, 0xea.U, 0xfd.U, 0xf0.U,\n 0x6b.U, 0x66.U, 0x71.U, 0x7c.U, 0x5f.U, 0x52.U, 0x45.U, 0x48.U, 0x03.U, 0x0e.U, 0x19.U, 0x14.U, 0x37.U, 0x3a.U, 0x2d.U, 0x20.U,\n 0x6d.U, 0x60.U, 0x77.U, 0x7a.U, 0x59.U, 0x54.U, 0x43.U, 0x4e.U, 0x05.U, 0x08.U, 0x1f.U, 0x12.U, 0x31.U, 0x3c.U, 0x2b.U, 0x26.U,\n 0xbd.U, 0xb0.U, 0xa7.U, 0xaa.U, 0x89.U, 0x84.U, 0x93.U, 0x9e.U, 0xd5.U, 0xd8.U, 0xcf.U, 0xc2.U, 0xe1.U, 0xec.U, 0xfb.U, 0xf6.U,\n 0xd6.U, 0xdb.U, 0xcc.U, 0xc1.U, 0xe2.U, 0xef.U, 0xf8.U, 0xf5.U, 0xbe.U, 0xb3.U, 0xa4.U, 0xa9.U, 0x8a.U, 0x87.U, 0x90.U, 0x9d.U,\n 0x06.U, 0x0b.U, 0x1c.U, 0x11.U, 0x32.U, 0x3f.U, 0x28.U, 0x25.U, 0x6e.U, 0x63.U, 0x74.U, 0x79.U, 0x5a.U, 0x57.U, 0x40.U, 0x4d.U,\n 0xda.U, 0xd7.U, 0xc0.U, 0xcd.U, 0xee.U, 0xe3.U, 0xf4.U, 0xf9.U, 0xb2.U, 0xbf.U, 0xa8.U, 0xa5.U, 0x86.U, 0x8b.U, 0x9c.U, 0x91.U,\n 0x0a.U, 0x07.U, 0x10.U, 0x1d.U, 0x3e.U, 0x33.U, 0x24.U, 0x29.U, 0x62.U, 0x6f.U, 0x78.U, 0x75.U, 0x56.U, 0x5b.U, 0x4c.U, 0x41.U,\n 0x61.U, 0x6c.U, 0x7b.U, 0x76.U, 0x55.U, 0x58.U, 0x4f.U, 0x42.U, 0x09.U, 0x04.U, 0x13.U, 0x1e.U, 0x3d.U, 0x30.U, 0x27.U, 0x2a.U,\n 0xb1.U, 0xbc.U, 0xab.U, 0xa6.U, 0x85.U, 0x88.U, 0x9f.U, 0x92.U, 0xd9.U, 0xd4.U, 0xc3.U, 0xce.U, 0xed.U, 0xe0.U, 0xf7.U, 0xfa.U,\n 0xb7.U, 0xba.U, 0xad.U, 0xa0.U, 0x83.U, 0x8e.U, 0x99.U, 0x94.U, 0xdf.U, 0xd2.U, 0xc5.U, 0xc8.U, 0xeb.U, 0xe6.U, 0xf1.U, 0xfc.U,\n 0x67.U, 0x6a.U, 0x7d.U, 0x70.U, 0x53.U, 0x5e.U, 0x49.U, 0x44.U, 0x0f.U, 0x02.U, 0x15.U, 0x18.U, 0x3b.U, 0x36.U, 0x21.U, 0x2c.U,\n 0x0c.U, 0x01.U, 0x16.U, 0x1b.U, 0x38.U, 0x35.U, 0x22.U, 0x2f.U, 0x64.U, 0x69.U, 0x7e.U, 0x73.U, 0x50.U, 0x5d.U, 0x4a.U, 0x47.U,\n 0xdc.U, 0xd1.U, 0xc6.U, 0xcb.U, 0xe8.U, 0xe5.U, 0xf2.U, 0xff.U, 0xb4.U, 0xb9.U, 0xae.U, 0xa3.U, 0x80.U, 0x8d.U, 0x9a.U, 0x97.U))\n\n val mul14 = VecInit(Array(\n 0x00.U, 0x0e.U, 0x1c.U, 0x12.U, 0x38.U, 0x36.U, 0x24.U, 0x2a.U, 0x70.U, 0x7e.U, 0x6c.U, 0x62.U, 0x48.U, 0x46.U, 0x54.U, 0x5a.U,\n 0xe0.U, 0xee.U, 0xfc.U, 0xf2.U, 0xd8.U, 0xd6.U, 0xc4.U, 0xca.U, 0x90.U, 0x9e.U, 0x8c.U, 0x82.U, 0xa8.U, 0xa6.U, 0xb4.U, 0xba.U,\n 0xdb.U, 0xd5.U, 0xc7.U, 0xc9.U, 0xe3.U, 0xed.U, 0xff.U, 0xf1.U, 0xab.U, 0xa5.U, 0xb7.U, 0xb9.U, 0x93.U, 0x9d.U, 0x8f.U, 0x81.U,\n 0x3b.U, 0x35.U, 0x27.U, 0x29.U, 0x03.U, 0x0d.U, 0x1f.U, 0x11.U, 0x4b.U, 0x45.U, 0x57.U, 0x59.U, 0x73.U, 0x7d.U, 0x6f.U, 0x61.U,\n 0xad.U, 0xa3.U, 0xb1.U, 0xbf.U, 0x95.U, 0x9b.U, 0x89.U, 0x87.U, 0xdd.U, 0xd3.U, 0xc1.U, 0xcf.U, 0xe5.U, 0xeb.U, 0xf9.U, 0xf7.U,\n 0x4d.U, 0x43.U, 0x51.U, 0x5f.U, 0x75.U, 0x7b.U, 0x69.U, 0x67.U, 0x3d.U, 0x33.U, 0x21.U, 0x2f.U, 0x05.U, 0x0b.U, 0x19.U, 0x17.U,\n 0x76.U, 0x78.U, 0x6a.U, 0x64.U, 0x4e.U, 0x40.U, 0x52.U, 0x5c.U, 0x06.U, 0x08.U, 0x1a.U, 0x14.U, 0x3e.U, 0x30.U, 0x22.U, 0x2c.U,\n 0x96.U, 0x98.U, 0x8a.U, 0x84.U, 0xae.U, 0xa0.U, 0xb2.U, 0xbc.U, 0xe6.U, 0xe8.U, 0xfa.U, 0xf4.U, 0xde.U, 0xd0.U, 0xc2.U, 0xcc.U,\n 0x41.U, 0x4f.U, 0x5d.U, 0x53.U, 0x79.U, 0x77.U, 0x65.U, 0x6b.U, 0x31.U, 0x3f.U, 0x2d.U, 0x23.U, 0x09.U, 0x07.U, 0x15.U, 0x1b.U,\n 0xa1.U, 0xaf.U, 0xbd.U, 0xb3.U, 0x99.U, 0x97.U, 0x85.U, 0x8b.U, 0xd1.U, 0xdf.U, 0xcd.U, 0xc3.U, 0xe9.U, 0xe7.U, 0xf5.U, 0xfb.U,\n 0x9a.U, 0x94.U, 0x86.U, 0x88.U, 0xa2.U, 0xac.U, 0xbe.U, 0xb0.U, 0xea.U, 0xe4.U, 0xf6.U, 0xf8.U, 0xd2.U, 0xdc.U, 0xce.U, 0xc0.U,\n 0x7a.U, 0x74.U, 0x66.U, 0x68.U, 0x42.U, 0x4c.U, 0x5e.U, 0x50.U, 0x0a.U, 0x04.U, 0x16.U, 0x18.U, 0x32.U, 0x3c.U, 0x2e.U, 0x20.U,\n 0xec.U, 0xe2.U, 0xf0.U, 0xfe.U, 0xd4.U, 0xda.U, 0xc8.U, 0xc6.U, 0x9c.U, 0x92.U, 0x80.U, 0x8e.U, 0xa4.U, 0xaa.U, 0xb8.U, 0xb6.U,\n 0x0c.U, 0x02.U, 0x10.U, 0x1e.U, 0x34.U, 0x3a.U, 0x28.U, 0x26.U, 0x7c.U, 0x72.U, 0x60.U, 0x6e.U, 0x44.U, 0x4a.U, 0x58.U, 0x56.U,\n 0x37.U, 0x39.U, 0x2b.U, 0x25.U, 0x0f.U, 0x01.U, 0x13.U, 0x1d.U, 0x47.U, 0x49.U, 0x5b.U, 0x55.U, 0x7f.U, 0x71.U, 0x63.U, 0x6d.U,\n 0xd7.U, 0xd9.U, 0xcb.U, 0xc5.U, 0xef.U, 0xe1.U, 0xf3.U, 0xfd.U, 0xa7.U, 0xa9.U, 0xbb.U, 0xb5.U, 0x9f.U, 0x91.U, 0x83.U, 0x8d.U))\n*/\n val tmp_state = Wire(Vec(Params.StateLength, UInt(8.W)))\n\n tmp_state(0) := mul02(io.state_in(0)) ^ mul03(io.state_in(1)) ^ io.state_in(2) ^ io.state_in(3)\n tmp_state(1) := io.state_in(0) ^ mul02(io.state_in(1)) ^ mul03(io.state_in(2)) ^ io.state_in(3)\n tmp_state(2) := io.state_in(0) ^ io.state_in(1) ^ mul02(io.state_in(2)) ^ mul03(io.state_in(3))\n tmp_state(3) := mul03(io.state_in(0)) ^ io.state_in(1) ^ io.state_in(2) ^ mul02(io.state_in(3))\n\n tmp_state(4) := mul02(io.state_in(4)) ^ mul03(io.state_in(5)) ^ io.state_in(6) ^ io.state_in(7)\n tmp_state(5) := io.state_in(4) ^ mul02(io.state_in(5)) ^ mul03(io.state_in(6)) ^ io.state_in(7)\n tmp_state(6) := io.state_in(4) ^ io.state_in(5) ^ mul02(io.state_in(6)) ^ mul03(io.state_in(7))\n tmp_state(7) := mul03(io.state_in(4)) ^ io.state_in(5) ^ io.state_in(6) ^ mul02(io.state_in(7))\n\n tmp_state(8) := mul02(io.state_in(8)) ^ mul03(io.state_in(9)) ^ io.state_in(10) ^ io.state_in(11)\n tmp_state(9) := io.state_in(8) ^ mul02(io.state_in(9)) ^ mul03(io.state_in(10)) ^ io.state_in(11)\n tmp_state(10) := io.state_in(8) ^ io.state_in(9) ^ mul02(io.state_in(10)) ^ mul03(io.state_in(11))\n tmp_state(11) := mul03(io.state_in(8)) ^ io.state_in(9) ^ io.state_in(10) ^ mul02(io.state_in(11))\n\n tmp_state(12) := mul02(io.state_in(12)) ^ mul03(io.state_in(13)) ^ io.state_in(14) ^ io.state_in(15)\n tmp_state(13) := io.state_in(12) ^ mul02(io.state_in(13)) ^ mul03(io.state_in(14)) ^ io.state_in(15)\n tmp_state(14) := io.state_in(12) ^ io.state_in(13) ^ mul02(io.state_in(14)) ^ mul03(io.state_in(15))\n tmp_state(15) := mul03(io.state_in(12)) ^ io.state_in(13) ^ io.state_in(14) ^ mul02(io.state_in(15))\n\n if (Pipelined) {\n io.state_out := ShiftRegister(tmp_state, 1)\n } else {\n io.state_out := tmp_state\n }\n}\n\nobject MixColumns {\n", "right_context": "}", "groundtruth": " def apply(Pipelined: Boolean = false): MixColumns = Module(new MixColumns(Pipelined))\n", "crossfile_context": ""}
{"task_id": "aes_chisel", "path": "aes_chisel/src/main/scala/aes/Tables.scala", "left_context": "package aes\n\nimport chisel3._\n\n// This module is not used and the file can be deleted.\n// Rather than having the tables together in a large ROM\n// it was simpler to have them distributed in the modules where they are used\n\nobject Tables {\n val s_box = VecInit(Array(\n 0x63.U, 0x7c.U, 0x77.U, 0x7b.U, 0xf2.U, 0x6b.U, 0x6f.U, 0xc5.U, 0x30.U, 0x01.U, 0x67.U, 0x2b.U, 0xfe.U, 0xd7.U, 0xab.U, 0x76.U,\n 0xca.U, 0x82.U, 0xc9.U, 0x7d.U, 0xfa.U, 0x59.U, 0x47.U, 0xf0.U, 0xad.U, 0xd4.U, 0xa2.U, 0xaf.U, 0x9c.U, 0xa4.U, 0x72.U, 0xc0.U,\n 0xb7.U, 0xfd.U, 0x93.U, 0x26.U, 0x36.U, 0x3f.U, 0xf7.U, 0xcc.U, 0x34.U, 0xa5.U, 0xe5.U, 0xf1.U, 0x71.U, 0xd8.U, 0x31.U, 0x15.U,\n 0x04.U, 0xc7.U, 0x23.U, 0xc3.U, 0x18.U, 0x96.U, 0x05.U, 0x9a.U, 0x07.U, 0x12.U, 0x80.U, 0xe2.U, 0xeb.U, 0x27.U, 0xb2.U, 0x75.U,\n 0x09.U, 0x83.U, 0x2c.U, 0x1a.U, 0x1b.U, 0x6e.U, 0x5a.U, 0xa0.U, 0x52.U, 0x3b.U, 0xd6.U, 0xb3.U, 0x29.U, 0xe3.U, 0x2f.U, 0x84.U,\n 0x53.U, 0xd1.U, 0x00.U, 0xed.U, 0x20.U, 0xfc.U, 0xb1.U, 0x5b.U, 0x6a.U, 0xcb.U, 0xbe.U, 0x39.U, 0x4a.U, 0x4c.U, 0x58.U, 0xcf.U,\n 0xd0.U, 0xef.U, 0xaa.U, 0xfb.U, 0x43.U, 0x4d.U, 0x33.U, 0x85.U, 0x45.U, 0xf9.U, 0x02.U, 0x7f.U, 0x50.U, 0x3c.U, 0x9f.U, 0xa8.U,\n 0x51.U, 0xa3.U, 0x40.U, 0x8f.U, 0x92.U, 0x9d.U, 0x38.U, 0xf5.U, 0xbc.U, 0xb6.U, 0xda.U, 0x21.U, 0x10.U, 0xff.U, 0xf3.U, 0xd2.U,\n 0xcd.U, 0x0c.U, 0x13.U, 0xec.U, 0x5f.U, 0x97.U, 0x44.U, 0x17.U, 0xc4.U, 0xa7.U, 0x7e.U, 0x3d.U, 0x64.U, 0x5d.U, 0x19.U, 0x73.U,\n 0x60.U, 0x81.U, 0x4f.U, 0xdc.U, 0x22.U, 0x2a.U, 0x90.U, 0x88.U, 0x46.U, 0xee.U, 0xb8.U, 0x14.U, 0xde.U, 0x5e.U, 0x0b.U, 0xdb.U,\n 0xe0.U, 0x32.U, 0x3a.U, 0x0a.U, 0x49.U, 0x06.U, 0x24.U, 0x5c.U, 0xc2.U, 0xd3.U, 0xac.U, 0x62.U, 0x91.U, 0x95.U, 0xe4.U, 0x79.U,\n 0xe7.U, 0xc8.U, 0x37.U, 0x6d.U, 0x8d.U, 0xd5.U, 0x4e.U, 0xa9.U, 0x6c.U, 0x56.U, 0xf4.U, 0xea.U, 0x65.U, 0x7a.U, 0xae.U, 0x08.U,\n 0xba.U, 0x78.U, 0x25.U, 0x2e.U, 0x1c.U, 0xa6.U, 0xb4.U, 0xc6.U, 0xe8.U, 0xdd.U, 0x74.U, 0x1f.U, 0x4b.U, 0xbd.U, 0x8b.U, 0x8a.U,\n 0x70.U, 0x3e.U, 0xb5.U, 0x66.U, 0x48.U, 0x03.U, 0xf6.U, 0x0e.U, 0x61.U, 0x35.U, 0x57.U, 0xb9.U, 0x86.U, 0xc1.U, 0x1d.U, 0x9e.U,\n", "right_context": " 0x7c.U, 0xe3.U, 0x39.U, 0x82.U, 0x9b.U, 0x2f.U, 0xff.U, 0x87.U, 0x34.U, 0x8e.U, 0x43.U, 0x44.U, 0xc4.U, 0xde.U, 0xe9.U, 0xcb.U,\n 0x54.U, 0x7b.U, 0x94.U, 0x32.U, 0xa6.U, 0xc2.U, 0x23.U, 0x3d.U, 0xee.U, 0x4c.U, 0x95.U, 0x0b.U, 0x42.U, 0xfa.U, 0xc3.U, 0x4e.U,\n 0x08.U, 0x2e.U, 0xa1.U, 0x66.U, 0x28.U, 0xd9.U, 0x24.U, 0xb2.U, 0x76.U, 0x5b.U, 0xa2.U, 0x49.U, 0x6d.U, 0x8b.U, 0xd1.U, 0x25.U,\n 0x72.U, 0xf8.U, 0xf6.U, 0x64.U, 0x86.U, 0x68.U, 0x98.U, 0x16.U, 0xd4.U, 0xa4.U, 0x5c.U, 0xcc.U, 0x5d.U, 0x65.U, 0xb6.U, 0x92.U,\n 0x6c.U, 0x70.U, 0x48.U, 0x50.U, 0xfd.U, 0xed.U, 0xb9.U, 0xda.U, 0x5e.U, 0x15.U, 0x46.U, 0x57.U, 0xa7.U, 0x8d.U, 0x9d.U, 0x84.U,\n 0x90.U, 0xd8.U, 0xab.U, 0x00.U, 0x8c.U, 0xbc.U, 0xd3.U, 0x0a.U, 0xf7.U, 0xe4.U, 0x58.U, 0x05.U, 0xb8.U, 0xb3.U, 0x45.U, 0x06.U,\n 0xd0.U, 0x2c.U, 0x1e.U, 0x8f.U, 0xca.U, 0x3f.U, 0x0f.U, 0x02.U, 0xc1.U, 0xaf.U, 0xbd.U, 0x03.U, 0x01.U, 0x13.U, 0x8a.U, 0x6b.U,\n 0x3a.U, 0x91.U, 0x11.U, 0x41.U, 0x4f.U, 0x67.U, 0xdc.U, 0xea.U, 0x97.U, 0xf2.U, 0xcf.U, 0xce.U, 0xf0.U, 0xb4.U, 0xe6.U, 0x73.U,\n 0x96.U, 0xac.U, 0x74.U, 0x22.U, 0xe7.U, 0xad.U, 0x35.U, 0x85.U, 0xe2.U, 0xf9.U, 0x37.U, 0xe8.U, 0x1c.U, 0x75.U, 0xdf.U, 0x6e.U,\n 0x47.U, 0xf1.U, 0x1a.U, 0x71.U, 0x1d.U, 0x29.U, 0xc5.U, 0x89.U, 0x6f.U, 0xb7.U, 0x62.U, 0x0e.U, 0xaa.U, 0x18.U, 0xbe.U, 0x1b.U,\n 0xfc.U, 0x56.U, 0x3e.U, 0x4b.U, 0xc6.U, 0xd2.U, 0x79.U, 0x20.U, 0x9a.U, 0xdb.U, 0xc0.U, 0xfe.U, 0x78.U, 0xcd.U, 0x5a.U, 0xf4.U,\n 0x1f.U, 0xdd.U, 0xa8.U, 0x33.U, 0x88.U, 0x07.U, 0xc7.U, 0x31.U, 0xb1.U, 0x12.U, 0x10.U, 0x59.U, 0x27.U, 0x80.U, 0xec.U, 0x5f.U,\n 0x60.U, 0x51.U, 0x7f.U, 0xa9.U, 0x19.U, 0xb5.U, 0x4a.U, 0x0d.U, 0x2d.U, 0xe5.U, 0x7a.U, 0x9f.U, 0x93.U, 0xc9.U, 0x9c.U, 0xef.U,\n 0xa0.U, 0xe0.U, 0x3b.U, 0x4d.U, 0xae.U, 0x2a.U, 0xf5.U, 0xb0.U, 0xc8.U, 0xeb.U, 0xbb.U, 0x3c.U, 0x83.U, 0x53.U, 0x99.U, 0x61.U,\n 0x17.U, 0x2b.U, 0x04.U, 0x7e.U, 0xba.U, 0x77.U, 0xd6.U, 0x26.U, 0xe1.U, 0x69.U, 0x14.U, 0x63.U, 0x55.U, 0x21.U, 0x0c.U, 0x7d.U))\n\n val mul02 = VecInit(Array(\n 0x00.U, 0x02.U, 0x04.U, 0x06.U, 0x08.U, 0x0a.U, 0x0c.U, 0x0e.U, 0x10.U, 0x12.U, 0x14.U, 0x16.U, 0x18.U, 0x1a.U, 0x1c.U, 0x1e.U,\n 0x20.U, 0x22.U, 0x24.U, 0x26.U, 0x28.U, 0x2a.U, 0x2c.U, 0x2e.U, 0x30.U, 0x32.U, 0x34.U, 0x36.U, 0x38.U, 0x3a.U, 0x3c.U, 0x3e.U,\n 0x40.U, 0x42.U, 0x44.U, 0x46.U, 0x48.U, 0x4a.U, 0x4c.U, 0x4e.U, 0x50.U, 0x52.U, 0x54.U, 0x56.U, 0x58.U, 0x5a.U, 0x5c.U, 0x5e.U,\n 0x60.U, 0x62.U, 0x64.U, 0x66.U, 0x68.U, 0x6a.U, 0x6c.U, 0x6e.U, 0x70.U, 0x72.U, 0x74.U, 0x76.U, 0x78.U, 0x7a.U, 0x7c.U, 0x7e.U,\n 0x80.U, 0x82.U, 0x84.U, 0x86.U, 0x88.U, 0x8a.U, 0x8c.U, 0x8e.U, 0x90.U, 0x92.U, 0x94.U, 0x96.U, 0x98.U, 0x9a.U, 0x9c.U, 0x9e.U,\n 0xa0.U, 0xa2.U, 0xa4.U, 0xa6.U, 0xa8.U, 0xaa.U, 0xac.U, 0xae.U, 0xb0.U, 0xb2.U, 0xb4.U, 0xb6.U, 0xb8.U, 0xba.U, 0xbc.U, 0xbe.U,\n 0xc0.U, 0xc2.U, 0xc4.U, 0xc6.U, 0xc8.U, 0xca.U, 0xcc.U, 0xce.U, 0xd0.U, 0xd2.U, 0xd4.U, 0xd6.U, 0xd8.U, 0xda.U, 0xdc.U, 0xde.U,\n 0xe0.U, 0xe2.U, 0xe4.U, 0xe6.U, 0xe8.U, 0xea.U, 0xec.U, 0xee.U, 0xf0.U, 0xf2.U, 0xf4.U, 0xf6.U, 0xf8.U, 0xfa.U, 0xfc.U, 0xfe.U,\n 0x1b.U, 0x19.U, 0x1f.U, 0x1d.U, 0x13.U, 0x11.U, 0x17.U, 0x15.U, 0x0b.U, 0x09.U, 0x0f.U, 0x0d.U, 0x03.U, 0x01.U, 0x07.U, 0x05.U,\n 0x3b.U, 0x39.U, 0x3f.U, 0x3d.U, 0x33.U, 0x31.U, 0x37.U, 0x35.U, 0x2b.U, 0x29.U, 0x2f.U, 0x2d.U, 0x23.U, 0x21.U, 0x27.U, 0x25.U,\n 0x5b.U, 0x59.U, 0x5f.U, 0x5d.U, 0x53.U, 0x51.U, 0x57.U, 0x55.U, 0x4b.U, 0x49.U, 0x4f.U, 0x4d.U, 0x43.U, 0x41.U, 0x47.U, 0x45.U,\n 0x7b.U, 0x79.U, 0x7f.U, 0x7d.U, 0x73.U, 0x71.U, 0x77.U, 0x75.U, 0x6b.U, 0x69.U, 0x6f.U, 0x6d.U, 0x63.U, 0x61.U, 0x67.U, 0x65.U,\n 0x9b.U, 0x99.U, 0x9f.U, 0x9d.U, 0x93.U, 0x91.U, 0x97.U, 0x95.U, 0x8b.U, 0x89.U, 0x8f.U, 0x8d.U, 0x83.U, 0x81.U, 0x87.U, 0x85.U,\n 0xbb.U, 0xb9.U, 0xbf.U, 0xbd.U, 0xb3.U, 0xb1.U, 0xb7.U, 0xb5.U, 0xab.U, 0xa9.U, 0xaf.U, 0xad.U, 0xa3.U, 0xa1.U, 0xa7.U, 0xa5.U,\n 0xdb.U, 0xd9.U, 0xdf.U, 0xdd.U, 0xd3.U, 0xd1.U, 0xd7.U, 0xd5.U, 0xcb.U, 0xc9.U, 0xcf.U, 0xcd.U, 0xc3.U, 0xc1.U, 0xc7.U, 0xc5.U,\n 0xfb.U, 0xf9.U, 0xff.U, 0xfd.U, 0xf3.U, 0xf1.U, 0xf7.U, 0xf5.U, 0xeb.U, 0xe9.U, 0xef.U, 0xed.U, 0xe3.U, 0xe1.U, 0xe7.U, 0xe5.U))\n\n val mul03 = VecInit(Array(\n 0x00.U, 0x03.U, 0x06.U, 0x05.U, 0x0c.U, 0x0f.U, 0x0a.U, 0x09.U, 0x18.U, 0x1b.U, 0x1e.U, 0x1d.U, 0x14.U, 0x17.U, 0x12.U, 0x11.U,\n 0x30.U, 0x33.U, 0x36.U, 0x35.U, 0x3c.U, 0x3f.U, 0x3a.U, 0x39.U, 0x28.U, 0x2b.U, 0x2e.U, 0x2d.U, 0x24.U, 0x27.U, 0x22.U, 0x21.U,\n 0x60.U, 0x63.U, 0x66.U, 0x65.U, 0x6c.U, 0x6f.U, 0x6a.U, 0x69.U, 0x78.U, 0x7b.U, 0x7e.U, 0x7d.U, 0x74.U, 0x77.U, 0x72.U, 0x71.U,\n 0x50.U, 0x53.U, 0x56.U, 0x55.U, 0x5c.U, 0x5f.U, 0x5a.U, 0x59.U, 0x48.U, 0x4b.U, 0x4e.U, 0x4d.U, 0x44.U, 0x47.U, 0x42.U, 0x41.U,\n 0xc0.U, 0xc3.U, 0xc6.U, 0xc5.U, 0xcc.U, 0xcf.U, 0xca.U, 0xc9.U, 0xd8.U, 0xdb.U, 0xde.U, 0xdd.U, 0xd4.U, 0xd7.U, 0xd2.U, 0xd1.U,\n 0xf0.U, 0xf3.U, 0xf6.U, 0xf5.U, 0xfc.U, 0xff.U, 0xfa.U, 0xf9.U, 0xe8.U, 0xeb.U, 0xee.U, 0xed.U, 0xe4.U, 0xe7.U, 0xe2.U, 0xe1.U,\n 0xa0.U, 0xa3.U, 0xa6.U, 0xa5.U, 0xac.U, 0xaf.U, 0xaa.U, 0xa9.U, 0xb8.U, 0xbb.U, 0xbe.U, 0xbd.U, 0xb4.U, 0xb7.U, 0xb2.U, 0xb1.U,\n 0x90.U, 0x93.U, 0x96.U, 0x95.U, 0x9c.U, 0x9f.U, 0x9a.U, 0x99.U, 0x88.U, 0x8b.U, 0x8e.U, 0x8d.U, 0x84.U, 0x87.U, 0x82.U, 0x81.U,\n 0x9b.U, 0x98.U, 0x9d.U, 0x9e.U, 0x97.U, 0x94.U, 0x91.U, 0x92.U, 0x83.U, 0x80.U, 0x85.U, 0x86.U, 0x8f.U, 0x8c.U, 0x89.U, 0x8a.U,\n 0xab.U, 0xa8.U, 0xad.U, 0xae.U, 0xa7.U, 0xa4.U, 0xa1.U, 0xa2.U, 0xb3.U, 0xb0.U, 0xb5.U, 0xb6.U, 0xbf.U, 0xbc.U, 0xb9.U, 0xba.U,\n 0xfb.U, 0xf8.U, 0xfd.U, 0xfe.U, 0xf7.U, 0xf4.U, 0xf1.U, 0xf2.U, 0xe3.U, 0xe0.U, 0xe5.U, 0xe6.U, 0xef.U, 0xec.U, 0xe9.U, 0xea.U,\n 0xcb.U, 0xc8.U, 0xcd.U, 0xce.U, 0xc7.U, 0xc4.U, 0xc1.U, 0xc2.U, 0xd3.U, 0xd0.U, 0xd5.U, 0xd6.U, 0xdf.U, 0xdc.U, 0xd9.U, 0xda.U,\n 0x5b.U, 0x58.U, 0x5d.U, 0x5e.U, 0x57.U, 0x54.U, 0x51.U, 0x52.U, 0x43.U, 0x40.U, 0x45.U, 0x46.U, 0x4f.U, 0x4c.U, 0x49.U, 0x4a.U,\n 0x6b.U, 0x68.U, 0x6d.U, 0x6e.U, 0x67.U, 0x64.U, 0x61.U, 0x62.U, 0x73.U, 0x70.U, 0x75.U, 0x76.U, 0x7f.U, 0x7c.U, 0x79.U, 0x7a.U,\n 0x3b.U, 0x38.U, 0x3d.U, 0x3e.U, 0x37.U, 0x34.U, 0x31.U, 0x32.U, 0x23.U, 0x20.U, 0x25.U, 0x26.U, 0x2f.U, 0x2c.U, 0x29.U, 0x2a.U,\n 0x0b.U, 0x08.U, 0x0d.U, 0x0e.U, 0x07.U, 0x04.U, 0x01.U, 0x02.U, 0x13.U, 0x10.U, 0x15.U, 0x16.U, 0x1f.U, 0x1c.U, 0x19.U, 0x1a.U))\n\n val mul09 = VecInit(Array(\n 0x00.U, 0x09.U, 0x12.U, 0x1b.U, 0x24.U, 0x2d.U, 0x36.U, 0x3f.U, 0x48.U, 0x41.U, 0x5a.U, 0x53.U, 0x6c.U, 0x65.U, 0x7e.U, 0x77.U,\n 0x90.U, 0x99.U, 0x82.U, 0x8b.U, 0xb4.U, 0xbd.U, 0xa6.U, 0xaf.U, 0xd8.U, 0xd1.U, 0xca.U, 0xc3.U, 0xfc.U, 0xf5.U, 0xee.U, 0xe7.U,\n 0x3b.U, 0x32.U, 0x29.U, 0x20.U, 0x1f.U, 0x16.U, 0x0d.U, 0x04.U, 0x73.U, 0x7a.U, 0x61.U, 0x68.U, 0x57.U, 0x5e.U, 0x45.U, 0x4c.U,\n 0xab.U, 0xa2.U, 0xb9.U, 0xb0.U, 0x8f.U, 0x86.U, 0x9d.U, 0x94.U, 0xe3.U, 0xea.U, 0xf1.U, 0xf8.U, 0xc7.U, 0xce.U, 0xd5.U, 0xdc.U,\n 0x76.U, 0x7f.U, 0x64.U, 0x6d.U, 0x52.U, 0x5b.U, 0x40.U, 0x49.U, 0x3e.U, 0x37.U, 0x2c.U, 0x25.U, 0x1a.U, 0x13.U, 0x08.U, 0x01.U,\n 0xe6.U, 0xef.U, 0xf4.U, 0xfd.U, 0xc2.U, 0xcb.U, 0xd0.U, 0xd9.U, 0xae.U, 0xa7.U, 0xbc.U, 0xb5.U, 0x8a.U, 0x83.U, 0x98.U, 0x91.U,\n 0x4d.U, 0x44.U, 0x5f.U, 0x56.U, 0x69.U, 0x60.U, 0x7b.U, 0x72.U, 0x05.U, 0x0c.U, 0x17.U, 0x1e.U, 0x21.U, 0x28.U, 0x33.U, 0x3a.U,\n 0xdd.U, 0xd4.U, 0xcf.U, 0xc6.U, 0xf9.U, 0xf0.U, 0xeb.U, 0xe2.U, 0x95.U, 0x9c.U, 0x87.U, 0x8e.U, 0xb1.U, 0xb8.U, 0xa3.U, 0xaa.U,\n 0xec.U, 0xe5.U, 0xfe.U, 0xf7.U, 0xc8.U, 0xc1.U, 0xda.U, 0xd3.U, 0xa4.U, 0xad.U, 0xb6.U, 0xbf.U, 0x80.U, 0x89.U, 0x92.U, 0x9b.U,\n 0x7c.U, 0x75.U, 0x6e.U, 0x67.U, 0x58.U, 0x51.U, 0x4a.U, 0x43.U, 0x34.U, 0x3d.U, 0x26.U, 0x2f.U, 0x10.U, 0x19.U, 0x02.U, 0x0b.U,\n 0xd7.U, 0xde.U, 0xc5.U, 0xcc.U, 0xf3.U, 0xfa.U, 0xe1.U, 0xe8.U, 0x9f.U, 0x96.U, 0x8d.U, 0x84.U, 0xbb.U, 0xb2.U, 0xa9.U, 0xa0.U,\n 0x47.U, 0x4e.U, 0x55.U, 0x5c.U, 0x63.U, 0x6a.U, 0x71.U, 0x78.U, 0x0f.U, 0x06.U, 0x1d.U, 0x14.U, 0x2b.U, 0x22.U, 0x39.U, 0x30.U,\n 0x9a.U, 0x93.U, 0x88.U, 0x81.U, 0xbe.U, 0xb7.U, 0xac.U, 0xa5.U, 0xd2.U, 0xdb.U, 0xc0.U, 0xc9.U, 0xf6.U, 0xff.U, 0xe4.U, 0xed.U,\n 0x0a.U, 0x03.U, 0x18.U, 0x11.U, 0x2e.U, 0x27.U, 0x3c.U, 0x35.U, 0x42.U, 0x4b.U, 0x50.U, 0x59.U, 0x66.U, 0x6f.U, 0x74.U, 0x7d.U,\n 0xa1.U, 0xa8.U, 0xb3.U, 0xba.U, 0x85.U, 0x8c.U, 0x97.U, 0x9e.U, 0xe9.U, 0xe0.U, 0xfb.U, 0xf2.U, 0xcd.U, 0xc4.U, 0xdf.U, 0xd6.U,\n 0x31.U, 0x38.U, 0x23.U, 0x2a.U, 0x15.U, 0x1c.U, 0x07.U, 0x0e.U, 0x79.U, 0x70.U, 0x6b.U, 0x62.U, 0x5d.U, 0x54.U, 0x4f.U, 0x46.U))\n\n val mul11 = VecInit(Array(\n 0x00.U, 0x0b.U, 0x16.U, 0x1d.U, 0x2c.U, 0x27.U, 0x3a.U, 0x31.U, 0x58.U, 0x53.U, 0x4e.U, 0x45.U, 0x74.U, 0x7f.U, 0x62.U, 0x69.U,\n 0xb0.U, 0xbb.U, 0xa6.U, 0xad.U, 0x9c.U, 0x97.U, 0x8a.U, 0x81.U, 0xe8.U, 0xe3.U, 0xfe.U, 0xf5.U, 0xc4.U, 0xcf.U, 0xd2.U, 0xd9.U,\n 0x7b.U, 0x70.U, 0x6d.U, 0x66.U, 0x57.U, 0x5c.U, 0x41.U, 0x4a.U, 0x23.U, 0x28.U, 0x35.U, 0x3e.U, 0x0f.U, 0x04.U, 0x19.U, 0x12.U,\n 0xcb.U, 0xc0.U, 0xdd.U, 0xd6.U, 0xe7.U, 0xec.U, 0xf1.U, 0xfa.U, 0x93.U, 0x98.U, 0x85.U, 0x8e.U, 0xbf.U, 0xb4.U, 0xa9.U, 0xa2.U,\n 0xf6.U, 0xfd.U, 0xe0.U, 0xeb.U, 0xda.U, 0xd1.U, 0xcc.U, 0xc7.U, 0xae.U, 0xa5.U, 0xb8.U, 0xb3.U, 0x82.U, 0x89.U, 0x94.U, 0x9f.U,\n 0x46.U, 0x4d.U, 0x50.U, 0x5b.U, 0x6a.U, 0x61.U, 0x7c.U, 0x77.U, 0x1e.U, 0x15.U, 0x08.U, 0x03.U, 0x32.U, 0x39.U, 0x24.U, 0x2f.U,\n 0x8d.U, 0x86.U, 0x9b.U, 0x90.U, 0xa1.U, 0xaa.U, 0xb7.U, 0xbc.U, 0xd5.U, 0xde.U, 0xc3.U, 0xc8.U, 0xf9.U, 0xf2.U, 0xef.U, 0xe4.U,\n 0x3d.U, 0x36.U, 0x2b.U, 0x20.U, 0x11.U, 0x1a.U, 0x07.U, 0x0c.U, 0x65.U, 0x6e.U, 0x73.U, 0x78.U, 0x49.U, 0x42.U, 0x5f.U, 0x54.U,\n 0xf7.U, 0xfc.U, 0xe1.U, 0xea.U, 0xdb.U, 0xd0.U, 0xcd.U, 0xc6.U, 0xaf.U, 0xa4.U, 0xb9.U, 0xb2.U, 0x83.U, 0x88.U, 0x95.U, 0x9e.U,\n 0x47.U, 0x4c.U, 0x51.U, 0x5a.U, 0x6b.U, 0x60.U, 0x7d.U, 0x76.U, 0x1f.U, 0x14.U, 0x09.U, 0x02.U, 0x33.U, 0x38.U, 0x25.U, 0x2e.U,\n 0x8c.U, 0x87.U, 0x9a.U, 0x91.U, 0xa0.U, 0xab.U, 0xb6.U, 0xbd.U, 0xd4.U, 0xdf.U, 0xc2.U, 0xc9.U, 0xf8.U, 0xf3.U, 0xee.U, 0xe5.U,\n 0x3c.U, 0x37.U, 0x2a.U, 0x21.U, 0x10.U, 0x1b.U, 0x06.U, 0x0d.U, 0x64.U, 0x6f.U, 0x72.U, 0x79.U, 0x48.U, 0x43.U, 0x5e.U, 0x55.U,\n 0x01.U, 0x0a.U, 0x17.U, 0x1c.U, 0x2d.U, 0x26.U, 0x3b.U, 0x30.U, 0x59.U, 0x52.U, 0x4f.U, 0x44.U, 0x75.U, 0x7e.U, 0x63.U, 0x68.U,\n 0xb1.U, 0xba.U, 0xa7.U, 0xac.U, 0x9d.U, 0x96.U, 0x8b.U, 0x80.U, 0xe9.U, 0xe2.U, 0xff.U, 0xf4.U, 0xc5.U, 0xce.U, 0xd3.U, 0xd8.U,\n 0x7a.U, 0x71.U, 0x6c.U, 0x67.U, 0x56.U, 0x5d.U, 0x40.U, 0x4b.U, 0x22.U, 0x29.U, 0x34.U, 0x3f.U, 0x0e.U, 0x05.U, 0x18.U, 0x13.U,\n 0xca.U, 0xc1.U, 0xdc.U, 0xd7.U, 0xe6.U, 0xed.U, 0xf0.U, 0xfb.U, 0x92.U, 0x99.U, 0x84.U, 0x8f.U, 0xbe.U, 0xb5.U, 0xa8.U, 0xa3.U))\n\n val mul13 = VecInit(Array(\n 0x00.U, 0x0d.U, 0x1a.U, 0x17.U, 0x34.U, 0x39.U, 0x2e.U, 0x23.U, 0x68.U, 0x65.U, 0x72.U, 0x7f.U, 0x5c.U, 0x51.U, 0x46.U, 0x4b.U,\n 0xd0.U, 0xdd.U, 0xca.U, 0xc7.U, 0xe4.U, 0xe9.U, 0xfe.U, 0xf3.U, 0xb8.U, 0xb5.U, 0xa2.U, 0xaf.U, 0x8c.U, 0x81.U, 0x96.U, 0x9b.U,\n 0xbb.U, 0xb6.U, 0xa1.U, 0xac.U, 0x8f.U, 0x82.U, 0x95.U, 0x98.U, 0xd3.U, 0xde.U, 0xc9.U, 0xc4.U, 0xe7.U, 0xea.U, 0xfd.U, 0xf0.U,\n 0x6b.U, 0x66.U, 0x71.U, 0x7c.U, 0x5f.U, 0x52.U, 0x45.U, 0x48.U, 0x03.U, 0x0e.U, 0x19.U, 0x14.U, 0x37.U, 0x3a.U, 0x2d.U, 0x20.U,\n 0x6d.U, 0x60.U, 0x77.U, 0x7a.U, 0x59.U, 0x54.U, 0x43.U, 0x4e.U, 0x05.U, 0x08.U, 0x1f.U, 0x12.U, 0x31.U, 0x3c.U, 0x2b.U, 0x26.U,\n 0xbd.U, 0xb0.U, 0xa7.U, 0xaa.U, 0x89.U, 0x84.U, 0x93.U, 0x9e.U, 0xd5.U, 0xd8.U, 0xcf.U, 0xc2.U, 0xe1.U, 0xec.U, 0xfb.U, 0xf6.U,\n 0xd6.U, 0xdb.U, 0xcc.U, 0xc1.U, 0xe2.U, 0xef.U, 0xf8.U, 0xf5.U, 0xbe.U, 0xb3.U, 0xa4.U, 0xa9.U, 0x8a.U, 0x87.U, 0x90.U, 0x9d.U,\n 0x06.U, 0x0b.U, 0x1c.U, 0x11.U, 0x32.U, 0x3f.U, 0x28.U, 0x25.U, 0x6e.U, 0x63.U, 0x74.U, 0x79.U, 0x5a.U, 0x57.U, 0x40.U, 0x4d.U,\n 0xda.U, 0xd7.U, 0xc0.U, 0xcd.U, 0xee.U, 0xe3.U, 0xf4.U, 0xf9.U, 0xb2.U, 0xbf.U, 0xa8.U, 0xa5.U, 0x86.U, 0x8b.U, 0x9c.U, 0x91.U,\n 0x0a.U, 0x07.U, 0x10.U, 0x1d.U, 0x3e.U, 0x33.U, 0x24.U, 0x29.U, 0x62.U, 0x6f.U, 0x78.U, 0x75.U, 0x56.U, 0x5b.U, 0x4c.U, 0x41.U,\n 0x61.U, 0x6c.U, 0x7b.U, 0x76.U, 0x55.U, 0x58.U, 0x4f.U, 0x42.U, 0x09.U, 0x04.U, 0x13.U, 0x1e.U, 0x3d.U, 0x30.U, 0x27.U, 0x2a.U,\n 0xb1.U, 0xbc.U, 0xab.U, 0xa6.U, 0x85.U, 0x88.U, 0x9f.U, 0x92.U, 0xd9.U, 0xd4.U, 0xc3.U, 0xce.U, 0xed.U, 0xe0.U, 0xf7.U, 0xfa.U,\n 0xb7.U, 0xba.U, 0xad.U, 0xa0.U, 0x83.U, 0x8e.U, 0x99.U, 0x94.U, 0xdf.U, 0xd2.U, 0xc5.U, 0xc8.U, 0xeb.U, 0xe6.U, 0xf1.U, 0xfc.U,\n 0x67.U, 0x6a.U, 0x7d.U, 0x70.U, 0x53.U, 0x5e.U, 0x49.U, 0x44.U, 0x0f.U, 0x02.U, 0x15.U, 0x18.U, 0x3b.U, 0x36.U, 0x21.U, 0x2c.U,\n 0x0c.U, 0x01.U, 0x16.U, 0x1b.U, 0x38.U, 0x35.U, 0x22.U, 0x2f.U, 0x64.U, 0x69.U, 0x7e.U, 0x73.U, 0x50.U, 0x5d.U, 0x4a.U, 0x47.U,\n 0xdc.U, 0xd1.U, 0xc6.U, 0xcb.U, 0xe8.U, 0xe5.U, 0xf2.U, 0xff.U, 0xb4.U, 0xb9.U, 0xae.U, 0xa3.U, 0x80.U, 0x8d.U, 0x9a.U, 0x97.U))\n\n val mul14 = VecInit(Array(\n 0x00.U, 0x0e.U, 0x1c.U, 0x12.U, 0x38.U, 0x36.U, 0x24.U, 0x2a.U, 0x70.U, 0x7e.U, 0x6c.U, 0x62.U, 0x48.U, 0x46.U, 0x54.U, 0x5a.U,\n 0xe0.U, 0xee.U, 0xfc.U, 0xf2.U, 0xd8.U, 0xd6.U, 0xc4.U, 0xca.U, 0x90.U, 0x9e.U, 0x8c.U, 0x82.U, 0xa8.U, 0xa6.U, 0xb4.U, 0xba.U,\n 0xdb.U, 0xd5.U, 0xc7.U, 0xc9.U, 0xe3.U, 0xed.U, 0xff.U, 0xf1.U, 0xab.U, 0xa5.U, 0xb7.U, 0xb9.U, 0x93.U, 0x9d.U, 0x8f.U, 0x81.U,\n 0x3b.U, 0x35.U, 0x27.U, 0x29.U, 0x03.U, 0x0d.U, 0x1f.U, 0x11.U, 0x4b.U, 0x45.U, 0x57.U, 0x59.U, 0x73.U, 0x7d.U, 0x6f.U, 0x61.U,\n 0xad.U, 0xa3.U, 0xb1.U, 0xbf.U, 0x95.U, 0x9b.U, 0x89.U, 0x87.U, 0xdd.U, 0xd3.U, 0xc1.U, 0xcf.U, 0xe5.U, 0xeb.U, 0xf9.U, 0xf7.U,\n 0x4d.U, 0x43.U, 0x51.U, 0x5f.U, 0x75.U, 0x7b.U, 0x69.U, 0x67.U, 0x3d.U, 0x33.U, 0x21.U, 0x2f.U, 0x05.U, 0x0b.U, 0x19.U, 0x17.U,\n 0x76.U, 0x78.U, 0x6a.U, 0x64.U, 0x4e.U, 0x40.U, 0x52.U, 0x5c.U, 0x06.U, 0x08.U, 0x1a.U, 0x14.U, 0x3e.U, 0x30.U, 0x22.U, 0x2c.U,\n 0x96.U, 0x98.U, 0x8a.U, 0x84.U, 0xae.U, 0xa0.U, 0xb2.U, 0xbc.U, 0xe6.U, 0xe8.U, 0xfa.U, 0xf4.U, 0xde.U, 0xd0.U, 0xc2.U, 0xcc.U,\n 0x41.U, 0x4f.U, 0x5d.U, 0x53.U, 0x79.U, 0x77.U, 0x65.U, 0x6b.U, 0x31.U, 0x3f.U, 0x2d.U, 0x23.U, 0x09.U, 0x07.U, 0x15.U, 0x1b.U,\n 0xa1.U, 0xaf.U, 0xbd.U, 0xb3.U, 0x99.U, 0x97.U, 0x85.U, 0x8b.U, 0xd1.U, 0xdf.U, 0xcd.U, 0xc3.U, 0xe9.U, 0xe7.U, 0xf5.U, 0xfb.U,\n 0x9a.U, 0x94.U, 0x86.U, 0x88.U, 0xa2.U, 0xac.U, 0xbe.U, 0xb0.U, 0xea.U, 0xe4.U, 0xf6.U, 0xf8.U, 0xd2.U, 0xdc.U, 0xce.U, 0xc0.U,\n 0x7a.U, 0x74.U, 0x66.U, 0x68.U, 0x42.U, 0x4c.U, 0x5e.U, 0x50.U, 0x0a.U, 0x04.U, 0x16.U, 0x18.U, 0x32.U, 0x3c.U, 0x2e.U, 0x20.U,\n 0xec.U, 0xe2.U, 0xf0.U, 0xfe.U, 0xd4.U, 0xda.U, 0xc8.U, 0xc6.U, 0x9c.U, 0x92.U, 0x80.U, 0x8e.U, 0xa4.U, 0xaa.U, 0xb8.U, 0xb6.U,\n 0x0c.U, 0x02.U, 0x10.U, 0x1e.U, 0x34.U, 0x3a.U, 0x28.U, 0x26.U, 0x7c.U, 0x72.U, 0x60.U, 0x6e.U, 0x44.U, 0x4a.U, 0x58.U, 0x56.U,\n 0x37.U, 0x39.U, 0x2b.U, 0x25.U, 0x0f.U, 0x01.U, 0x13.U, 0x1d.U, 0x47.U, 0x49.U, 0x5b.U, 0x55.U, 0x7f.U, 0x71.U, 0x63.U, 0x6d.U,\n 0xd7.U, 0xd9.U, 0xcb.U, 0xc5.U, 0xef.U, 0xe1.U, 0xf3.U, 0xfd.U, 0xa7.U, 0xa9.U, 0xbb.U, 0xb5.U, 0x9f.U, 0x91.U, 0x83.U, 0x8d.U))\n\n val rcon = VecInit(Array(\n 0x8d.U, 0x01.U, 0x02.U, 0x04.U, 0x08.U, 0x10.U, 0x20.U, 0x40.U, 0x80.U, 0x1b.U, 0x36.U, 0x6c.U, 0xd8.U, 0xab.U, 0x4d.U, 0x9a.U,\n 0x2f.U, 0x5e.U, 0xbc.U, 0x63.U, 0xc6.U, 0x97.U, 0x35.U, 0x6a.U, 0xd4.U, 0xb3.U, 0x7d.U, 0xfa.U, 0xef.U, 0xc5.U, 0x91.U, 0x39.U,\n 0x72.U, 0xe4.U, 0xd3.U, 0xbd.U, 0x61.U, 0xc2.U, 0x9f.U, 0x25.U, 0x4a.U, 0x94.U, 0x33.U, 0x66.U, 0xcc.U, 0x83.U, 0x1d.U, 0x3a.U,\n 0x74.U, 0xe8.U, 0xcb.U, 0x8d.U, 0x01.U, 0x02.U, 0x04.U, 0x08.U, 0x10.U, 0x20.U, 0x40.U, 0x80.U, 0x1b.U, 0x36.U, 0x6c.U, 0xd8.U,\n 0xab.U, 0x4d.U, 0x9a.U, 0x2f.U, 0x5e.U, 0xbc.U, 0x63.U, 0xc6.U, 0x97.U, 0x35.U, 0x6a.U, 0xd4.U, 0xb3.U, 0x7d.U, 0xfa.U, 0xef.U,\n 0xc5.U, 0x91.U, 0x39.U, 0x72.U, 0xe4.U, 0xd3.U, 0xbd.U, 0x61.U, 0xc2.U, 0x9f.U, 0x25.U, 0x4a.U, 0x94.U, 0x33.U, 0x66.U, 0xcc.U,\n 0x83.U, 0x1d.U, 0x3a.U, 0x74.U, 0xe8.U, 0xcb.U, 0x8d.U, 0x01.U, 0x02.U, 0x04.U, 0x08.U, 0x10.U, 0x20.U, 0x40.U, 0x80.U, 0x1b.U,\n 0x36.U, 0x6c.U, 0xd8.U, 0xab.U, 0x4d.U, 0x9a.U, 0x2f.U, 0x5e.U, 0xbc.U, 0x63.U, 0xc6.U, 0x97.U, 0x35.U, 0x6a.U, 0xd4.U, 0xb3.U,\n 0x7d.U, 0xfa.U, 0xef.U, 0xc5.U, 0x91.U, 0x39.U, 0x72.U, 0xe4.U, 0xd3.U, 0xbd.U, 0x61.U, 0xc2.U, 0x9f.U, 0x25.U, 0x4a.U, 0x94.U,\n 0x33.U, 0x66.U, 0xcc.U, 0x83.U, 0x1d.U, 0x3a.U, 0x74.U, 0xe8.U, 0xcb.U, 0x8d.U, 0x01.U, 0x02.U, 0x04.U, 0x08.U, 0x10.U, 0x20.U,\n 0x40.U, 0x80.U, 0x1b.U, 0x36.U, 0x6c.U, 0xd8.U, 0xab.U, 0x4d.U, 0x9a.U, 0x2f.U, 0x5e.U, 0xbc.U, 0x63.U, 0xc6.U, 0x97.U, 0x35.U,\n 0x6a.U, 0xd4.U, 0xb3.U, 0x7d.U, 0xfa.U, 0xef.U, 0xc5.U, 0x91.U, 0x39.U, 0x72.U, 0xe4.U, 0xd3.U, 0xbd.U, 0x61.U, 0xc2.U, 0x9f.U,\n 0x25.U, 0x4a.U, 0x94.U, 0x33.U, 0x66.U, 0xcc.U, 0x83.U, 0x1d.U, 0x3a.U, 0x74.U, 0xe8.U, 0xcb.U, 0x8d.U, 0x01.U, 0x02.U, 0x04.U,\n 0x08.U, 0x10.U, 0x20.U, 0x40.U, 0x80.U, 0x1b.U, 0x36.U, 0x6c.U, 0xd8.U, 0xab.U, 0x4d.U, 0x9a.U, 0x2f.U, 0x5e.U, 0xbc.U, 0x63.U,\n 0xc6.U, 0x97.U, 0x35.U, 0x6a.U, 0xd4.U, 0xb3.U, 0x7d.U, 0xfa.U, 0xef.U, 0xc5.U, 0x91.U, 0x39.U, 0x72.U, 0xe4.U, 0xd3.U, 0xbd.U,\n 0x61.U, 0xc2.U, 0x9f.U, 0x25.U, 0x4a.U, 0x94.U, 0x33.U, 0x66.U, 0xcc.U, 0x83.U, 0x1d.U, 0x3a.U, 0x74.U, 0xe8.U, 0xcb.U, 0x8d.U))\n}", "groundtruth": " 0xe1.U, 0xf8.U, 0x98.U, 0x11.U, 0x69.U, 0xd9.U, 0x8e.U, 0x94.U, 0x9b.U, 0x1e.U, 0x87.U, 0xe9.U, 0xce.U, 0x55.U, 0x28.U, 0xdf.U,\n 0x8c.U, 0xa1.U, 0x89.U, 0x0d.U, 0xbf.U, 0xe6.U, 0x42.U, 0x68.U, 0x41.U, 0x99.U, 0x2d.U, 0x0f.U, 0xb0.U, 0x54.U, 0xbb.U, 0x16.U))\n\n", "crossfile_context": ""}
{"task_id": "aes_chisel", "path": "aes_chisel/src/main/scala/gcd/GCD.scala", "left_context": "// See README.md for license details.\n\npackage gcd\n\nimport chisel3._\n\n/**\n * Compute GCD using subtraction method.\n * Subtracts the smaller from the larger until register y is zero.\n * value in register x is then the GCD\n */\nclass GCD extends Module {\n val io = IO(new Bundle {\n val value1 = Input(UInt(16.W))\n val value2 = Input(UInt(16.W))\n val loadingValues = Input(Bool())\n val outputGCD = Output(UInt(16.W))\n val outputValid = Output(Bool())\n })\n\n val x = Reg(UInt())\n val y = Reg(UInt())\n\n when(x > y) { x := x - y }\n", "right_context": "\n when(io.loadingValues) {\n x := io.value1\n y := io.value2\n }\n\n io.outputGCD := x\n io.outputValid := y === 0.U\n}\n", "groundtruth": " .otherwise { y := y - x }\n", "crossfile_context": ""}
{"task_id": "aes_chisel", "path": "aes_chisel/src/main/scala/lfsr/LFSR.scala", "left_context": "package lfsr\n\nimport chisel3._\nimport chisel3.util.Cat\n\nclass LFSR extends Module {\n //declare input-output interface signals\n val io = IO(new Bundle {\n //clock and reset are default,\n //no other inputs necessary\n //lfsr_6 and lfsr_3r will have the random values\n val lfsr_6 = Output(UInt(6.W))\n val lfsr_3r = Output(UInt(3.W))\n })\n\n //declare the 6-bit register and initialize to 000001\n val D0123456 = RegInit(1.U(6.W)) //will init at reset\n\n //next clk value is XOR of 2 MSBs as LSB concatenated with left shift rest\n //example: 010010 => 100101 = Cat('10010','0^1')\n val nxt_D0123456 = Cat(D0123456(4, 0), D0123456(5) ^ D0123456(4))\n\n //update 6-bit register will happen in sync with clk\n D0123456 := nxt_D0123456\n\n //assign outputs\n io.lfsr_6 := D0123456\n //lfsr_3r in reverse order just for fun\n io.lfsr_3r := Cat(D0123456(1), D0123456(3), D0123456(5))\n}\n\nobject LFSR {\n", "right_context": "}", "groundtruth": " def apply(): LFSR = Module(new LFSR())\n", "crossfile_context": ""}
{"task_id": "aes_chisel", "path": "aes_chisel/src/test/scala/aes/AddRoundKeyUnitTest.scala", "left_context": "package aes\n\nimport chisel3.iotesters\nimport chisel3.iotesters.{ChiselFlatSpec, Driver, PeekPokeTester}\n\nclass AddRoundKeyUnitTester(c: AddRoundKey, Pipelined: Boolean) extends PeekPokeTester(c) {\n\n def computeAddRoundKey(state_in: Array[Int], roundKey: Array[Int]): Array[Int] = {\n\n var state_out = new Array[Int](Params.StateLength)\n\n for (i <- 0 until Params.StateLength) {\n state_out(i) = state_in(i) ^ roundKey(i)\n }\n\n state_out\n }\n\n private val aes_ark = c\n var state = Array(0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34)\n var roundKey = Array(0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f)\n\n for (i <- 0 until Params.StateLength) {\n poke(aes_ark.io.state_in(i), state(i))\n poke(aes_ark.io.roundKey(i), roundKey(i))\n }\n\n state = computeAddRoundKey(state, roundKey)\n println(state.deep.mkString(\" \"))\n\n if (Pipelined) {\n step(2)\n } else {\n step(1)\n }\n\n for (i <- 0 until Params.StateLength)\n expect(aes_ark.io.state_out(i), state(i))\n}\n\n// Run test with:\n// sbt 'testOnly aes.AddRoundKeyTester'\n// extend with the option '-- -z verbose' or '-- -z vcd' for specific test\n\nclass AddRoundKeyTester extends ChiselFlatSpec {\n\n private val Pipelined = true // [false -> 127 LUTs, true -> 64 LUTs and 128 FFs]\n private val backendNames = Array(\"firrtl\", \"verilator\")\n private val dir = \"AddRoundKey\"\n\n for (backendName <- backendNames) {\n \"AddRoundKey\" should s\"execute AES AddRoundKey (with $backendName)\" in {\n Driver(() => new AddRoundKey(Pipelined), backendName) {\n c => new AddRoundKeyUnitTester(c, Pipelined)\n } should be(true)\n }\n }\n\n \"Basic test using Driver.execute\" should \"be used as an alternative way to run specification\" in {\n iotesters.Driver.execute(\n Array(\"--target-dir\", \"test_run_dir/\" + dir + \"_basic_test\", \"--top-name\", dir), () => new AddRoundKey(Pipelined)) {\n c => new AddRoundKeyUnitTester(c, Pipelined)\n } should be(true)\n }\n\n \"using --backend-name verilator\" should \"be an alternative way to run using verilator\" in {\n", "right_context": " \"--backend-name\", \"verilator\"), () => new AddRoundKey(Pipelined)) {\n c => new AddRoundKeyUnitTester(c, Pipelined)\n } should be(true)\n }\n }\n\n \"using --backend-name firrtl\" should \"be an alternative way to run using firrtl\" in {\n if (backendNames.contains(\"firrtl\")) {\n iotesters.Driver.execute(\n Array(\"--target-dir\", \"test_run_dir/\" + dir + \"_firrtl_test\", \"--top-name\", dir,\n \"--backend-name\", \"firrtl\", \"--generate-vcd-output\", \"on\"), () => new AddRoundKey(Pipelined)) {\n c => new AddRoundKeyUnitTester(c, Pipelined)\n } should be(true)\n }\n }\n\n \"running with --is-verbose\" should \"show more about what's going on in your tester\" in {\n iotesters.Driver.execute(\n Array(\"--target-dir\", \"test_run_dir/\" + dir + \"_verbose_test\", \"--top-name\", dir,\n \"--is-verbose\"), () => new AddRoundKey(Pipelined)) {\n c => new AddRoundKeyUnitTester(c, Pipelined)\n } should be(true)\n }\n\n}\n", "groundtruth": " if (backendNames.contains(\"verilator\")) {\n iotesters.Driver.execute(\n", "crossfile_context": ""}
{"task_id": "aes_chisel", "path": "aes_chisel/src/test/scala/aes/ShiftRowsUnitTest.scala", "left_context": "package aes\n\nimport chisel3.iotesters\nimport chisel3.iotesters.{ChiselFlatSpec, Driver, PeekPokeTester}\n\nclass ShiftRowsUnitTester(c: ShiftRows) extends PeekPokeTester(c) {\n\n // ShiftRows in Scala\n def computeShiftRows(state_in: Array[Int]): Array[Int] = {\n var state_out = new Array[Int](Params.StateLength)\n\n state_out(0) = state_in(0)\n state_out(1) = state_in(5)\n state_out(2) = state_in(10)\n state_out(3) = state_in(15)\n\n state_out(4) = state_in(4)\n state_out(5) = state_in(9)\n state_out(6) = state_in(14)\n state_out(7) = state_in(3)\n\n state_out(8) = state_in(8)\n state_out(9) = state_in(13)\n state_out(10) = state_in(2)\n state_out(11) = state_in(7)\n\n state_out(12) = state_in(12)\n state_out(13) = state_in(1)\n state_out(14) = state_in(6)\n state_out(15) = state_in(11)\n\n state_out\n }\n\n private val aes_sr = c\n var state = Array(0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34)\n\n for (i <- 0 until Params.StateLength)\n poke(aes_sr.io.state_in(i), state(i))\n\n // run in Scala\n state = computeShiftRows(state)\n println(state.deep.mkString(\" \"))\n\n step(1)\n\n // match chisel and Scala\n for (i <- 0 until Params.StateLength)\n expect(aes_sr.io.state_out(i), state(i))\n}\n\n// Run test with:\n// sbt 'testOnly aes.ShiftRowsTester'\n// or sbt 'testOnly aes.ShiftRowsTester -- -z verbose'\n// or sbt 'testOnly aes.ShiftRowsTester -- -z vcd'\n\nclass ShiftRowsTester extends ChiselFlatSpec {\n\n private val backendNames = Array(\"firrtl\", \"verilator\")\n private val dir = \"ShiftRows\"\n\n for (backendName <- backendNames) {\n \"ShiftRows\" should s\"execute AES ShiftRows (with $backendName)\" in {\n Driver(() => new ShiftRows, backendName) {\n c => new ShiftRowsUnitTester(c)\n } should be(true)\n }\n }\n\n \"Basic test using Driver.execute\" should \"be used as an alternative way to run specification\" in {\n iotesters.Driver.execute(\n Array(\"--target-dir\", \"test_run_dir/\" + dir + \"_basic_test\", \"--top-name\", dir), () => new ShiftRows) {\n c => new ShiftRowsUnitTester(c)\n } should be(true)\n }\n\n \"using --backend-name verilator\" should \"be an alternative way to run using verilator\" in {\n if (backendNames.contains(\"verilator\")) {\n iotesters.Driver.execute(\n Array(\"--target-dir\", \"test_run_dir/\" + dir + \"_verilator_test\", \"--top-name\", dir,\n \"--backend-name\", \"verilator\"), () => new ShiftRows) {\n c => new ShiftRowsUnitTester(c)\n } should be(true)\n }\n }\n\n \"using --backend-name firrtl\" should \"be an alternative way to run using firrtl\" in {\n if (backendNames.contains(\"firrtl\")) {\n iotesters.Driver.execute(\n Array(\"--target-dir\", \"test_run_dir/\" + dir + \"_firrtl_test\", \"--top-name\", dir,\n", "right_context": "\n \"running with --is-verbose\" should \"show more about what's going on in your tester\" in {\n iotesters.Driver.execute(\n Array(\"--target-dir\", \"test_run_dir/\" + dir + \"_verbose_test\", \"--top-name\", dir,\n \"--is-verbose\"), () => new ShiftRows) {\n c => new ShiftRowsUnitTester(c)\n } should be(true)\n }\n\n}\n", "groundtruth": " \"--backend-name\", \"firrtl\", \"--generate-vcd-output\", \"on\"), () => new ShiftRows) {\n c => new ShiftRowsUnitTester(c)\n } should be(true)\n", "crossfile_context": ""}
{"task_id": "aes_chisel", "path": "aes_chisel/src/test/scala/aes/UnrolledAESUnitTest.scala", "left_context": "package aes\n\nimport chisel3.iotesters\nimport chisel3.iotesters.{ChiselFlatSpec, Driver, PeekPokeTester}\n\nclass UnrolledAESUnitTester(c: UnrolledAES, Nk: Int, unrolled: Int, SubBytes_SCD: Boolean, InvSubBytes_SCD: Boolean, expandedKeyMemType: String) extends PeekPokeTester(c) {\n require(Nk == 4 || Nk == 6 || Nk == 8)\n require(expandedKeyMemType == \"ROM\" || expandedKeyMemType == \"Mem\" || expandedKeyMemType == \"SyncReadMem\")\n\n private val aes_i = c\n\n val KeyLength: Int = Nk * Params.rows\n val Nr: Int = Nk + 6 // 10, 12, 14 rounds\n val Nrplus1: Int = Nr + 1 // 10+1, 12+1, 14+1\n\n printf(\"\\nStarting the tests with 4 idle cycles\\n\")\n poke(aes_i.io.AES_mode, 0) // off\n step(4) // test that things are fine in Idle state\n\n val input_text = Array(0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34)\n\n if (expandedKeyMemType == \"Mem\" || expandedKeyMemType == \"SyncReadMem\") {\n val roundKey128 = Array(0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f)\n val expandedKey128 = Array(\n Array(0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f),\n Array(0xd6, 0xaa, 0x74, 0xfd, 0xd2, 0xaf, 0x72, 0xfa, 0xda, 0xa6, 0x78, 0xf1, 0xd6, 0xab, 0x76, 0xfe),\n Array(0xb6, 0x92, 0xcf, 0x0b, 0x64, 0x3d, 0xbd, 0xf1, 0xbe, 0x9b, 0xc5, 0x00, 0x68, 0x30, 0xb3, 0xfe),\n Array(0xb6, 0xff, 0x74, 0x4e, 0xd2, 0xc2, 0xc9, 0xbf, 0x6c, 0x59, 0x0c, 0xbf, 0x04, 0x69, 0xbf, 0x41),\n Array(0x47, 0xf7, 0xf7, 0xbc, 0x95, 0x35, 0x3e, 0x03, 0xf9, 0x6c, 0x32, 0xbc, 0xfd, 0x05, 0x8d, 0xfd),\n Array(0x3c, 0xaa, 0xa3, 0xe8, 0xa9, 0x9f, 0x9d, 0xeb, 0x50, 0xf3, 0xaf, 0x57, 0xad, 0xf6, 0x22, 0xaa),\n Array(0x5e, 0x39, 0x0f, 0x7d, 0xf7, 0xa6, 0x92, 0x96, 0xa7, 0x55, 0x3d, 0xc1, 0x0a, 0xa3, 0x1f, 0x6b),\n Array(0x14, 0xf9, 0x70, 0x1a, 0xe3, 0x5f, 0xe2, 0x8c, 0x44, 0x0a, 0xdf, 0x4d, 0x4e, 0xa9, 0xc0, 0x26),\n Array(0x47, 0x43, 0x87, 0x35, 0xa4, 0x1c, 0x65, 0xb9, 0xe0, 0x16, 0xba, 0xf4, 0xae, 0xbf, 0x7a, 0xd2),\n Array(0x54, 0x99, 0x32, 0xd1, 0xf0, 0x85, 0x57, 0x68, 0x10, 0x93, 0xed, 0x9c, 0xbe, 0x2c, 0x97, 0x4e),\n Array(0x13, 0x11, 0x1d, 0x7f, 0xe3, 0x94, 0x4a, 0x17, 0xf3, 0x07, 0xa7, 0x8b, 0x4d, 0x2b, 0x30, 0xc5))\n\n val roundKey192 = Array(0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17)\n val expandedKey192 = Array(\n Array(0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f),\n Array(0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x58, 0x46, 0xf2, 0xf9, 0x5c, 0x43, 0xf4, 0xfe),\n Array(0x54, 0x4a, 0xfe, 0xf5, 0x58, 0x47, 0xf0, 0xfa, 0x48, 0x56, 0xe2, 0xe9, 0x5c, 0x43, 0xf4, 0xfe),\n Array(0x40, 0xf9, 0x49, 0xb3, 0x1c, 0xba, 0xbd, 0x4d, 0x48, 0xf0, 0x43, 0xb8, 0x10, 0xb7, 0xb3, 0x42),\n Array(0x58, 0xe1, 0x51, 0xab, 0x04, 0xa2, 0xa5, 0x55, 0x7e, 0xff, 0xb5, 0x41, 0x62, 0x45, 0x08, 0x0c),\n Array(0x2a, 0xb5, 0x4b, 0xb4, 0x3a, 0x02, 0xf8, 0xf6, 0x62, 0xe3, 0xa9, 0x5d, 0x66, 0x41, 0x0c, 0x08),\n Array(0xf5, 0x01, 0x85, 0x72, 0x97, 0x44, 0x8d, 0x7e, 0xbd, 0xf1, 0xc6, 0xca, 0x87, 0xf3, 0x3e, 0x3c),\n Array(0xe5, 0x10, 0x97, 0x61, 0x83, 0x51, 0x9b, 0x69, 0x34, 0x15, 0x7c, 0x9e, 0xa3, 0x51, 0xf1, 0xe0),\n Array(0x1e, 0xa0, 0x37, 0x2a, 0x99, 0x53, 0x09, 0x16, 0x7c, 0x43, 0x9e, 0x77, 0xff, 0x12, 0x05, 0x1e),\n Array(0xdd, 0x7e, 0x0e, 0x88, 0x7e, 0x2f, 0xff, 0x68, 0x60, 0x8f, 0xc8, 0x42, 0xf9, 0xdc, 0xc1, 0x54),\n Array(0x85, 0x9f, 0x5f, 0x23, 0x7a, 0x8d, 0x5a, 0x3d, 0xc0, 0xc0, 0x29, 0x52, 0xbe, 0xef, 0xd6, 0x3a),\n Array(0xde, 0x60, 0x1e, 0x78, 0x27, 0xbc, 0xdf, 0x2c, 0xa2, 0x23, 0x80, 0x0f, 0xd8, 0xae, 0xda, 0x32),\n Array(0xa4, 0x97, 0x0a, 0x33, 0x1a, 0x78, 0xdc, 0x09, 0xc4, 0x18, 0xc2, 0x71, 0xe3, 0xa4, 0x1d, 0x5d))\n\n val roundKey256 = Array(0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f)\n val expandedKey256 = Array(\n Array(0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f),\n Array(0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f),\n Array(0xa5, 0x73, 0xc2, 0x9f, 0xa1, 0x76, 0xc4, 0x98, 0xa9, 0x7f, 0xce, 0x93, 0xa5, 0x72, 0xc0, 0x9c),\n Array(0x16, 0x51, 0xa8, 0xcd, 0x02, 0x44, 0xbe, 0xda, 0x1a, 0x5d, 0xa4, 0xc1, 0x06, 0x40, 0xba, 0xde),\n Array(0xae, 0x87, 0xdf, 0xf0, 0x0f, 0xf1, 0x1b, 0x68, 0xa6, 0x8e, 0xd5, 0xfb, 0x03, 0xfc, 0x15, 0x67),\n Array(0x6d, 0xe1, 0xf1, 0x48, 0x6f, 0xa5, 0x4f, 0x92, 0x75, 0xf8, 0xeb, 0x53, 0x73, 0xb8, 0x51, 0x8d),\n Array(0xc6, 0x56, 0x82, 0x7f, 0xc9, 0xa7, 0x99, 0x17, 0x6f, 0x29, 0x4c, 0xec, 0x6c, 0xd5, 0x59, 0x8b),\n", "right_context": " Array(0x7c, 0xcf, 0xf7, 0x1c, 0xbe, 0xb4, 0xfe, 0x54, 0x13, 0xe6, 0xbb, 0xf0, 0xd2, 0x61, 0xa7, 0xdf),\n Array(0xf0, 0x1a, 0xfa, 0xfe, 0xe7, 0xa8, 0x29, 0x79, 0xd7, 0xa5, 0x64, 0x4a, 0xb3, 0xaf, 0xe6, 0x40),\n Array(0x25, 0x41, 0xfe, 0x71, 0x9b, 0xf5, 0x00, 0x25, 0x88, 0x13, 0xbb, 0xd5, 0x5a, 0x72, 0x1c, 0x0a),\n Array(0x4e, 0x5a, 0x66, 0x99, 0xa9, 0xf2, 0x4f, 0xe0, 0x7e, 0x57, 0x2b, 0xaa, 0xcd, 0xf8, 0xcd, 0xea),\n Array(0x24, 0xfc, 0x79, 0xcc, 0xbf, 0x09, 0x79, 0xe9, 0x37, 0x1a, 0xc2, 0x3c, 0x6d, 0x68, 0xde, 0x36))\n\n val roundKey = Nk match {\n case 4 => roundKey128\n case 6 => roundKey192\n case 8 => roundKey256\n }\n\n val expandedKey = Nk match {\n case 4 => expandedKey128\n case 6 => expandedKey192\n case 8 => expandedKey256\n }\n\n printf(\"\\nSending expanded AES key\\n\")\n // send expanded key to AES memory block\n poke(aes_i.io.AES_mode, 1) // configure key\n for (i <- 0 until Nrplus1) {\n for (j <- 0 until Params.StateLength) {\n poke(aes_i.io.input_text(j), expandedKey(i)(j))\n }\n step(1)\n }\n\n printf(\"\\nStaying idle for 4 cycles\\n\")\n poke(aes_i.io.AES_mode, 0) // must stop when all roundKeys were sent\n step(4)\n }\n\n printf(\"\\nStarting AES cipher mode, sending plaintext\\n\")\n poke(aes_i.io.AES_mode, 2) // cipher\n // send the plaintext\n for (i <- 0 until Params.StateLength) {\n poke(aes_i.io.input_text(i), input_text(i))\n }\n step(1)\n poke(aes_i.io.AES_mode, 0) // idle\n\n // remaining rounds\n for (i <- 1 until Nrplus1) {\n step(1)\n }\n\n val state_e128 = Array(0x89, 0xed, 0x5e, 0x6a, 0x05, 0xca, 0x76, 0x33, 0x81, 0x35, 0x08, 0x5f, 0xe2, 0x1c, 0x40, 0xbd)\n val state_e192 = Array(0xbc, 0x3a, 0xaa, 0xb5, 0xd9, 0x7b, 0xaa, 0x7b, 0x32, 0x5d, 0x7b, 0x8f, 0x69, 0xcd, 0x7c, 0xa8)\n val state_e256 = Array(0x9a, 0x19, 0x88, 0x30, 0xff, 0x9a, 0x4e, 0x39, 0xec, 0x15, 0x01, 0x54, 0x7d, 0x4a, 0x6b, 0x1b)\n\n val state_e = Nk match {\n case 4 => state_e128\n case 6 => state_e192\n case 8 => state_e256\n }\n\n printf(\"\\nInspecting cipher output\\n\")\n // verify aes cipher output\n for (i <- 0 until Params.StateLength)\n expect(aes_i.io.output_text(i), state_e(i))\n expect(aes_i.io.output_valid, 1)\n\n // store cipher output\n val cipher_output = peek(aes_i.io.output_text)\n\n printf(\"\\nStaying idle for 4 cycles\\n\")\n poke(aes_i.io.AES_mode, 0) // off\n step(4)\n\n printf(\"\\nStarting AES inverse cipher mode, sending ciphertext\\n\")\n poke(aes_i.io.AES_mode, 3) // inverse cipher\n // send the ciphertext\n for (i <- 0 until Params.StateLength) {\n poke(aes_i.io.input_text(i), cipher_output(i)) // same as state_e(i)\n }\n step(1)\n poke(aes_i.io.AES_mode, 0) // idle\n\n // remaining rounds\n for (i <- 1 until Nrplus1) {\n step(1)\n }\n\n printf(\"\\nInspecting inverse cipher output\\n\")\n // verify aes inverse cipher output\n for (i <- 0 until Params.StateLength)\n expect(aes_i.io.output_text(i), input_text(i))\n expect(aes_i.io.output_valid, 1)\n\n printf(\"\\nStaying idle for 4 cycles\\n\")\n step(4)\n}\n\n// Run test with:\n// sbt 'testOnly aes.UnrolledAESTester'\n// sbt 'testOnly aes.UnrolledAESTester -- -z \"using verilator\"'\n// sbt 'testOnly aes.UnrolledAESTester -- -z \"using firrtl\"'\n// sbt 'testOnly aes.UnrolledAESTester -- -z verbose'\n// sbt 'testOnly aes.UnrolledAESTester -- -z vcd'\n\nclass UnrolledAESTester extends ChiselFlatSpec {\n\n private val expandedKeyMemType = \"SyncReadMem\" // ROM or Mem or SyncReadMem works\n private val SubBytes_SCD = false\n private val InvSubBytes_SCD = false\n private val Nk = 8 // 4, 6, 8 [32-bit words] columns in cipher key\n private val unrolled = 10\n private val backendNames = Array(\"firrtl\", \"verilator\")\n private val dir = \"UnrolledAES\"\n\n for (backendName <- backendNames) {\n \"UnrolledAES\" should s\"execute cipher and inverse cipher (with $backendName)\" in {\n Driver(() => new UnrolledAES(Nk, unrolled, SubBytes_SCD, InvSubBytes_SCD, expandedKeyMemType), backendName) {\n c => new UnrolledAESUnitTester(c, Nk, unrolled, SubBytes_SCD, InvSubBytes_SCD, expandedKeyMemType)\n } should be(true)\n }\n }\n\n \"Basic test using Driver.execute\" should \"be used as an alternative way to run specification\" in {\n iotesters.Driver.execute(\n Array(\"--target-dir\", \"test_run_dir/\" + dir + \"_basic_test\", \"--top-name\", dir),\n () => new UnrolledAES(Nk, unrolled, SubBytes_SCD, InvSubBytes_SCD, expandedKeyMemType)) {\n c => new UnrolledAESUnitTester(c, Nk, unrolled, SubBytes_SCD, InvSubBytes_SCD, expandedKeyMemType)\n } should be(true)\n }\n\n \"using --backend-name verilator\" should \"be an alternative way to run using verilator\" in {\n if (backendNames.contains(\"verilator\")) {\n iotesters.Driver.execute(\n Array(\"--target-dir\", \"test_run_dir/\" + dir + \"_verilator_test\", \"--top-name\", dir,\n \"--backend-name\", \"verilator\"), () => new UnrolledAES(Nk, unrolled, SubBytes_SCD, InvSubBytes_SCD, expandedKeyMemType)) {\n c => new UnrolledAESUnitTester(c, Nk, unrolled, SubBytes_SCD, InvSubBytes_SCD, expandedKeyMemType)\n } should be(true)\n }\n }\n\n \"using --backend-name firrtl\" should \"be an alternative way to run using firrtl\" in {\n if (backendNames.contains(\"firrtl\")) {\n iotesters.Driver.execute(\n Array(\"--target-dir\", \"test_run_dir/\" + dir + \"_firrtl_test\", \"--top-name\", dir,\n \"--backend-name\", \"firrtl\", \"--generate-vcd-output\", \"on\"), () => new UnrolledAES(Nk, unrolled, SubBytes_SCD, InvSubBytes_SCD, expandedKeyMemType)) {\n c => new UnrolledAESUnitTester(c, Nk, unrolled, SubBytes_SCD, InvSubBytes_SCD, expandedKeyMemType)\n } should be(true)\n }\n }\n\n \"running with --is-verbose\" should \"show more about what's going on in your tester\" in {\n iotesters.Driver.execute(\n Array(\"--target-dir\", \"test_run_dir/\" + dir + \"_verbose_test\", \"--top-name\", dir,\n \"--is-verbose\"), () => new UnrolledAES(Nk, unrolled, SubBytes_SCD, InvSubBytes_SCD, expandedKeyMemType)) {\n c => new UnrolledAESUnitTester(c, Nk, unrolled, SubBytes_SCD, InvSubBytes_SCD, expandedKeyMemType)\n } should be(true)\n }\n\n}\n", "groundtruth": " Array(0x3d, 0xe2, 0x3a, 0x75, 0x52, 0x47, 0x75, 0xe7, 0x27, 0xbf, 0x9e, 0xb4, 0x54, 0x07, 0xcf, 0x39),\n Array(0x0b, 0xdc, 0x90, 0x5f, 0xc2, 0x7b, 0x09, 0x48, 0xad, 0x52, 0x45, 0xa4, 0xc1, 0x87, 0x1c, 0x2f),\n", "crossfile_context": ""}
{"task_id": "aes_chisel", "path": "aes_chisel/src/test/scala/gcd/GCDMain.scala", "left_context": "// See README.md for license details.\n\npackage gcd\n\nimport chisel3._\n\n/**\n * This provides an alternate way to run tests, by executing then as a main\n * From sbt (Note: the test: prefix is because this main is under the test package hierarchy):\n * {{{\n * test:runMain gcd.GCDMain\n * }}}\n * To see all command line options use:\n * {{{\n * test:runMain gcd.GCDMain --help\n * }}}\n * To run with verilator:\n * {{{\n * test:runMain gcd.GCDMain --backend-name verilator\n * }}}\n * To run with verilator from your terminal shell use:\n * {{{\n * sbt 'test:runMain gcd.GCDMain --backend-name verilator'\n * }}}\n */\nobject GCDMain extends App {\n iotesters.Driver.execute(args, () => new GCD) {\n c => new GCDUnitTester(c)\n }\n}\n\n/**\n * This provides a way to run the firrtl-interpreter REPL (or shell)\n * on the lowered firrtl generated by your circuit. You will be placed\n * in an interactive shell. This can be very helpful as a debugging\n * technique. Type help to see a list of commands.\n *\n * To run from sbt\n * {{{\n * test:runMain gcd.GCDRepl\n * }}}\n * To run from sbt and see the half a zillion options try\n * {{{\n * test:runMain gcd.GCDRepl --help\n * }}}\n */\n", "right_context": "", "groundtruth": "object GCDRepl extends App {\n iotesters.Driver.executeFirrtlRepl(args, () => new GCD)\n}", "crossfile_context": ""}
{"task_id": "aes_chisel", "path": "aes_chisel/src/test/scala/lfsr/LFSRUnitTest.scala", "left_context": "package lfsr\n\nimport chisel3.iotesters\nimport chisel3.iotesters.{ChiselFlatSpec, Driver, PeekPokeTester}\n\nclass LFSRUnitTester(c: LFSR) extends PeekPokeTester(c) {\n //init D0123456 to 1\n var D0123456 = 1\n for (t <- 0 until 63) {\n step(1)\n val bit = ((D0123456 >> 5) ^ (D0123456 >> 4)) & 1;\n D0123456 = (D0123456 << 1) | bit;\n if (D0123456 > 63) {\n D0123456 = D0123456 - 64\n }\n expect(c.io.lfsr_6, D0123456)\n }\n}\n\n// Run with:\n// sbt 'testOnly lfsr.LFSRTester'\n// or sbt 'testOnly lfsr.LFSRTester -- -z verbose'\n// or sbt 'testOnly lfsr.LFSRTester -- -z vcd'\n\nclass LFSRTester extends ChiselFlatSpec {\n\n private val backendNames = Array[String](\"firrtl\", \"verilator\")\n private val dir = \"LFSR\"\n\n for (backendName <- backendNames) {\n \"LFSR\" should s\"calculate proper greatest common denominator (with $backendName)\" in {\n Driver(() => new LFSR, backendName) {\n c => new LFSRUnitTester(c)\n } should be(true)\n }\n }\n\n \"Basic test using Driver.execute\" should \"be used as an alternative way to run specification\" in {\n iotesters.Driver.execute(\n Array(\"--target-dir\", \"test_run_dir/\" + dir + \"_basic_test\", \"--top-name\", dir), () => new LFSR) {\n c => new LFSRUnitTester(c)\n } should be(true)\n }\n\n \"using --backend-name verilator\" should \"be an alternative way to run using verilator\" in {\n if (backendNames.contains(\"verilator\")) {\n iotesters.Driver.execute(\n Array(\"--target-dir\", \"test_run_dir/\" + dir + \"_verilator_test\", \"--top-name\", dir,\n \"--backend-name\", \"verilator\"), () => new LFSR) {\n c => new LFSRUnitTester(c)\n } should be(true)\n }\n }\n\n \"using --backend-name firrtl\" should \"be an alternative way to run using firrtl\" in {\n if (backendNames.contains(\"firrtl\")) {\n", "right_context": " }\n }\n\n \"running with --is-verbose\" should \"show more about what's going on in your tester\" in {\n iotesters.Driver.execute(\n Array(\"--target-dir\", \"test_run_dir/\" + dir + \"_verbose_test\", \"--top-name\", dir,\n \"--is-verbose\"), () => new LFSR) {\n c => new LFSRUnitTester(c)\n } should be(true)\n }\n\n}\n", "groundtruth": " iotesters.Driver.execute(\n Array(\"--target-dir\", \"test_run_dir/\" + dir + \"_firrtl_test\", \"--top-name\", dir,\n \"--backend-name\", \"firrtl\", \"--generate-vcd-output\", \"on\"), () => new LFSR) {\n", "crossfile_context": ""}
{"task_id": "Quasar", "path": "Quasar/design/src/main/scala/dec/dec_decode_ctl.scala", "left_context": "package dec\nimport chisel3._\n\nimport scala.collection._\nimport chisel3.util._\nimport include._\nimport lib._\nimport exu._\nimport lsu._\n\nclass dec_decode_ctl extends Module with lib with RequireAsyncReset{\n val io = IO(new Bundle{\n val decode_exu = Flipped(new decode_exu) //connection with exu top\n val dec_alu = Flipped(new dec_alu) //connection with alu\n val dec_div = Flipped(new dec_div) //connection with divider\n val dctl_busbuff = Flipped(new dctl_busbuff()) //connection with bus buffer\n val dctl_dma = new dctl_dma //connection with dma\n val dec_aln = Flipped(new aln_dec) //connection with aligner\n val dbg_dctl = new dbg_dctl() //connection with dbg\n\n val dec_tlu_trace_disable = Input(Bool())\n val dec_debug_valid_d = Input(Bool())\n\n\n val dec_tlu_flush_extint = Input(Bool())\n val dec_tlu_force_halt = Input(Bool()) // invalidate nonblock load cam on a force halt event\n\n val dec_i0_inst_wb = Output(UInt(32.W)) // 32b instruction at wb+1 for trace encoder\n val dec_i0_pc_wb = Output(UInt(31.W)) // 31b pc at wb+1 for trace encoder\n\n val dec_i0_trigger_match_d = Input(UInt(4.W)) // i0 decode trigger matches\n val dec_tlu_wr_pause_r = Input(Bool()) // pause instruction at r\n val dec_tlu_pipelining_disable = Input(Bool()) // pipeline disable - presync, i0 decode only\n val lsu_trigger_match_m = Input(UInt(4.W)) // lsu trigger matches\n val lsu_pmu_misaligned_m = Input(Bool()) // perf mon: load/store misalign\n val dec_tlu_debug_stall = Input(Bool()) // debug stall decode\n val dec_tlu_flush_leak_one_r = Input(Bool()) // leak1 instruction\n val dec_debug_fence_d = Input(Bool()) // debug fence instruction\n val dec_i0_icaf_d = Input(Bool()) // icache access fault\n\n val dec_i0_icaf_second_d = Input(Bool()) // i0 instruction access fault at decode for f1 fetch group\n\n val dec_i0_icaf_type_d = Input(UInt(2.W)) // i0 instruction access fault type\n val dec_i0_dbecc_d = Input(Bool()) // icache/iccm double-bit error\n val dec_i0_brp = Flipped(Valid(new br_pkt_t)) // branch packet\n val dec_i0_bp_index = Input(UInt(((BTB_ADDR_HI-BTB_ADDR_LO)+1).W)) // i0 branch index\n val dec_i0_bp_fghr = Input(UInt(BHT_GHR_SIZE.W)) // BP FGHR\n val dec_i0_bp_btag = Input(UInt(BTB_BTAG_SIZE.W)) // BP tag\n\n val dec_i0_bp_fa_index = Input(UInt(log2Ceil(BTB_SIZE).W)) // Fully associt btb index\n\n // val dec_i0_pc_d = Input(UInt(31.W)) // pc\n val lsu_idle_any = Input(Bool()) // lsu idle: if fence instr & !!!!!!!!!!!!!!!!!!!!!!!!!lsu_idle then stall decode\n val lsu_load_stall_any = Input(Bool()) // stall any load at decode\n val lsu_store_stall_any = Input(Bool()) // stall any store at decode6\n val exu_div_wren = Input(Bool()) // nonblocking divide write enable to GPR.\n val dec_tlu_i0_kill_writeb_wb = Input(Bool()) // I0 is flushed, don't writeback any results to arch state\n val dec_tlu_flush_lower_wb = Input(Bool()) // trap lower flush\n val dec_tlu_i0_kill_writeb_r = Input(Bool()) // I0 is flushed, don't writeback any results to arch state\n val dec_tlu_flush_lower_r = Input(Bool()) // trap lower flush\n val dec_tlu_flush_pause_r = Input(Bool()) // don't clear pause state on initial lower flush\n val dec_tlu_presync_d = Input(Bool()) // CSR read needs to be presync'd\n val dec_tlu_postsync_d = Input(Bool()) // CSR ops that need to be postsync'd\n val dec_i0_pc4_d = Input(Bool()) // inst is 4B inst else 2B\n val dec_csr_rddata_d = Input(UInt(32.W)) // csr read data at wb\n val dec_csr_legal_d = Input(Bool()) // csr indicates legal operation\n val lsu_result_m = Input(UInt(32.W)) // load result\n val lsu_result_corr_r = Input(UInt(32.W)) // load result - corrected data for writing gpr's, not for bypassing\n val exu_flush_final = Input(Bool()) // lower flush or i0 flush at X or D\n val dec_i0_instr_d = Input(UInt(32.W)) // inst at decode\n val dec_ib0_valid_d = Input(Bool()) // inst valid at decode\n\n val active_clk = Input(Clock()) // Clock only while core active. Through two clock headers. For flops without second clock header built in.\n val free_l2clk = Input(Clock()) // Clock always. Through one clock header. For flops with second header built in.\n val clk_override = Input(Bool()) // Override non-functional clock gating\n\n val dec_i0_rs1_d = Output(UInt(5.W)) // rs1 logical source\n val dec_i0_rs2_d = Output(UInt(5.W))\n val dec_i0_waddr_r = Output(UInt(5.W)) // i0 logical source to write to gpr's\n val dec_i0_wen_r = Output(Bool()) // i0 write enable\n val dec_i0_wdata_r = Output(UInt(32.W)) // i0 write data\n\n // val dec_i0_branch_d = Output(Bool()) // Branch in D-stage\n // val dec_i0_result_r = Output(UInt(32.W)) // Result R-stage\n // val dec_qual_lsu_d = Output(Bool())// LSU instruction at D. Use to quiet LSU operands\n\n val lsu_p = Valid(new lsu_pkt_t) // load/store packet\n val div_waddr_wb = Output(UInt(5.W)) // DIV write address to GPR\n val dec_lsu_valid_raw_d = Output(Bool())\n val dec_lsu_offset_d = Output(UInt(12.W))\n val dec_csr_wen_unq_d = Output(Bool()) // valid csr with write - for csr legal\n val dec_csr_any_unq_d = Output(Bool()) // valid csr - for csr legal\n val dec_csr_rdaddr_d = Output(UInt(12.W)) // read address for csr\n val dec_csr_wen_r = Output(Bool()) // csr write enable at r\n val dec_csr_wraddr_r = Output(UInt(12.W)) // write address for csr\n val dec_csr_wrdata_r = Output(UInt(32.W)) // csr write data at r\n val dec_csr_stall_int_ff = Output(Bool()) // csr is mie/mstatus\n val dec_tlu_i0_valid_r = Output(Bool()) // i0 valid inst at c\n val dec_tlu_packet_r = Output(new trap_pkt_t) // trap packet\n val dec_tlu_i0_pc_r = Output(UInt(31.W)) // i0 trap pc\n val dec_illegal_inst = Output(UInt(32.W)) // illegal inst\n\n val dec_fa_error_index = Output(UInt(log2Ceil(BTB_SIZE).W)) // Fully associt btb error index\n\n val dec_pmu_instr_decoded = Output(Bool()) // number of instructions decode this cycle encoded\n val dec_pmu_decode_stall = Output(Bool()) // decode is stalled\n val dec_pmu_presync_stall = Output(Bool()) // decode has presync stall\n val dec_pmu_postsync_stall = Output(Bool()) // decode has postsync stall\n val dec_nonblock_load_wen = Output(Bool()) // write enable for nonblock load\n val dec_nonblock_load_waddr = Output(UInt(5.W)) // logical write addr for nonblock load\n val dec_pause_state = Output(Bool()) // core in pause state\n val dec_pause_state_cg = Output(Bool()) // pause state for clock-gating\n val dec_div_active = Output(Bool()) // non-block divide is active\n val scan_mode = Input(Bool())\n val dec_i0_decode_d = Output(Bool())\n })\n //packets zero initialization\n io.decode_exu.mul_p := 0.U.asTypeOf(io.decode_exu.mul_p)\n // Vals defined\n val leak1_i1_stall_in = WireInit(UInt(1.W), 0.U)\n val leak1_i0_stall_in = WireInit(UInt(1.W), 0.U)\n val i0r = Wire(new reg_pkt_t)\n val d_t = Wire(new trap_pkt_t)\n val x_t = Wire(new trap_pkt_t)\n val x_t_in = Wire(new trap_pkt_t)\n val r_t = Wire(new trap_pkt_t)\n val r_t_in = Wire(new trap_pkt_t)\n val d_d = Wire(Valid(new dest_pkt_t))\n val x_d = Wire(Valid(new dest_pkt_t))\n val r_d = Wire(Valid(new dest_pkt_t))\n val r_d_in = Wire(Valid(new dest_pkt_t))\n val wbd = Wire(Valid(new dest_pkt_t))\n val i0_d_c = Wire(new class_pkt_t)\n val i0_rs1_class_d = Wire(new class_pkt_t)\n val i0_rs2_class_d = Wire(new class_pkt_t)\n val i0_rs1_depth_d = WireInit(UInt(2.W),0.U)\n val i0_rs2_depth_d = WireInit(UInt(2.W),0.U)\n val cam_wen = WireInit(UInt(LSU_NUM_NBLOAD.W), 0.U)\n val cam = Wire(Vec(LSU_NUM_NBLOAD,Valid(new load_cam_pkt_t)))\n val cam_write = WireInit(UInt(1.W), 0.U)\n val cam_inv_reset_val = Wire(Vec(LSU_NUM_NBLOAD,UInt(1.W)))\n val cam_data_reset_val = Wire(Vec(LSU_NUM_NBLOAD,UInt(1.W)))\n val nonblock_load_write = Wire(Vec(LSU_NUM_NBLOAD,UInt(1.W)))\n val cam_raw = Wire(Vec(LSU_NUM_NBLOAD,Valid(new load_cam_pkt_t)))\n val cam_in = Wire(Vec(LSU_NUM_NBLOAD,Valid(new load_cam_pkt_t)))\n val i0_dp = Wire(new dec_pkt_t)\n val i0_dp_raw = Wire(new dec_pkt_t)\n val i0_rs1bypass = WireInit(UInt(3.W), 0.U)\n val i0_rs2bypass = WireInit(UInt(3.W), 0.U)\n val illegal_lockout = WireInit(UInt(1.W), 0.U)\n val postsync_stall = WireInit(UInt(1.W), 0.U)\n val ps_stall_in = WireInit(UInt(1.W), 0.U)\n val i0_pipe_en = WireInit(UInt(4.W), 0.U)\n val i0_load_block_d = WireInit(UInt(1.W), 0.U)\n val load_ldst_bypass_d = WireInit(UInt(1.W), 0.U)\n val store_data_bypass_d = WireInit(UInt(1.W), 0.U)\n val store_data_bypass_m = WireInit(UInt(1.W), 0.U)\n val tlu_wr_pause_r1 = WireInit(UInt(1.W), 0.U)\n val tlu_wr_pause_r2 = WireInit(UInt(1.W), 0.U)\n val leak1_i1_stall = WireInit(UInt(1.W), 0.U)\n val leak1_i0_stall = WireInit(UInt(1.W), 0.U)\n val pause_state = WireInit(Bool(), 0.B)\n val flush_final_r = WireInit(UInt(1.W), 0.U)\n val illegal_lockout_in = WireInit(UInt(1.W), 0.U)\n val lsu_idle = WireInit(Bool(), 0.B)\n val pause_state_in = WireInit(Bool(), 0.B)\n val leak1_mode = WireInit(UInt(1.W), 0.U)\n val i0_pcall = WireInit(UInt(1.W), 0.U)\n val i0_pja = WireInit(UInt(1.W), 0.U)\n val i0_pret = WireInit(UInt(1.W), 0.U)\n val i0_legal_decode_d = WireInit(UInt(1.W), 0.U)\n val i0_pcall_raw = WireInit(UInt(1.W), 0.U)\n val i0_pja_raw = WireInit(UInt(1.W), 0.U)\n val i0_pret_raw = WireInit(UInt(1.W), 0.U)\n val i0_br_offset = WireInit(UInt(12.W), 0.U)\n val i0_csr_write_only_d = WireInit(UInt(1.W), 0.U)\n val i0_jal = WireInit(UInt(1.W), 0.U)\n val i0_wen_r = WireInit(UInt(1.W), 0.U)\n val i0_x_ctl_en = WireInit(UInt(1.W), 0.U)\n val i0_r_ctl_en = WireInit(UInt(1.W), 0.U)\n val i0_wb_ctl_en = WireInit(UInt(1.W), 0.U)\n val i0_x_data_en = WireInit(UInt(1.W), 0.U)\n val i0_r_data_en = WireInit(UInt(1.W), 0.U)\n val i0_wb_data_en = WireInit(UInt(1.W), 0.U)\n val i0_wb1_data_en = WireInit(UInt(1.W), 0.U)\n val i0_nonblock_load_stall = WireInit(UInt(1.W), 0.U)\n val csr_ren_qual_d = WireInit(Bool(), 0.B)\n val lsu_decode_d = WireInit(UInt(1.W), 0.U)\n val mul_decode_d = WireInit(UInt(1.W), 0.U)\n val div_decode_d = WireInit(UInt(1.W), 0.U)\n val write_csr_data = WireInit(UInt(32.W),0.U)\n val i0_result_corr_r = WireInit(UInt(32.W),0.U)\n val presync_stall = WireInit(UInt(1.W), 0.U)\n val i0_nonblock_div_stall = WireInit(UInt(1.W), 0.U)\n val debug_fence = WireInit(Bool(), 0.B)\n val i0_immed_d = WireInit(UInt(32.W), 0.U)\n val i0_result_x = WireInit(UInt(32.W), 0.U)\n val i0_result_r = WireInit(UInt(32.W), 0.U)\n val i0_br_error_all = WireInit(Bool(),0.B)\n val i0_brp_valid = WireInit(Bool(),0.B)\n val btb_error_found_f = WireInit(Bool(),0.B)\n val fa_error_index_ns = WireInit(Bool(),0.B)\n val btb_error_found = WireInit(Bool(),0.B)\n val div_active_in = WireInit(Bool(),0.B)\n\n //////////////////////////////////////////////////////////////////////\n\n leak1_i1_stall := rvdffie(leak1_i1_stall_in, io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n leak1_i0_stall := rvdffie(leak1_i0_stall_in, io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n io.decode_exu.dec_extint_stall := rvdffie(io.dec_tlu_flush_extint, io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n pause_state := rvdffie(pause_state_in, io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n tlu_wr_pause_r1 := rvdffie(io.dec_tlu_wr_pause_r, io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n tlu_wr_pause_r2 := rvdffie(tlu_wr_pause_r1, io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n illegal_lockout := rvdffie(illegal_lockout_in, io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n postsync_stall := rvdffie(ps_stall_in, io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n\n val lsu_trigger_match_r = rvdffie(io.lsu_trigger_match_m, io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n val lsu_pmu_misaligned_r = rvdffie(io.lsu_pmu_misaligned_m, io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n io.dec_div_active := rvdffie(div_active_in, io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n flush_final_r := rvdffie(io.exu_flush_final, io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n val debug_valid_x = rvdffie(io.dec_debug_valid_d, io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n val i0_icaf_d = io.dec_i0_icaf_d | io.dec_i0_dbecc_d\n if(BTB_ENABLE){\n i0_brp_valid := io.dec_i0_brp.valid & !leak1_mode & !i0_icaf_d\n io.decode_exu.dec_i0_predict_p_d.bits.misp := 0.U\n io.decode_exu.dec_i0_predict_p_d.bits.ataken := 0.U\n io.decode_exu.dec_i0_predict_p_d.bits.boffset := 0.U\n io.decode_exu.dec_i0_predict_p_d.bits.pcall := i0_pcall // don't mark as pcall if branch error\n io.decode_exu.dec_i0_predict_p_d.bits.pja := i0_pja\n io.decode_exu.dec_i0_predict_p_d.bits.pret := i0_pret\n io.decode_exu.dec_i0_predict_p_d.bits.prett := io.dec_i0_brp.bits.prett\n io.decode_exu.dec_i0_predict_p_d.bits.pc4 := io.dec_i0_pc4_d\n io.decode_exu.dec_i0_predict_p_d.bits.hist := io.dec_i0_brp.bits.hist\n io.decode_exu.dec_i0_predict_p_d.valid := i0_brp_valid & i0_legal_decode_d\n val i0_notbr_error = i0_brp_valid & !(i0_dp_raw.condbr | i0_pcall_raw | i0_pja_raw | i0_pret_raw)\n\n // no toffset error for a pret\n val i0_br_toffset_error = i0_brp_valid & io.dec_i0_brp.bits.hist(1) & (io.dec_i0_brp.bits.toffset =/= i0_br_offset) & !i0_pret_raw\n val i0_ret_error = i0_brp_valid & (io.dec_i0_brp.bits.ret ^ i0_pret_raw)\n val i0_br_error = io.dec_i0_brp.bits.br_error | i0_notbr_error | i0_br_toffset_error | i0_ret_error\n io.decode_exu.dec_i0_predict_p_d.bits.br_error := i0_br_error & i0_legal_decode_d & !leak1_mode\n io.decode_exu.dec_i0_predict_p_d.bits.br_start_error := io.dec_i0_brp.bits.br_start_error & i0_legal_decode_d & !leak1_mode\n io.decode_exu.i0_predict_index_d := io.dec_i0_bp_index\n io.decode_exu.i0_predict_btag_d := io.dec_i0_bp_btag\n i0_br_error_all := (i0_br_error | io.dec_i0_brp.bits.br_start_error) & !leak1_mode\n io.decode_exu.dec_i0_predict_p_d.bits.toffset := i0_br_offset\n io.decode_exu.i0_predict_fghr_d := io.dec_i0_bp_fghr\n io.decode_exu.dec_i0_predict_p_d.bits.way := io.dec_i0_brp.bits.way\n if(BTB_FULLYA){\n\n io.dec_fa_error_index := withClock(io.active_clk){RegNext(fa_error_index_ns,0.U)}\n val btb_error_found_f = withClock(io.active_clk){RegNext(btb_error_found,0.B)}\n btb_error_found := (i0_br_error_all | btb_error_found_f) & ~io.dec_tlu_flush_lower_r\n fa_error_index_ns := Mux(i0_br_error_all & ~btb_error_found_f, io.dec_i0_bp_fa_index , io.dec_fa_error_index)\n\n }else{\n io.dec_fa_error_index := 0.U\n }\n\n }else{\n io.decode_exu.dec_i0_predict_p_d := 0.U\n io.decode_exu.dec_i0_predict_p_d.bits.pcall := i0_pcall // don't mark as pcall if branch error\n io.decode_exu.dec_i0_predict_p_d.bits.pja := i0_pja\n io.decode_exu.dec_i0_predict_p_d.bits.pret := i0_pret\n io.decode_exu.dec_i0_predict_p_d.bits.pc4 := io.dec_i0_pc4_d\n\n i0_br_error_all := 0.U\n io.decode_exu.i0_predict_index_d := 0.U\n io.decode_exu.i0_predict_btag_d := 0.U\n io.decode_exu.i0_predict_fghr_d := 0.U\n i0_brp_valid := 0.U\n }\n\n // end\n\n // on br error turn anything into a nop\n // on i0 instruction fetch access fault turn anything into a nop\n // nop => alu rs1 imm12 rd lor\n\n val i0_instr_error = i0_icaf_d\n i0_dp := i0_dp_raw\n when((i0_br_error_all | i0_instr_error).asBool){\n i0_dp := 0.U.asTypeOf(i0_dp)\n i0_dp.alu := 1.B\n i0_dp.rs1 := 1.B\n i0_dp.rs2 := 1.B\n i0_dp.lor := 1.B\n i0_dp.legal := 1.B\n i0_dp.postsync := 1.B\n }\n\n val i0 = io.dec_i0_instr_d\n io.decode_exu.dec_i0_select_pc_d := i0_dp.pc\n\n // branches that can be predicted\n val i0_predict_br = i0_dp.condbr | i0_pcall | i0_pja | i0_pret\n val i0_predict_nt = !(io.dec_i0_brp.bits.hist(1) & i0_brp_valid) & i0_predict_br\n val i0_predict_t = (io.dec_i0_brp.bits.hist(1) & i0_brp_valid) & i0_predict_br\n val i0_ap_pc2 = !io.dec_i0_pc4_d\n val i0_ap_pc4 = io.dec_i0_pc4_d\n io.decode_exu.i0_ap.predict_nt := i0_predict_nt\n io.decode_exu.i0_ap.predict_t := i0_predict_t\n\n\n io.decode_exu.i0_ap.add := i0_dp.add\n io.decode_exu.i0_ap.sub := i0_dp.sub\n io.decode_exu.i0_ap.land := i0_dp.land\n io.decode_exu.i0_ap.lor := i0_dp.lor\n io.decode_exu.i0_ap.lxor := i0_dp.lxor\n io.decode_exu.i0_ap.sll := i0_dp.sll\n io.decode_exu.i0_ap.srl := i0_dp.srl\n io.decode_exu.i0_ap.sra := i0_dp.sra\n io.decode_exu.i0_ap.slt := i0_dp.slt\n io.decode_exu.i0_ap.unsign := i0_dp.unsign\n io.decode_exu.i0_ap.beq := i0_dp.beq\n io.decode_exu.i0_ap.bne := i0_dp.bne\n io.decode_exu.i0_ap.blt := i0_dp.blt\n io.decode_exu.i0_ap.bge := i0_dp.bge\n io.decode_exu.i0_ap.clz := i0_dp.clz\n io.decode_exu.i0_ap.ctz := i0_dp.ctz\n io.decode_exu.i0_ap.pcnt := i0_dp.pcnt\n io.decode_exu.i0_ap.sext_b := i0_dp.sext_b\n io.decode_exu.i0_ap.sext_h := i0_dp.sext_h\n io.decode_exu.i0_ap.sh1add := i0_dp.sh1add\n io.decode_exu.i0_ap.sh2add := i0_dp.sh2add\n io.decode_exu.i0_ap.sh3add := i0_dp.sh3add\n io.decode_exu.i0_ap.zba := i0_dp.zba\n io.decode_exu.i0_ap.slo := i0_dp.slo\n io.decode_exu.i0_ap.sro := i0_dp.sro\n io.decode_exu.i0_ap.min := i0_dp.min\n io.decode_exu.i0_ap.max := i0_dp.max\n io.decode_exu.i0_ap.pack := i0_dp.pack\n io.decode_exu.i0_ap.packu := i0_dp.packu\n io.decode_exu.i0_ap.packh := i0_dp.packh\n io.decode_exu.i0_ap.rol := i0_dp.rol\n io.decode_exu.i0_ap.ror := i0_dp.ror\n io.decode_exu.i0_ap.grev := i0_dp.grev\n io.decode_exu.i0_ap.gorc := i0_dp.gorc\n io.decode_exu.i0_ap.zbb := i0_dp.zbb\n io.decode_exu.i0_ap.sbset := i0_dp.sbset\n io.decode_exu.i0_ap.sbclr := i0_dp.sbclr\n io.decode_exu.i0_ap.sbinv := i0_dp.sbinv\n io.decode_exu.i0_ap.sbext := i0_dp.sbext\n io.decode_exu.i0_ap.csr_write := i0_csr_write_only_d\n io.decode_exu.i0_ap.csr_imm := i0_dp.csr_imm\n io.decode_exu.i0_ap.jal := i0_jal\n\n // non block load cam logic\n // val found=Wire(UInt(1.W))\n cam_wen := Mux1H((0 until LSU_NUM_NBLOAD).map(i=>(0 to i).map(j=> if(i==j) !cam(j).valid else cam(j).valid).reduce(_.asBool&_.asBool).asBool -> (cam_write << i)))\n\n cam_write := io.dctl_busbuff.lsu_nonblock_load_valid_m\n val cam_write_tag = io.dctl_busbuff.lsu_nonblock_load_tag_m(LSU_NUM_NBLOAD_WIDTH-1,0)\n\n val cam_inv_reset = io.dctl_busbuff.lsu_nonblock_load_inv_r\n val cam_inv_reset_tag = io.dctl_busbuff.lsu_nonblock_load_inv_tag_r\n\n val cam_data_reset = io.dctl_busbuff.lsu_nonblock_load_data_valid | io.dctl_busbuff.lsu_nonblock_load_data_error\n val cam_data_reset_tag = io.dctl_busbuff.lsu_nonblock_load_data_tag\n\n val nonblock_load_rd = Mux(x_d.bits.i0load.asBool, x_d.bits.i0rd, 0.U(5.W)) // rd data\n val load_data_tag = io.dctl_busbuff.lsu_nonblock_load_data_tag\n // case of multiple loads to same dest ie. x1 ... you have to invalidate the older one\n // don't writeback a nonblock load\n val nonblock_load_valid_m_delay=withClock(io.active_clk){RegEnable(io.dctl_busbuff.lsu_nonblock_load_valid_m,0.U, i0_r_ctl_en.asBool)}\n val i0_load_kill_wen_r = nonblock_load_valid_m_delay & r_d.bits.i0load\n for(i <- 0 until LSU_NUM_NBLOAD){\n cam_inv_reset_val(i) := cam_inv_reset & (cam_inv_reset_tag === cam(i).bits.tag) & cam(i).valid\n cam_data_reset_val(i) := cam_data_reset & (cam_data_reset_tag === cam(i).bits.tag) & cam_raw(i).valid\n cam_in(i):=0.U.asTypeOf(cam(0))\n cam(i):=cam_raw(i)\n\n when(cam_data_reset_val(i).asBool){\n cam(i).valid := 0.U(1.W)\n }\n when(cam_wen(i).asBool){\n cam_in(i).valid := 1.U(1.W)\n cam_in(i).bits.wb := 0.U(1.W)\n cam_in(i).bits.tag := cam_write_tag\n cam_in(i).bits.rd := nonblock_load_rd\n }.elsewhen(cam_inv_reset_val(i).asBool || (i0_wen_r.asBool && (r_d_in.bits.i0rd === cam(i).bits.rd) && cam(i).bits.wb.asBool)){\n cam_in(i).valid := 0.U\n }.otherwise{\n cam_in(i) := cam(i)\n }\n when(nonblock_load_valid_m_delay===1.U && (io.dctl_busbuff.lsu_nonblock_load_inv_tag_r === cam(i).bits.tag) && cam(i).valid===1.U){\n cam_in(i).bits.wb := 1.U\n }\n // force debug halt forces cam valids to 0 highest priority\n when(io.dec_tlu_force_halt){\n cam_in(i).valid := 0.U\n }\n\n cam_raw(i):=rvdffie(cam_in(i),clock,reset.asAsyncReset(),io.scan_mode)\n nonblock_load_write(i) := (load_data_tag === cam_raw(i).bits.tag) & cam_raw(i).valid\n }\n\n io.dec_nonblock_load_waddr:=0.U(5.W)\n // cancel if any younger inst (including another nonblock) committing this cycle\n val nonblock_load_cancel = ((r_d_in.bits.i0rd === io.dec_nonblock_load_waddr) & i0_wen_r)\n io.dec_nonblock_load_wen := (io.dctl_busbuff.lsu_nonblock_load_data_valid && nonblock_load_write.reduce(_|_).asBool && !nonblock_load_cancel)\n val i0_nonblock_boundary_stall = ((nonblock_load_rd===i0r.rs1) & io.dctl_busbuff.lsu_nonblock_load_valid_m & io.decode_exu.dec_i0_rs1_en_d)|((nonblock_load_rd===i0r.rs2) & io.dctl_busbuff.lsu_nonblock_load_valid_m & io.decode_exu.dec_i0_rs2_en_d)\n\n i0_nonblock_load_stall := i0_nonblock_boundary_stall\n\n val cal_temp= for(i <-0 until LSU_NUM_NBLOAD) yield ((Fill(5,nonblock_load_write(i)) & cam(i).bits.rd), io.decode_exu.dec_i0_rs1_en_d & cam(i).valid & (cam(i).bits.rd === i0r.rs1), io.decode_exu.dec_i0_rs2_en_d & cam(i).valid & (cam(i).bits.rd === i0r.rs2))\n val (waddr, ld_stall_1, ld_stall_2) = (cal_temp.map(_._1).reduce(_|_) , cal_temp.map(_._2).reduce(_|_), cal_temp.map(_._3).reduce(_|_) )\n io.dec_nonblock_load_waddr:=waddr\n i0_nonblock_load_stall:=ld_stall_1 | ld_stall_2 | i0_nonblock_boundary_stall\n //i0_nonblock_load_stall:=ld_stall_2\n\n // end non block load cam logic\n\n // pmu start\n\n val csr_read = csr_ren_qual_d\n val csr_write = io.dec_csr_wen_unq_d\n val i0_br_unpred = i0_dp.jal & !i0_predict_br\n\n // the classes must be mutually exclusive with one another\n import inst_pkt_t._\n d_t.pmu_i0_itype :=Fill(4,i0_legal_decode_d) & MuxCase(NULL ,Array(\n i0_dp.jal -> JAL,\n i0_dp.condbr -> CONDBR,\n i0_dp.mret -> MRET,\n i0_dp.fence_i -> FENCEI,\n i0_dp.fence -> FENCE,\n i0_dp.ecall -> ECALL,\n i0_dp.ebreak -> EBREAK,\n ( csr_read & csr_write).asBool -> CSRRW,\n (!csr_read & csr_write).asBool -> CSRWRITE,\n ( csr_read & !csr_write).asBool -> CSRREAD,\n (i0_dp.zbb | i0_dp.zbs | i0_dp.zbe | i0_dp.zbc | i0_dp.zbp | i0_dp.zbr | i0_dp.zbf | i0_dp.zba) -> BITMANIPU,\n i0_dp.pm_alu -> ALU,\n i0_dp.store -> STORE,\n i0_dp.load -> LOAD,\n i0_dp.mul -> MUL))\n // end pmu\n\n val i0_dec =Module(new dec_dec_ctl)\n i0_dec.io.ins:= i0\n i0_dp_raw:=i0_dec.io.out\n\n lsu_idle:=withClock(io.active_clk){RegNext(io.lsu_idle_any,0.U)}\n\n // can't make this clock active_clock\n leak1_i1_stall_in := (io.dec_tlu_flush_leak_one_r | (leak1_i1_stall & !io.dec_tlu_flush_lower_r))\n leak1_mode := leak1_i1_stall\n leak1_i0_stall_in := ((io.dec_i0_decode_d & leak1_i1_stall) | (leak1_i0_stall & !io.dec_tlu_flush_lower_r))\n\n // 12b jal's can be predicted - these are calls\n\n val i0_pcall_imm = Cat(i0(31),i0(19,12),i0(20),i0(30,21))\n val i0_pcall_12b_offset = Mux(i0_pcall_imm(11).asBool, i0_pcall_imm(19,12) === 0xff.U , i0_pcall_imm(19,12) === 0.U(8.W))\n val i0_pcall_case = i0_pcall_12b_offset & i0_dp_raw.imm20 & (i0r.rd === 1.U(5.W) | i0r.rd === 5.U(5.W))\n val i0_pja_case = i0_pcall_12b_offset & i0_dp_raw.imm20 & !(i0r.rd === 1.U(5.W) | i0r.rd === 5.U(5.W))\n i0_pcall_raw := i0_dp_raw.jal & i0_pcall_case // this includes ja\n i0_pcall := i0_dp.jal & i0_pcall_case\n i0_pja_raw := i0_dp_raw.jal & i0_pja_case\n i0_pja := i0_dp.jal & i0_pja_case\n i0_br_offset := Mux((i0_pcall_raw | i0_pja_raw).asBool, i0_pcall_imm(11,0) , Cat(i0(31),i0(7),i0(30,25),i0(11,8)))\n // jalr with rd==0, rs1==1 or rs1==5 is a ret\n val i0_pret_case = (i0_dp_raw.jal & i0_dp_raw.imm12 & (i0r.rd === 0.U(5.W)) & (i0r.rs1===1.U(5.W) | i0r.rs1 === 5.U(5.W)))\n i0_pret_raw := i0_dp_raw.jal & i0_pret_case\n i0_pret := i0_dp.jal & i0_pret_case\n i0_jal := i0_dp.jal & !i0_pcall_case & !i0_pja_case & !i0_pret_case\n ///////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n io.dec_div.div_p.valid := div_decode_d\n io.dec_div.div_p.bits.unsign := i0_dp.unsign\n io.dec_div.div_p.bits.rem := i0_dp.rem\n\n io.decode_exu.mul_p.valid := mul_decode_d\n io.decode_exu.mul_p.bits.rs1_sign := i0_dp.rs1_sign\n io.decode_exu.mul_p.bits.rs2_sign := i0_dp.rs2_sign\n io.decode_exu.mul_p.bits.low := i0_dp.low\n io.decode_exu.mul_p.bits.bext := i0_dp.bext\n io.decode_exu.mul_p.bits.bdep := i0_dp.bdep\n io.decode_exu.mul_p.bits.clmul := i0_dp.clmul\n io.decode_exu.mul_p.bits.clmulh := i0_dp.clmulh\n io.decode_exu.mul_p.bits.clmulr := i0_dp.clmulr\n io.decode_exu.mul_p.bits.grev := i0_dp.grev\n io.decode_exu.mul_p.bits.gorc := i0_dp.gorc\n io.decode_exu.mul_p.bits.shfl := i0_dp.shfl\n io.decode_exu.mul_p.bits.unshfl := i0_dp.unshfl\n io.decode_exu.mul_p.bits.crc32_b := i0_dp.crc32_b\n io.decode_exu.mul_p.bits.crc32_h := i0_dp.crc32_h\n io.decode_exu.mul_p.bits.crc32_w := i0_dp.crc32_w\n io.decode_exu.mul_p.bits.crc32c_b := i0_dp.crc32c_b\n io.decode_exu.mul_p.bits.crc32c_h := i0_dp.crc32c_h\n io.decode_exu.mul_p.bits.crc32c_w := i0_dp.crc32c_w\n io.decode_exu.mul_p.bits.bfp := i0_dp.bfp\n\n\n io.lsu_p := 0.U.asTypeOf(io.lsu_p)\n when (io.decode_exu.dec_extint_stall){\n io.lsu_p.bits.load := 1.U(1.W)\n io.lsu_p.bits.word := 1.U(1.W)\n io.lsu_p.bits.fast_int := 1.U(1.W)\n io.lsu_p.valid := 1.U(1.W)\n\n\n }.otherwise {\n io.lsu_p.valid := lsu_decode_d\n io.lsu_p.bits.load := i0_dp.load\n io.lsu_p.bits.store := i0_dp.store\n io.lsu_p.bits.by := i0_dp.by\n io.lsu_p.bits.half := i0_dp.half\n io.lsu_p.bits.word := i0_dp.word\n io.lsu_p.bits.stack := (i0r.rs1 === 2.U(5.W)) // stack reference\n io.lsu_p.bits.load_ldst_bypass_d := load_ldst_bypass_d\n io.lsu_p.bits.store_data_bypass_d := store_data_bypass_d\n io.lsu_p.bits.store_data_bypass_m := store_data_bypass_m\n io.lsu_p.bits.unsign := i0_dp.unsign\n }\n\n //////////////////////////////////////\n io.dec_alu.dec_csr_ren_d := i0_dp.csr_read & io.dec_ib0_valid_d//H: ing csr read enable signal decoded from decode_ctl going as input to EXU\n csr_ren_qual_d := i0_dp.csr_read & i0_legal_decode_d.asBool //csr_ren_qual_d ed as csr_read above\n\n val i0_csr_write = i0_dp.csr_write & !io.dec_debug_fence_d\n val csr_clr_d = i0_dp.csr_clr & i0_legal_decode_d.asBool\n val csr_set_d = i0_dp.csr_set & i0_legal_decode_d.asBool\n val csr_write_d = i0_csr_write & i0_legal_decode_d.asBool\n\n i0_csr_write_only_d := i0_csr_write & !i0_dp.csr_read\n io.dec_csr_wen_unq_d := (i0_dp.csr_clr | i0_dp.csr_set | i0_csr_write) & io.dec_ib0_valid_d // for csr legal, can't write read-only csr\n //dec_csr_wen_unq_d ed as csr_write above\n val any_csr_d = i0_dp.csr_read | i0_csr_write\n io.dec_csr_any_unq_d := any_csr_d & io.dec_ib0_valid_d\n io.dec_csr_rdaddr_d := Fill(12,io.dec_csr_any_unq_d) & i0(31,20)\n io.dec_csr_wraddr_r := Fill(12,(r_d.bits.csrwen & r_d.valid)) & r_d.bits.csrwaddr //r_d is a dest_pkt\n\n // make sure csr doesn't write same cycle as dec_tlu_flush_lower_wb\n // also use valid so it's flushable\n io.dec_csr_wen_r := r_d.bits.csrwen & r_d.valid & !io.dec_tlu_i0_kill_writeb_r\n\n // If we are writing MIE or MSTATUS, hold off the external interrupt for a cycle on the write.\n io.dec_csr_stall_int_ff := ((r_d.bits.csrwaddr === \"h300\".U) | (r_d.bits.csrwaddr === \"h304\".U)) & r_d.bits.csrwen & r_d.valid & !io.dec_tlu_i0_kill_writeb_wb\n\n val csr_read_x = withClock(io.active_clk){RegNext(csr_ren_qual_d,init=0.B)}\n val csr_clr_x = withClock(io.active_clk){RegNext(csr_clr_d, init=0.B)}\n", "right_context": " val csr_write_x = withClock(io.active_clk){RegNext(csr_write_d, init=0.B)}\n val csr_imm_x = withClock(io.active_clk){RegNext(i0_dp.csr_imm, init=0.U)}\n\n // perform the update operation if any\n val csrimm_x = rvdffe(i0(19,15),i0_x_data_en & any_csr_d.asBool,clock,io.scan_mode)\n val csr_rddata_x = rvdffe(io.dec_csr_rddata_d,i0_x_data_en & any_csr_d.asBool,clock,io.scan_mode)\n\n val csr_mask_x = Mux1H(Seq(\n csr_imm_x.asBool -> Cat(repl(27,0.U),csrimm_x(4,0)),\n !csr_imm_x.asBool -> io.decode_exu.exu_csr_rs1_x))\n\n val write_csr_data_x = Mux1H(Seq(\n csr_clr_x -> (csr_rddata_x & (~csr_mask_x).asUInt),\n csr_set_x -> (csr_rddata_x | csr_mask_x),\n csr_write_x -> ( csr_mask_x)))\n // pause instruction\n val clear_pause = (io.dec_tlu_flush_lower_r & !io.dec_tlu_flush_pause_r) | (pause_state & (write_csr_data === Cat(Fill(31,0.U),write_csr_data(0)))) // if 0 or 1 then exit pause state - 1 cycle pause\n pause_state_in := (io.dec_tlu_wr_pause_r | pause_state) & !clear_pause\n io.dec_pause_state := pause_state\n //pause for clock gating\n io.dec_pause_state_cg := (pause_state & (!tlu_wr_pause_r1 && !tlu_wr_pause_r2))\n // end pause\n\n val write_csr_data_in = Mux(pause_state,(write_csr_data - 1.U(32.W)),\n Mux(io.dec_tlu_wr_pause_r,io.dec_csr_wrdata_r,write_csr_data_x))\n val csr_data_wen = ((csr_clr_x | csr_set_x | csr_write_x) & csr_read_x) | io.dec_tlu_wr_pause_r | pause_state\n write_csr_data := rvdffe(write_csr_data_in,csr_data_wen,io.free_l2clk,io.scan_mode)\n\n // will hold until write-back at which time the CSR will be updated while GPR is possibly written with prior CSR\n val pause_stall = pause_state\n\n // for csr write only data is produced by the alu\n io.dec_csr_wrdata_r := Mux((r_d.bits.csrwonly & r_d.valid).asBool,i0_result_corr_r,write_csr_data)\n\n val prior_csr_write = x_d.bits.csrwonly | r_d.bits.csrwonly | wbd.bits.csrwonly\n\n val debug_fence_i = io.dec_debug_fence_d & io.dbg_dctl.dbg_cmd_wrdata(0)\n val debug_fence_raw = io.dec_debug_fence_d & io.dbg_dctl.dbg_cmd_wrdata(1)\n debug_fence := debug_fence_raw | debug_fence_i\n\n // some CSR reads need to be presync'd\n val i0_presync = i0_dp.presync | io.dec_tlu_presync_d | debug_fence_i | debug_fence_raw | io.dec_tlu_pipelining_disable // both fence's presync\n\n // some CSR writes need to be postsync'd\n val i0_postsync = i0_dp.postsync | io.dec_tlu_postsync_d | debug_fence_i | (i0_csr_write_only_d & (i0(31,20) === \"h7c2\".U))\n val bitmanip_legal = WireInit(Bool(),0.B)\n val i0_legal = i0_dp.legal & (!any_csr_d | io.dec_csr_legal_d) & bitmanip_legal\n val i0_inst_d = Mux(io.dec_i0_pc4_d,i0,Cat(repl(16,0.U), io.dec_aln.ifu_i0_cinst))\n // illegal inst handling\n\n val shift_illegal = io.dec_i0_decode_d & !i0_legal//lm: valid but not legal\n val illegal_inst_en = shift_illegal & !illegal_lockout\n io.dec_illegal_inst := rvdffe(i0_inst_d,illegal_inst_en,clock,io.scan_mode)\n illegal_lockout_in := (shift_illegal | illegal_lockout) & !flush_final_r\n val i0_div_prior_div_stall = i0_dp.div & io.dec_div_active\n //stalls signals\n val i0_block_raw_d = (i0_dp.csr_read & prior_csr_write) | io.decode_exu.dec_extint_stall | pause_stall |\n leak1_i0_stall | io.dec_tlu_debug_stall | postsync_stall | presync_stall |\n ((i0_dp.fence | debug_fence) & !lsu_idle) | i0_nonblock_load_stall |\n i0_load_block_d | i0_nonblock_div_stall | i0_div_prior_div_stall\n\n val i0_store_stall_d = i0_dp.store & (io.lsu_store_stall_any | io.dctl_dma.dma_dccm_stall_any)\n val i0_load_stall_d = i0_dp.load & (io.lsu_load_stall_any | io.dctl_dma.dma_dccm_stall_any)\n val i0_block_d = i0_block_raw_d | i0_store_stall_d | i0_load_stall_d\n val i0_exublock_d = i0_block_raw_d\n\n //decode valid\n io.dec_i0_decode_d := io.dec_ib0_valid_d & !i0_block_d & !io.dec_tlu_flush_lower_r & !flush_final_r\n val i0_exudecode_d = io.dec_ib0_valid_d & !i0_exublock_d & !io.dec_tlu_flush_lower_r & !flush_final_r\n val i0_exulegal_decode_d = i0_exudecode_d & i0_legal\n\n // performance monitor signals\n io.dec_pmu_instr_decoded := io.dec_i0_decode_d\n io.dec_pmu_decode_stall := io.dec_ib0_valid_d & !io.dec_i0_decode_d\n io.dec_pmu_postsync_stall := postsync_stall.asBool & io.dec_ib0_valid_d\n io.dec_pmu_presync_stall := presync_stall.asBool & io.dec_ib0_valid_d\n\n val prior_inflight_x = x_d.valid\n val prior_inflight_wb = r_d.valid\n val prior_inflight = prior_inflight_x | prior_inflight_wb\n val prior_inflight_eff = Mux(i0_dp.div,prior_inflight_x,prior_inflight)\n\n presync_stall := (i0_presync & prior_inflight_eff)\n // illegals will postsync\n ps_stall_in := (io.dec_i0_decode_d & (i0_postsync | !i0_legal) ) | ( postsync_stall & prior_inflight_x)\n\n io.dec_alu.dec_i0_alu_decode_d := i0_exulegal_decode_d & i0_dp.alu\n io.decode_exu.dec_i0_branch_d := i0_dp.condbr | i0_dp.jal | i0_br_error_all\n\n lsu_decode_d := i0_legal_decode_d & i0_dp.lsu\n mul_decode_d := i0_exulegal_decode_d & i0_dp.mul\n div_decode_d := i0_exulegal_decode_d & i0_dp.div\n io.decode_exu.dec_qual_lsu_d := i0_dp.lsu\n io.dec_tlu_i0_valid_r := r_d.valid & !io.dec_tlu_flush_lower_wb\n\n //traps for TLU (tlu stuff)\n d_t.legal := i0_legal_decode_d\n d_t.icaf := i0_icaf_d & i0_legal_decode_d // dbecc is icaf exception\n d_t.icaf_second := io.dec_i0_icaf_second_d & i0_legal_decode_d // this includes icaf and dbecc\n d_t.icaf_type := io.dec_i0_icaf_type_d\n\n d_t.fence_i := (i0_dp.fence_i | debug_fence_i) & i0_legal_decode_d\n\n // put pmu info into the trap packet\n d_t.pmu_i0_br_unpred := i0_br_unpred\n d_t.pmu_divide := 0.U(1.W)\n d_t.pmu_lsu_misaligned := 0.U(1.W)\n\n d_t.i0trigger := io.dec_i0_trigger_match_d & repl(4,io.dec_i0_decode_d)\n\n\n x_t := rvdfflie(d_t,clock,reset.asAsyncReset,i0_x_ctl_en.asBool,io.scan_mode, elements = 3)\n\n x_t_in := x_t\n x_t_in.i0trigger := x_t.i0trigger & ~(repl(4,io.dec_tlu_flush_lower_wb))\n\n r_t := rvdfflie(x_t_in,clock,reset.asAsyncReset,i0_x_ctl_en.asBool,io.scan_mode, elements = 3)\n\n r_t_in := r_t\n\n r_t_in.i0trigger := (repl(4,(r_d.bits.i0load | r_d.bits.i0store)) & lsu_trigger_match_r) | r_t.i0trigger\n r_t_in.pmu_lsu_misaligned := lsu_pmu_misaligned_r // only valid if a load/store is valid in DC3 stage\n\n when (io.dec_tlu_flush_lower_wb.asBool) {r_t_in := 0.U.asTypeOf(r_t_in) }\n\n io.dec_tlu_packet_r := r_t_in\n io.dec_tlu_packet_r.pmu_divide := r_d.bits.i0div & r_d.valid\n // end tlu stuff\n\n\n io.dec_i0_decode_d := io.dec_ib0_valid_d & !i0_block_d & !io.dec_tlu_flush_lower_r & !flush_final_r\n\n i0r.rs1 := i0(19,15) //H: ing reg packets the instructions bits\n i0r.rs2 := i0(24,20)\n i0r.rd := i0(11,7)\n\n io.decode_exu.dec_i0_rs1_en_d := i0_dp.rs1 & (i0r.rs1 =/= 0.U(5.W)) // if rs1_en=0 then read will be all 0's\n io.decode_exu.dec_i0_rs2_en_d := i0_dp.rs2 & (i0r.rs2 =/= 0.U(5.W))\n val i0_rd_en_d = i0_dp.rd & (i0r.rd =/= 0.U(5.W))\n io.dec_i0_rs1_d := i0r.rs1//H:assiging packets to output signals leading to gprfile\n io.dec_i0_rs2_d := i0r.rs2\n\n val i0_jalimm20 = i0_dp.jal & i0_dp.imm20 // H:jal (used at line 915)\n val i0_uiimm20 = !i0_dp.jal & i0_dp.imm20\n\n // io.decode_exu.dec_i0_immed_d := Mux1H(Seq(\n // i0_dp.csr_read -> io.dec_csr_rddata_d,\n // !i0_dp.csr_read -> i0_immed_d))\n\n io.decode_exu.dec_i0_immed_d := Mux1H(Seq(\n i0_dp.imm12 -> Cat(repl(20,i0(31)),i0(31,20)), // jalr\n i0_dp.shimm5 -> Cat(repl(27,0.U),i0(24,20)),\n i0_jalimm20 -> Cat(repl(12,i0(31)),i0(19,12),i0(20),i0(30,21),0.U),\n i0_uiimm20 -> Cat(i0(31,12),repl(12,0.U)),\n (i0_csr_write_only_d & i0_dp.csr_imm).asBool -> Cat(repl(27,0.U),i0(19,15)))) // for csr's that only write\n\n val bitmanip_zbb_legal = WireInit(Bool(),0.B)\n val bitmanip_zbs_legal = WireInit(Bool(),0.B)\n val bitmanip_zbe_legal = WireInit(Bool(),0.B)\n val bitmanip_zbc_legal = WireInit(Bool(),0.B)\n val bitmanip_zbp_legal = WireInit(Bool(),0.B)\n val bitmanip_zbr_legal = WireInit(Bool(),0.B)\n val bitmanip_zbf_legal = WireInit(Bool(),0.B)\n val bitmanip_zba_legal = WireInit(Bool(),0.B)\n val bitmanip_zbb_zbp_legal = WireInit(Bool(),0.B)\n\n if (BITMANIP_ZBB == 1)\n bitmanip_zbb_legal := 1.B\n else\n bitmanip_zbb_legal := !(i0_dp.zbb & !i0_dp.zbp)\n\n if (BITMANIP_ZBS == 1)\n bitmanip_zbs_legal := 1.B\n else\n bitmanip_zbs_legal := !i0_dp.zbs\n\n if (BITMANIP_ZBE == 1)\n bitmanip_zbe_legal := 1.B\n else\n bitmanip_zbe_legal := !i0_dp.zbe\n\n if (BITMANIP_ZBC == 1)\n bitmanip_zbc_legal := 1.B\n else\n bitmanip_zbc_legal := !i0_dp.zbc\n\n if (BITMANIP_ZBP == 1)\n bitmanip_zbp_legal := 1.B\n else\n bitmanip_zbp_legal := !(i0_dp.zbp & !i0_dp.zbb)\n\n if (BITMANIP_ZBR == 1)\n bitmanip_zbr_legal := 1.B\n else\n bitmanip_zbr_legal := !i0_dp.zbr\n\n if (BITMANIP_ZBF == 1)\n bitmanip_zbf_legal := 1.B\n else\n bitmanip_zbf_legal := !i0_dp.zbf\n\n if (BITMANIP_ZBA == 1)\n bitmanip_zba_legal := 1.B\n else\n bitmanip_zba_legal := !i0_dp.zba\n\n if ( (BITMANIP_ZBB == 1) | (BITMANIP_ZBP == 1) )\n bitmanip_zbb_zbp_legal := 1.B\n else\n bitmanip_zbb_zbp_legal := !(i0_dp.zbb & i0_dp.zbp)\n\n bitmanip_legal := bitmanip_zbb_legal & bitmanip_zbs_legal & bitmanip_zbe_legal & bitmanip_zbc_legal & bitmanip_zbp_legal & bitmanip_zbr_legal & bitmanip_zbf_legal & bitmanip_zba_legal & bitmanip_zbb_zbp_legal\n i0_legal_decode_d := io.dec_i0_decode_d & i0_legal\n\n i0_d_c.mul := i0_dp.mul & i0_legal_decode_d\n i0_d_c.load := i0_dp.load & i0_legal_decode_d\n i0_d_c.alu := i0_dp.alu & i0_legal_decode_d\n\n val i0_x_c = withClock(io.active_clk){RegEnable(i0_d_c,0.U.asTypeOf(i0_d_c), i0_x_ctl_en.asBool)}\n val i0_r_c = withClock(io.active_clk){RegEnable(i0_x_c,0.U.asTypeOf(i0_x_c), i0_r_ctl_en.asBool)}\n i0_pipe_en := Cat(io.dec_i0_decode_d,withClock(io.active_clk){RegNext(i0_pipe_en(3,1), init=0.U)})\n\n i0_x_ctl_en := (i0_pipe_en(3,2).orR | io.clk_override)\n i0_r_ctl_en := (i0_pipe_en(2,1).orR | io.clk_override)\n i0_wb_ctl_en := (i0_pipe_en(1,0).orR | io.clk_override)\n i0_x_data_en := ( i0_pipe_en(3) | io.clk_override)\n i0_r_data_en := ( i0_pipe_en(2) | io.clk_override)\n i0_wb_data_en := ( i0_pipe_en(1) | io.clk_override)\n\n io.decode_exu.dec_data_en := Cat(i0_x_data_en, i0_r_data_en)\n io.decode_exu.dec_ctl_en := Cat(i0_x_ctl_en, i0_r_ctl_en)\n\n d_d.bits.i0rd := i0r.rd\n d_d.bits.i0v := i0_rd_en_d & i0_legal_decode_d\n d_d.valid := io.dec_i0_decode_d // has flush_final_r\n\n d_d.bits.i0load := i0_dp.load & i0_legal_decode_d\n d_d.bits.i0store := i0_dp.store & i0_legal_decode_d\n d_d.bits.i0div := i0_dp.div & i0_legal_decode_d\n\n d_d.bits.csrwen := io.dec_csr_wen_unq_d & i0_legal_decode_d\n d_d.bits.csrwonly := i0_csr_write_only_d & io.dec_i0_decode_d\n d_d.bits.csrwaddr := Mux(d_d.bits.csrwen, i0(31,20), 0.U)\n\n x_d := rvdfflie(d_d,clock,reset.asAsyncReset(), i0_x_ctl_en.asBool,io.scan_mode,elements = 4)\n val x_d_in = Wire(Valid(new dest_pkt_t))\n x_d_in := x_d\n x_d_in.bits.i0v := x_d.bits.i0v & !io.dec_tlu_flush_lower_wb & !io.dec_tlu_flush_lower_r\n x_d_in.valid := x_d.valid & !io.dec_tlu_flush_lower_wb & !io.dec_tlu_flush_lower_r\n\n r_d := rvdfflie(x_d_in,clock,reset.asAsyncReset(),i0_r_ctl_en.asBool,io.scan_mode, elements = 4)\n r_d_in := r_d\n r_d_in.bits.i0rd := r_d.bits.i0rd\n\n r_d_in.bits.i0v := (r_d.bits.i0v & !io.dec_tlu_flush_lower_wb)\n r_d_in.valid := (r_d.valid & !io.dec_tlu_flush_lower_wb)\n r_d_in.bits.i0load := r_d.bits.i0load & !io.dec_tlu_flush_lower_wb\n r_d_in.bits.i0store := r_d.bits.i0store & !io.dec_tlu_flush_lower_wb\n\n wbd := rvdfflie(r_d_in,clock,reset.asAsyncReset(),i0_wb_ctl_en.asBool,io.scan_mode, elements = 4)\n\n io.dec_i0_waddr_r := r_d_in.bits.i0rd\n i0_wen_r := r_d_in.bits.i0v & !io.dec_tlu_i0_kill_writeb_r\n io.dec_i0_wen_r := i0_wen_r & !r_d_in.bits.i0div & !i0_load_kill_wen_r // don't write a nonblock load 1st time down the pipe\n io.dec_i0_wdata_r := i0_result_corr_r\n\n\n val i0_result_r_raw = rvdffe(i0_result_x,(i0_r_data_en & (x_d.bits.i0v | x_d.bits.csrwen | debug_valid_x)) === 1.B,clock,io.scan_mode)\n if ( LOAD_TO_USE_PLUS1) {\n i0_result_x := io.decode_exu.exu_i0_result_x\n i0_result_r := Mux((r_d.bits.i0v & r_d.bits.i0load).asBool,io.lsu_result_m, i0_result_r_raw)\n }\n else {\n i0_result_x := Mux((x_d.bits.i0v & x_d.bits.i0load).asBool,io.lsu_result_m,io.decode_exu.exu_i0_result_x)\n i0_result_r := i0_result_r_raw\n }\n\n // correct lsu load data - don't use for bypass, do pass down the pipe\n i0_result_corr_r := Mux((r_d.bits.i0v & r_d.bits.i0load).asBool,io.lsu_result_corr_r,i0_result_r_raw)\n io.dec_alu.dec_i0_br_immed_d := Mux((io.decode_exu.i0_ap.predict_nt & !i0_dp.jal).asBool,i0_br_offset,Cat(repl(10,0.U),i0_ap_pc4,i0_ap_pc2))\n val last_br_immed_d = WireInit(UInt(12.W),0.U)\n last_br_immed_d := Mux((io.decode_exu.i0_ap.predict_nt).asBool,Cat(repl(10,0.U),i0_ap_pc4,i0_ap_pc2),i0_br_offset)\n val last_br_immed_x = WireInit(UInt(12.W),0.U)\n last_br_immed_x := rvdffe(last_br_immed_d,i0_x_data_en.asBool,clock,io.scan_mode)\n\n // divide stuff\n\n val div_e1_to_r = (x_d.bits.i0div & x_d.valid) | (r_d.bits.i0div & r_d.valid)\n\n val div_flush = (x_d.bits.i0div & x_d.valid & (x_d.bits.i0rd === 0.U(5.W))) |\n (x_d.bits.i0div & x_d.valid & io.dec_tlu_flush_lower_r ) |\n (r_d.bits.i0div & r_d.valid & io.dec_tlu_flush_lower_r & io.dec_tlu_i0_kill_writeb_r)\n\n // cancel if any younger inst committing this cycle to same dest as nonblock divide\n\n val nonblock_div_cancel = (io.dec_div_active & div_flush) |\n (io.dec_div_active & !div_e1_to_r & (r_d.bits.i0rd === io.div_waddr_wb) & i0_wen_r)\n\n io.dec_div.dec_div_cancel := nonblock_div_cancel.asBool\n val i0_div_decode_d = i0_legal_decode_d & i0_dp.div\n\n div_active_in := i0_div_decode_d | (io.dec_div_active & !io.exu_div_wren & !nonblock_div_cancel)\n\n // io.dec_div_active := withClock(io.free_l2clk){RegNext(div_active_in, 0.U)}\n\n // nonblocking div scheme\n i0_nonblock_div_stall := (io.decode_exu.dec_i0_rs1_en_d & io.dec_div_active & (io.div_waddr_wb === i0r.rs1)) |\n (io.decode_exu.dec_i0_rs2_en_d & io.dec_div_active & (io.div_waddr_wb === i0r.rs2))\n\n\n ///div end\n\n //for tracing instruction\n val i0_wb_en = i0_wb_data_en\n val trace_enable = ~io.dec_tlu_trace_disable\n\n io.div_waddr_wb := rvdffe(i0r.rd,i0_div_decode_d.asBool(),clock,io.scan_mode)\n\n val i0_inst_x = rvdffe(i0_inst_d,(i0_x_data_en & trace_enable),clock,io.scan_mode)\n val i0_inst_r = rvdffe(i0_inst_x,(i0_r_data_en & trace_enable),clock,io.scan_mode)\n val i0_inst_wb_in = i0_inst_r\n val i0_inst_wb = rvdffe(i0_inst_wb_in,(i0_wb_en & trace_enable),clock,io.scan_mode)\n val i0_pc_wb = rvdffe(io.dec_tlu_i0_pc_r,(i0_wb_en & trace_enable),clock,io.scan_mode)\n\n io.dec_i0_inst_wb := i0_inst_wb\n io.dec_i0_pc_wb := i0_pc_wb\n val dec_i0_pc_r = rvdffpcie(io.dec_alu.exu_i0_pc_x,i0_r_data_en.asBool,reset.asAsyncReset(),clock,io.scan_mode)\n\n io.dec_tlu_i0_pc_r := dec_i0_pc_r\n\n //end tracing\n\n val temp_pred_correct_npc_x = rvbradder(Cat(io.dec_alu.exu_i0_pc_x,0.U),Cat(last_br_immed_x,0.U))\n io.decode_exu.pred_correct_npc_x := temp_pred_correct_npc_x(31,1)\n\n // scheduling logic for primary alu's\n\n val i0_rs1_depend_i0_x = io.decode_exu.dec_i0_rs1_en_d & x_d.bits.i0v & (x_d.bits.i0rd === i0r.rs1)\n val i0_rs1_depend_i0_r = io.decode_exu.dec_i0_rs1_en_d & r_d.bits.i0v & (r_d.bits.i0rd === i0r.rs1)\n\n val i0_rs2_depend_i0_x = io.decode_exu.dec_i0_rs2_en_d & x_d.bits.i0v & (x_d.bits.i0rd === i0r.rs2)\n val i0_rs2_depend_i0_r = io.decode_exu.dec_i0_rs2_en_d & r_d.bits.i0v & (r_d.bits.i0rd === i0r.rs2)\n // order the producers as follows: , i0_x, i0_r, i0_wb\n i0_rs1_class_d := Mux(i0_rs1_depend_i0_x.asBool,i0_x_c,Mux(i0_rs1_depend_i0_r.asBool, i0_r_c, 0.U.asTypeOf(i0_rs1_class_d)))\n i0_rs1_depth_d := Mux(i0_rs1_depend_i0_x.asBool,1.U(2.W),Mux(i0_rs1_depend_i0_r.asBool, 2.U(2.W), 0.U))\n i0_rs2_class_d := Mux(i0_rs2_depend_i0_x.asBool,i0_x_c,Mux(i0_rs2_depend_i0_r.asBool, i0_r_c, 0.U.asTypeOf(i0_rs2_class_d)))\n i0_rs2_depth_d := Mux(i0_rs2_depend_i0_x.asBool,1.U(2.W),Mux(i0_rs2_depend_i0_r.asBool, 2.U(2.W), 0.U))\n\n // stores will bypass load data in the lsu pipe\n if (LOAD_TO_USE_PLUS1) {\n i0_load_block_d := (i0_rs1_class_d.load & i0_rs1_depth_d) | (i0_rs2_class_d.load & i0_rs2_depth_d(0) & !i0_dp.store)\n load_ldst_bypass_d := (i0_dp.load | i0_dp.store) & i0_rs1_depth_d(1) & i0_rs1_class_d.load\n store_data_bypass_d := i0_dp.store & (i0_rs2_depth_d(1) & i0_rs2_class_d.load)\n store_data_bypass_m := i0_dp.store & (i0_rs2_depth_d(0) & i0_rs2_class_d.load)\n }\n else {\n i0_load_block_d := 0.B\n load_ldst_bypass_d := (i0_dp.load | i0_dp.store) & i0_rs1_depth_d(0) & i0_rs1_class_d.load\n store_data_bypass_d := i0_dp.store & i0_rs2_depth_d(0) & i0_rs2_class_d.load\n store_data_bypass_m := 0.B\n }\n // add nonblock load rs1/rs2 bypass cases\n\n val i0_rs1_nonblock_load_bypass_en_d = io.decode_exu.dec_i0_rs1_en_d & io.dec_nonblock_load_wen & (io.dec_nonblock_load_waddr === i0r.rs1)\n\n val i0_rs2_nonblock_load_bypass_en_d = io.decode_exu.dec_i0_rs2_en_d & io.dec_nonblock_load_wen & (io.dec_nonblock_load_waddr === i0r.rs2)\n\n // bit 2 is priority match, bit 0 lowest priority\t, i0_x, i0_r\n i0_rs1bypass := Cat((i0_rs1_depth_d(0) &(i0_rs1_class_d.alu | i0_rs1_class_d.mul)),(i0_rs1_depth_d(0) & (i0_rs1_class_d.load)), (i0_rs1_depth_d(1) & (i0_rs1_class_d.alu | i0_rs1_class_d.mul | i0_rs1_class_d.load)))\n\n i0_rs2bypass := Cat((i0_rs2_depth_d(0) & (i0_rs2_class_d.alu | i0_rs2_class_d.mul)),(i0_rs2_depth_d(0) & (i0_rs2_class_d.load)),(i0_rs2_depth_d(1) & (i0_rs2_class_d.alu | i0_rs2_class_d.mul | i0_rs2_class_d.load)))\n\n io.decode_exu.dec_i0_rs1_bypass_en_d := Cat(!i0_rs1bypass(0) & !i0_rs1bypass(1) & !i0_rs1bypass(2) & i0_rs1_nonblock_load_bypass_en_d,i0_rs1bypass(2),i0_rs1bypass(1),i0_rs1bypass(0) )\n io.decode_exu.dec_i0_rs2_bypass_en_d := Cat(!i0_rs2bypass(0) & !i0_rs2bypass(1) & !i0_rs2bypass(2) & i0_rs2_nonblock_load_bypass_en_d,i0_rs2bypass(2),i0_rs2bypass(1),i0_rs2bypass(0) )\n\n io.decode_exu.dec_i0_result_r := i0_result_r\n\n io.dec_lsu_valid_raw_d := ((io.dec_ib0_valid_d & (i0_dp_raw.load | i0_dp_raw.store) & !io.dctl_dma.dma_dccm_stall_any & !i0_block_raw_d) | io.decode_exu.dec_extint_stall)\n io.dec_lsu_offset_d := Mux1H(Seq(\n (!io.decode_exu.dec_extint_stall & i0_dp.lsu & i0_dp.load).asBool -> i0(31,20),\n (!io.decode_exu.dec_extint_stall & i0_dp.lsu & i0_dp.store).asBool -> Cat(i0(31,25),i0(11,7))))\n}\n", "groundtruth": " val csr_set_x = withClock(io.active_clk){RegNext(csr_set_d, init=0.B)}\n", "crossfile_context": ""}
{"task_id": "Quasar", "path": "Quasar/design/src/main/scala/dec/dec_ib_ctl.scala", "left_context": "package dec\n\nimport chisel3._\nimport chisel3.util._\nimport exu._\nimport include._\nimport lib._\n\n", "right_context": " val dec_i0_icaf_type_d =Output(UInt(2.W)) // i0 instruction access fault type\n val dec_i0_instr_d =Output(UInt(32.W)) // i0 inst at decode\n val dec_i0_pc4_d =Output(UInt(1.W)) // i0 is 4B inst else 2B\n val dec_i0_brp =Valid(new br_pkt_t) // i0 branch packet at decode\n val dec_i0_bp_index =Output(UInt(((BTB_ADDR_HI-BTB_ADDR_LO)+1).W)) // i0 branch index\n val dec_i0_bp_fghr =Output(UInt(BHT_GHR_SIZE.W)) // BP FGHR\n val dec_i0_bp_btag =Output(UInt(BTB_BTAG_SIZE.W)) // BP tag\n val ifu_i0_fa_index =Input(UInt(log2Ceil(BTB_SIZE).W))\n val dec_i0_bp_fa_index =Output(UInt(log2Ceil(BTB_SIZE).W))\n\n val dec_i0_icaf_d =Output(UInt(1.W)) // i0 instruction access fault at decode\n val dec_i0_icaf_second_d =Output(UInt(1.W)) // i0 instruction access fault at decode for f1 fetch group\n val dec_i0_dbecc_d =Output(UInt(1.W)) // i0 double-bit error at decode\n val dec_debug_fence_d =Output(UInt(1.W)) // debug fence inst\n}\n\nclass dec_ib_ctl extends Module with param{\n val io=IO(new dec_ib_ctl_IO)\n io.dec_i0_icaf_second_d :=io.ifu_ib.ifu_i0_icaf_second\n io.dec_i0_dbecc_d :=io.ifu_ib.ifu_i0_dbecc\n io.dec_i0_icaf_d :=io.ifu_ib.ifu_i0_icaf\n io.ib_exu.dec_i0_pc_d :=io.ifu_ib.ifu_i0_pc\n io.dec_i0_pc4_d :=io.ifu_ib.ifu_i0_pc4\n io.dec_i0_icaf_type_d :=io.ifu_ib.ifu_i0_icaf_type\n io.dec_i0_brp :=io.ifu_ib.i0_brp\n io.dec_i0_bp_index :=io.ifu_ib.ifu_i0_bp_index\n io.dec_i0_bp_fghr :=io.ifu_ib.ifu_i0_bp_fghr\n io.dec_i0_bp_btag :=io.ifu_ib.ifu_i0_bp_btag\n io.dec_i0_bp_fa_index := io.ifu_i0_fa_index\n\n // GPR accesses\n // put reg to read on rs1\n // read -> or %x0, %reg,%x0 {000000000000,reg[4:0],110000000110011}\n // put write date on rs1\n // write -> or %reg, %x0, %x0 {00000000000000000110,reg[4:0],0110011}\n // CSR accesses\n // csr is of form rd, csr, rs1\n // read -> csrrs %x0, %csr, %x0 {csr[11:0],00000010000001110011}\n // put write data on rs1\n // write -> csrrw %x0, %csr, %x0 {csr[11:0],00000001000001110011}\n\n\n val debug_valid =io.dbg_ib.dbg_cmd_valid & (io.dbg_ib.dbg_cmd_type =/= 2.U)\n val debug_read =debug_valid & !io.dbg_ib.dbg_cmd_write\n val debug_write =debug_valid & io.dbg_ib.dbg_cmd_write\n io.dec_debug_valid_d := debug_valid\n val debug_read_gpr = debug_read & (io.dbg_ib.dbg_cmd_type===0.U)\n val debug_write_gpr = debug_write & (io.dbg_ib.dbg_cmd_type===0.U)\n val debug_read_csr = debug_read & (io.dbg_ib.dbg_cmd_type===1.U)\n val debug_write_csr = debug_write & (io.dbg_ib.dbg_cmd_type===1.U)\n\n val dreg = io.dbg_ib.dbg_cmd_addr(4,0)\n val dcsr = io.dbg_ib.dbg_cmd_addr(11,0)\n\n val ib0_debug_in =Mux1H(Seq(\n debug_read_gpr.asBool \t-> Cat(Fill(12,0.U(1.W)),dreg,\"b110000000110011\".U),\n debug_write_gpr.asBool \t-> Cat(\"b00000000000000000110\".U(20.W),dreg,\"b0110011\".U(7.W)),\n debug_read_csr.asBool\t-> Cat(dcsr,\"b00000010000001110011\".U(20.W)),\n debug_write_csr.asBool \t-> Cat(dcsr,\"b00000001000001110011\".U(20.W))\n ))\n\n // machine is in halted state, pipe empty, write will always happen next cycle\n io.ib_exu.dec_debug_wdata_rs1_d := debug_write_gpr | debug_write_csr\n\n // special fence csr for use only in debug mode\n io.dec_debug_fence_d := debug_write_csr & (dcsr === 0x7C4.U)\n\n io.dec_ib0_valid_d := io.ifu_ib.ifu_i0_valid | debug_valid\n io.dec_i0_instr_d := Mux(debug_valid.asBool,ib0_debug_in,io.ifu_ib.ifu_i0_instr)\n\n}\n", "groundtruth": "class dec_ib_ctl_IO extends Bundle with param{\n val ifu_ib = Flipped(new aln_ib)\n val ib_exu = Flipped(new ib_exu)\n val dbg_ib = new dbg_ib\n", "crossfile_context": ""}
{"task_id": "Quasar", "path": "Quasar/design/src/main/scala/dec/dec_tlu_ctl.scala", "left_context": "package dec\nimport chisel3._\nimport chisel3.util._\nimport lib._\nimport include._\nimport inst_pkt_t._\nimport lsu._\nimport exu._\n\ntrait CSR_VAL {\n\n\tval MSTATUS_MIE\t\t=0\n\tval MIP_MCEIP \t\t=5\n\tval MIP_MITIP0 \t\t=4\n\tval MIP_MITIP1 \t\t=3\n\tval MIP_MEIP \t\t=2\n\tval MIP_MTIP \t\t=1\n\tval MIP_MSIP \t\t=0\n\n\tval MIE_MCEIE \t\t=5\n\tval MIE_MITIE0 \t\t=4\n\tval MIE_MITIE1 \t\t=3\n\tval MIE_MEIE \t\t=2\n\tval MIE_MTIE \t\t=1\n\tval MIE_MSIE \t\t=0\n\n\tval DCSR_EBREAKM \t=15\n\tval DCSR_STEPIE \t=11\n\tval DCSR_STOPC \t\t=10\n\tval DCSR_STEP \t\t=2\n\n\tval MTDATA1_DMODE \t\t=9\n\tval MTDATA1_SEL \t\t=7\n\tval MTDATA1_ACTION \t\t=6\n\tval MTDATA1_CHAIN \t\t=5\n\tval MTDATA1_MATCH \t\t=4\n\tval MTDATA1_M_ENABLED \t=3\n\tval MTDATA1_EXE \t\t=2\n\tval MTDATA1_ST \t\t\t=1\n\tval MTDATA1_LD \t\t\t=0\n\n\n}\n\nclass dec_tlu_ctl_IO extends Bundle with lib {\n\tval tlu_exu = Flipped(new tlu_exu)\n\tval tlu_dma = new tlu_dma\n\tval free_clk = Input(Clock())\n\tval free_l2clk = Input(Clock())\n\tval scan_mode = Input(Bool())\n\tval rst_vec = Input(UInt(31.W)) // reset vector, from core pins\n\tval nmi_int = Input(UInt(1.W)) // nmi pin\n\tval nmi_vec = Input(UInt(31.W)) // nmi vector\n\tval i_cpu_halt_req = Input(UInt(1.W)) // Asynchronous Halt request to CPU\n\tval i_cpu_run_req = Input(UInt(1.W)) // Asynchronous Restart request to CPU\n\tval lsu_fastint_stall_any = Input(UInt(1.W)) // needed by lsu for 2nd pass of dma with ecc correction, stall next cycle\n\tval lsu_idle_any = Input(UInt(1.W)) // lsu is idle\n\t// perf counter inputs\n\tval dec_pmu_instr_decoded = Input(UInt(1.W))// decoded instructions\n\tval dec_pmu_decode_stall = Input(UInt(1.W))// decode stall\n\tval dec_pmu_presync_stall = Input(UInt(1.W))// decode stall due to presync'd inst\n\tval dec_pmu_postsync_stall = Input(UInt(1.W))// decode stall due to postsync'd inst\n\tval lsu_store_stall_any = Input(UInt(1.W))// SB or WB is full, stall decode\n\tval lsu_fir_addr = Input(UInt(31.W)) // Fast int address\n\tval lsu_fir_error = Input(UInt(2.W)) // Fast int lookup error\n\tval iccm_dma_sb_error = Input(UInt(1.W)) // I side dma single bit error\n\tval lsu_error_pkt_r = Flipped(Valid(new lsu_error_pkt_t))// lsu precise exception/error packet\n\tval lsu_single_ecc_error_incr = Input(UInt(1.W)) // LSU inc SB error counter\n\tval dec_pause_state = Input(UInt(1.W)) // Pause counter not zero\n\tval dec_csr_wen_unq_d = Input(UInt(1.W)) // valid csr with write - for csr legal\n\tval dec_csr_any_unq_d = Input(UInt(1.W)) // valid csr - for csr legal\n\tval dec_csr_rdaddr_d = Input(UInt(12.W)) // read address for csr\n\tval dec_csr_wen_r = Input(UInt(1.W)) // csr write enable at wb\n\tval dec_csr_wraddr_r = Input(UInt(12.W)) // write address for csr\n\tval dec_csr_wrdata_r = Input(UInt(32.W)) // csr write data at wb\n\tval dec_csr_stall_int_ff = Input(UInt(1.W)) // csr is mie/mstatus\n\tval dec_tlu_i0_valid_r = Input(UInt(1.W)) // pipe 0 op at e4 is valid\n\tval dec_tlu_i0_pc_r = Input(UInt(31.W)) // for PC/NPC tracking\n\tval dec_tlu_packet_r = Input(new trap_pkt_t) // exceptions known at decode\n\tval dec_illegal_inst = Input(UInt(32.W)) // For mtval\n\tval dec_i0_decode_d = Input(UInt(1.W)) // decode valid, used for clean icache diagnostics\n\tval exu_i0_br_way_r = Input(UInt(1.W))// way hit or repl\n\n\tval dec_tlu_core_empty = Output(UInt(1.W)) // abstract command done\n\t// Debug start\n\tval dec_dbg_cmd_done = Output(UInt(1.W)) // abstract command done\n\tval dec_dbg_cmd_fail = Output(UInt(1.W)) // abstract command failed\n\tval dec_tlu_dbg_halted = Output(UInt(1.W)) // Core is halted and ready for debug command\n\tval dec_tlu_debug_mode = Output(UInt(1.W)) // Core is in debug mode\n\tval dec_tlu_resume_ack = Output(UInt(1.W)) // Resume acknowledge\n\tval dec_tlu_debug_stall = Output(UInt(1.W)) // stall decode while waiting on core to empty\n\tval dec_tlu_mpc_halted_only = Output(UInt(1.W)) // Core is halted only due to MPC\n\tval dec_tlu_flush_extint = Output(UInt(1.W)) // fast ext int started\n\tval dbg_halt_req = Input(UInt(1.W)) // DM requests a halt\n\tval dbg_resume_req = Input(UInt(1.W)) // DM requests a resume\n\tval dec_div_active = Input(UInt(1.W)) // oop div is active\n\tval trigger_pkt_any = Output(Vec(4,new trigger_pkt_t))// trigger info for trigger blocks\n\tval timer_int= Input(UInt(1.W)) // timer interrupt pending\n\tval soft_int= Input(UInt(1.W)) // software interrupt pending\n\tval o_cpu_halt_status = Output(UInt(1.W)) // PMU interface, halted\n\tval o_cpu_halt_ack = Output(UInt(1.W)) // halt req ack\n\tval o_cpu_run_ack = Output(UInt(1.W)) // run req ack\n\tval o_debug_mode_status = Output(UInt(1.W)) // Core to the PMU that core is in debug mode. When core is in debug mode, the PMU should refrain from sendng a halt or run request\n\tval core_id = Input(UInt(28.W)) // Core ID\n\t// external MPC halt/run interface\n\tval mpc_debug_halt_req = Input(UInt(1.W)) // Async halt request\n\tval mpc_debug_run_req = Input(UInt(1.W)) // Async run request\n\tval mpc_reset_run_req = Input(UInt(1.W)) // Run/halt after reset\n\tval mpc_debug_halt_ack = Output(UInt(1.W)) // Halt ack\n\tval mpc_debug_run_ack = Output(UInt(1.W)) // Run ack\n\tval debug_brkpt_status = Output(UInt(1.W)) // debug breakpoint\n\tval dec_csr_rddata_d = Output(UInt(32.W)) // csr read data at wb\n\tval dec_csr_legal_d = Output(UInt(1.W)) // csr indicates legal operation\n\tval dec_tlu_i0_kill_writeb_wb = Output(UInt(1.W)) // I0 is flushed, don't writeback any results to arch state\n\tval dec_tlu_i0_kill_writeb_r = Output(UInt(1.W)) // I0 is flushed, don't writeback any results to arch state\n\tval dec_tlu_wr_pause_r = Output(UInt(1.W)) // CSR write to pause reg is at R.\n\tval dec_tlu_flush_pause_r = Output(UInt(1.W)) // Flush is due to pause\n\tval dec_tlu_presync_d = Output(UInt(1.W)) // CSR read needs to be presync'd\n\tval dec_tlu_postsync_d = Output(UInt(1.W)) // CSR needs to be presync'd\n\tval dec_tlu_perfcnt0 = Output(UInt(1.W)) // toggles when pipe0 perf counter 0 has an event inc\n\tval dec_tlu_perfcnt1 = Output(UInt(1.W)) // toggles when pipe0 perf counter 1 has an event inc\n\tval dec_tlu_perfcnt2 = Output(UInt(1.W)) // toggles when pipe0 perf counter 2 has an event inc\n\tval dec_tlu_perfcnt3 = Output(UInt(1.W)) // toggles when pipe0 perf counter 3 has an event inc\n\tval dec_tlu_i0_exc_valid_wb1 = Output(UInt(1.W)) // pipe 0 exception valid\n\tval dec_tlu_i0_valid_wb1 = Output(UInt(1.W)) // pipe 0 valid\n\tval dec_tlu_int_valid_wb1 = Output(UInt(1.W)) // pipe 2 int valid\n\tval dec_tlu_exc_cause_wb1 = Output(UInt(5.W)) // exception or int cause\n\tval dec_tlu_mtval_wb1 = Output(UInt(32.W)) // MTVAL value\n\tval dec_tlu_pipelining_disable = Output(UInt(1.W)) // disable pipelining\n\n\tval dec_tlu_trace_disable = Output(Bool()) // disable pipelining\n\t// clock gating overrides from mcgc\n\tval dec_tlu_misc_clk_override = Output(UInt(1.W)) // override misc clock domain gating\n\tval dec_tlu_dec_clk_override = Output(UInt(1.W)) // override decode clock domain gating\n\tval dec_tlu_ifu_clk_override = Output(UInt(1.W)) // override fetch clock domain gating\n\tval dec_tlu_lsu_clk_override = Output(UInt(1.W)) // override load/store clock domain gating\n\tval dec_tlu_bus_clk_override = Output(UInt(1.W)) // override bus clock domain gating\n\tval dec_tlu_pic_clk_override = Output(UInt(1.W)) // override PIC clock domain gating\n\n\tval dec_tlu_picio_clk_override = Output(UInt(1.W)) // override PIC clock domain gating\n\tval dec_tlu_dccm_clk_override = Output(UInt(1.W)) // override DCCM clock domain gating\n\tval dec_tlu_icm_clk_override = Output(UInt(1.W)) // override ICCM clock domain gating\n\tval dec_tlu_flush_lower_wb = Output(Bool())\n\tval ifu_pmu_instr_aligned = Input(UInt(1.W))\n\tval tlu_bp = Flipped(new dec_bp)\n\tval tlu_ifc = Flipped(new dec_ifc)\n\tval tlu_mem = Flipped(new dec_mem_ctrl)\n\tval tlu_busbuff = Flipped (new tlu_busbuff)\n\tval lsu_tlu = Flipped (new lsu_tlu)\n\tval dec_pic = new dec_pic\n}\nclass dec_tlu_ctl extends Module with lib with RequireAsyncReset with CSR_VAL{\n\tval io = IO(new dec_tlu_ctl_IO)\n\n\tval mtdata1_t\t\t\t\t\t = Wire(Vec(4,UInt(10.W)))\n\tval pause_expired_wb\t\t\t\t=WireInit(UInt(1.W), 0.U)\n\tval take_nmi_r_d1\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval exc_or_int_valid_r_d1\t\t\t=WireInit(UInt(1.W),0.U)\n\tval interrupt_valid_r_d1\t\t\t=WireInit(Bool(),0.B)\n\tval tlu_flush_lower_r\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval synchronous_flush_r\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval interrupt_valid_r\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval take_nmi\t\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval take_reset\t\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval take_int_timer1_int\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval take_int_timer0_int\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval take_timer_int\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval take_soft_int\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval take_ce_int\t\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval take_ext_int_start \t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval ext_int_freeze \t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval take_ext_int_start_d2 \t\t\t=WireInit(UInt(1.W),0.U)\n\tval take_ext_int_start_d3 \t\t\t=WireInit(UInt(1.W),0.U)\n\tval fast_int_meicpct \t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval ignore_ext_int_due_to_lsu_stall =WireInit(UInt(1.W),0.U)\n\tval take_ext_int \t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval internal_dbg_halt_timers\t\t=WireInit(UInt(1.W),0.U)\n\tval int_timer1_int_hold\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval int_timer0_int_hold\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval mhwakeup_ready \t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval ext_int_ready \t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval ce_int_ready \t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval soft_int_ready \t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval timer_int_ready \t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval ebreak_to_debug_mode_r_d1 \t\t=WireInit(UInt(1.W),0.U)\n\tval ebreak_to_debug_mode_r \t\t\t=WireInit(UInt(1.W),0.U)\n\tval inst_acc_r\t\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval inst_acc_r_raw\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval iccm_sbecc_r\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval ic_perr_r\t\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval fence_i_r\t\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval ebreak_r \t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval ecall_r \t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval illegal_r \t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval mret_r \t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval iccm_repair_state_ns\t\t\t=WireInit(UInt(1.W),0.U)\n\tval rfpc_i0_r \t\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval tlu_i0_kill_writeb_r\t\t\t=WireInit(UInt(1.W),0.U)\n\tval lsu_exc_valid_r_d1\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval lsu_i0_exc_r_raw\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval mdseac_locked_f\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval i_cpu_run_req_d1\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval cpu_run_ack\t\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval cpu_halt_status\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval cpu_halt_ack\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval pmu_fw_tlu_halted\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval internal_pmu_fw_halt_mode\t\t=WireInit(UInt(1.W),0.U)\n\tval pmu_fw_halt_req_ns\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval pmu_fw_halt_req_f\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval pmu_fw_tlu_halted_f\t\t\t=WireInit(UInt(1.W),0.U)\n\tval int_timer0_int_hold_f\t\t\t=WireInit(UInt(1.W),0.U)\n\tval int_timer1_int_hold_f\t\t\t=WireInit(UInt(1.W),0.U)\n\tval trigger_hit_dmode_r \t\t\t=WireInit(UInt(1.W),0.U)\n\tval i0_trigger_hit_r\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval pause_expired_r\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval dec_tlu_pmu_fw_halted\t\t\t=WireInit(UInt(1.W),0.U)\n\tval dec_tlu_flush_noredir_r_d1\t\t=WireInit(UInt(1.W),0.U)\n\tval halt_taken_f\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval lsu_idle_any_f\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval ifu_miss_state_idle_f\t\t\t=WireInit(UInt(1.W),0.U)\n\tval dbg_tlu_halted_f\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval debug_halt_req_f\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval debug_resume_req_f_raw\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval debug_resume_req_f\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval trigger_hit_dmode_r_d1\t\t\t=WireInit(UInt(1.W),0.U)\n\tval dcsr_single_step_done_f\t\t\t=WireInit(UInt(1.W),0.U)\n\tval debug_halt_req_d1\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval request_debug_mode_r_d1\t\t\t=WireInit(UInt(1.W),0.U)\n\tval request_debug_mode_done_f\t\t=WireInit(UInt(1.W),0.U)\n\tval dcsr_single_step_running_f\t\t=WireInit(UInt(1.W),0.U)\n\tval dec_tlu_flush_pause_r_d1\t\t=WireInit(UInt(1.W),0.U)\n\tval dbg_halt_req_held\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval debug_halt_req_ns \t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval internal_dbg_halt_mode\t\t\t=WireInit(UInt(1.W),0.U)\n\tval core_empty\t\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval dbg_halt_req_final \t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval debug_brkpt_status_ns \t\t\t=WireInit(UInt(1.W),0.U)\n\tval mpc_debug_halt_ack_ns \t\t\t=WireInit(UInt(1.W),0.U)\n\tval mpc_debug_run_ack_ns \t\t\t=WireInit(UInt(1.W),0.U)\n\tval mpc_halt_state_ns \t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval mpc_run_state_ns \t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval dbg_halt_state_ns \t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval dbg_run_state_ns \t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval dbg_halt_state_f \t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval mpc_halt_state_f \t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval nmi_int_detected \t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval nmi_lsu_load_type \t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval nmi_lsu_store_type \t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval reset_delayed\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval internal_dbg_halt_mode_f\t\t=WireInit(UInt(1.W),0.U)\n\tval e5_valid\t\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval ic_perr_r_d1\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\tval iccm_sbecc_r_d1\t\t\t\t\t=WireInit(UInt(1.W),0.U)\n\n\tval npc_r = WireInit(UInt(31.W),0.U)\n\tval npc_r_d1 = WireInit(UInt(31.W),0.U)\n\tval mie_ns = WireInit(UInt(6.W),0.U)\n\tval mepc = WireInit(UInt(31.W),0.U)\n\tval mdseac_locked_ns = WireInit(UInt(1.W),0.U)\n\tval force_halt \t\t\t\t = WireInit(UInt(1.W),0.U)\n\tval dpc = WireInit(UInt(31.W),0.U)\n\tval mstatus_mie_ns = WireInit(UInt(1.W),0.U)\n\tval dec_csr_wen_r_mod = WireInit(UInt(1.W),0.U)\n\tval fw_halt_req = WireInit(UInt(1.W),0.U)\n\tval mstatus = WireInit(UInt(2.W),0.U)\n\tval dcsr = WireInit(UInt(16.W),0.U)\n\tval mtvec = WireInit(UInt(31.W),0.U)\n\tval mip = WireInit(UInt(6.W),0.U)\n\tval csr_pkt = Wire(new dec_tlu_csr_pkt)\n\tval dec_tlu_mpc_halted_only_ns = WireInit(UInt(1.W),0.U)\n\t// tell dbg we are only MPC halted\n\tdec_tlu_mpc_halted_only_ns := ~dbg_halt_state_f & mpc_halt_state_f\n\tval int_exc = Module(new int_exc)\n\tval csr=Module(new csr_tlu)\n\tval int_timers=Module(new dec_timer_ctl)\n\tint_timers.io.free_l2clk\t\t\t\t:=io.free_l2clk\n\tint_timers.io.scan_mode\t\t\t\t:=io.scan_mode\n\tint_timers.io.dec_csr_wen_r_mod\t\t:=dec_csr_wen_r_mod\n\tint_timers.io.dec_csr_wraddr_r\t\t:=io.dec_csr_wraddr_r\n\tint_timers.io.dec_csr_wrdata_r\t\t:=io.dec_csr_wrdata_r\n\tint_timers.io.csr_mitctl0\t\t\t:=csr_pkt.csr_mitctl0\n\tint_timers.io.csr_mitctl1\t\t\t:=csr_pkt.csr_mitctl1\n\tint_timers.io.csr_mitb0\t\t\t\t:=csr_pkt.csr_mitb0\n\tint_timers.io.csr_mitb1\t\t\t\t:=csr_pkt.csr_mitb1\n\tint_timers.io.csr_mitcnt0\t\t\t:=csr_pkt.csr_mitcnt0\n\tint_timers.io.csr_mitcnt1\t\t\t:=csr_pkt.csr_mitcnt1\n\tint_timers.io.dec_pause_state\t\t:=io.dec_pause_state\n\tint_timers.io.dec_tlu_pmu_fw_halted\t:=dec_tlu_pmu_fw_halted\n\tint_timers.io.internal_dbg_halt_timers:=internal_dbg_halt_timers\n\n\tval dec_timer_rddata_d\t\t=int_timers.io.dec_timer_rddata_d\n\tval dec_timer_read_d\t\t=int_timers.io.dec_timer_read_d\n\tval dec_timer_t0_pulse\t\t=int_timers.io.dec_timer_t0_pulse\n\tval dec_timer_t1_pulse\t\t=int_timers.io.dec_timer_t1_pulse\n\n\tval clk_override = io.dec_tlu_dec_clk_override\n\n\t// Async inputs to the core have to be sync'd to the core clock.\n\n\tval syncro_ff=rvsyncss(Cat(io.nmi_int, io.timer_int, io.soft_int, io.i_cpu_halt_req, io.i_cpu_run_req, io.mpc_debug_halt_req, io.mpc_debug_run_req),io.free_clk)\n\tval nmi_int_sync\t\t\t\t\t=syncro_ff(6)\n\tval timer_int_sync\t\t\t\t=syncro_ff(5)\n\tval soft_int_sync\t\t\t\t=syncro_ff(4)\n\tval i_cpu_halt_req_sync\t\t\t=syncro_ff(3)\n\tval i_cpu_run_req_sync\t\t\t=syncro_ff(2)\n\tval mpc_debug_halt_req_sync_raw\t=syncro_ff(1)\n\tval mpc_debug_run_req_sync\t\t=syncro_ff(0)\n\n\t// for CSRs that have inpipe writes only\n\tval csr_wr_clk=rvoclkhdr(clock,(dec_csr_wen_r_mod | clk_override).asBool,io.scan_mode)\n\tint_timers.io.csr_wr_clk := csr_wr_clk\n\t\n\tval e4_valid = io.dec_tlu_i0_valid_r\n\tval e4e5_valid = e4_valid | e5_valid\n\tval flush_clkvalid = internal_dbg_halt_mode_f | i_cpu_run_req_d1 | interrupt_valid_r | interrupt_valid_r_d1 | reset_delayed | pause_expired_r | pause_expired_wb | ic_perr_r | iccm_sbecc_r | clk_override\n\n\t// dontTouch(flush_clkvalid)\n\tval e4e5_clk=rvoclkhdr(clock,(e4e5_valid | clk_override).asBool,io.scan_mode)\n\tval e4e5_int_clk=rvoclkhdr(clock,(e4e5_valid | flush_clkvalid).asBool,io.scan_mode)\n\n\tval ifu_ic_error_start_f =rvdffie(io.tlu_mem.ifu_ic_error_start,io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n\tval ifu_iccm_rd_ecc_single_err_f =rvdffie(io.tlu_mem.ifu_iccm_rd_ecc_single_err,io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n\n\tval iccm_repair_state_d1\t\t=rvdffie(iccm_repair_state_ns,io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n\te5_valid\t\t\t\t\t\t :=rvdffie(e4_valid,io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n\tinternal_dbg_halt_mode_f\t\t :=rvdffie(internal_dbg_halt_mode,io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n\tval lsu_pmu_load_external_r\t\t =rvdffie(io.lsu_tlu.lsu_pmu_load_external_m,io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n\tval lsu_pmu_store_external_r\t =rvdffie(io.lsu_tlu.lsu_pmu_store_external_m,io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n\tval tlu_flush_lower_r_d1\t\t =rvdffie(tlu_flush_lower_r,io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n\tio.dec_tlu_i0_kill_writeb_wb\t:=rvdffie(tlu_i0_kill_writeb_r,io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n\tval internal_dbg_halt_mode_f2\t =rvdffie(internal_dbg_halt_mode_f,io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n\tio.tlu_mem.dec_tlu_force_halt\t:=rvdffie(force_halt,io.free_l2clk, reset.asAsyncReset(), io.scan_mode)\n\n\n\n\tio.dec_tlu_i0_kill_writeb_r \t:=tlu_i0_kill_writeb_r\n\n\tval nmi_int_delayed \t\t=rvdffie(nmi_int_sync, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\tval nmi_int_detected_f\t\t=rvdffie(nmi_int_detected, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\tval nmi_lsu_load_type_f\t\t=rvdffie(nmi_lsu_load_type, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\tval nmi_lsu_store_type_f\t=rvdffie(nmi_lsu_store_type, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\n\tval nmi_fir_type = WireInit(UInt(1.W),0.U)\n\tval nmi_lsu_detected = ~mdseac_locked_f & (io.tlu_busbuff.lsu_imprecise_error_load_any | io.tlu_busbuff.lsu_imprecise_error_store_any) & ~nmi_fir_type\n\n\t// Filter subsequent bus errors after the first, until the lock on MDSEAC is cleared\n\tnmi_int_detected := (nmi_int_sync & ~nmi_int_delayed) | nmi_lsu_detected | (nmi_int_detected_f & ~take_nmi_r_d1) | nmi_fir_type\n\t// if the first nmi is a lsu type, note it. If there's already an nmi pending, ignore. Simultaneous with FIR, drop.\n\tnmi_lsu_load_type := (nmi_lsu_detected & io.tlu_busbuff.lsu_imprecise_error_load_any & ~(nmi_int_detected_f & ~take_nmi_r_d1)) | (nmi_lsu_load_type_f & ~take_nmi_r_d1)\n\tnmi_lsu_store_type := (nmi_lsu_detected & io.tlu_busbuff.lsu_imprecise_error_store_any & ~(nmi_int_detected_f & ~take_nmi_r_d1)) | (nmi_lsu_store_type_f & ~take_nmi_r_d1)\n\n\tnmi_fir_type := ~nmi_int_detected_f & csr.io.take_ext_int_start_d3 & io.lsu_fir_error.orR\n\n\tval reset_detect\t\t\t\t=rvdffie(1.U(1.W), io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\tval reset_detected\t\t\t=rvdffie(reset_detect, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\treset_delayed \t\t\t\t:=reset_detect ^ reset_detected\n\n\n\t// ----------------------------------------------------------------------\n\t// MPC halt\n\t// - can interact with debugger halt and v-v\n\t// fast ints in progress have priority\n\tval mpc_debug_halt_req_sync = mpc_debug_halt_req_sync_raw & !csr.io.ext_int_freeze_d1\n\tval mpc_debug_halt_req_sync_f\t=rvdffie(mpc_debug_halt_req_sync, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(mpc_debug_halt_req_sync,0.U)}\n\tval mpc_debug_run_req_sync_f\t=rvdffie(mpc_debug_run_req_sync, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(mpc_debug_run_req_sync,0.U)}\n\tmpc_halt_state_f\t\t\t\t :=rvdffie(mpc_halt_state_ns, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(mpc_halt_state_ns,0.U)}\n\tval mpc_run_state_f\t\t\t\t =rvdffie(mpc_run_state_ns, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(mpc_run_state_ns,0.U)}\n\tval debug_brkpt_status_f\t\t =rvdffie(debug_brkpt_status_ns, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(debug_brkpt_status_ns,0.U)}\n\tval mpc_debug_halt_ack_f\t\t =rvdffie(mpc_debug_halt_ack_ns, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(mpc_debug_halt_ack_ns,0.U)}\n\tval mpc_debug_run_ack_f\t\t\t =rvdffie(mpc_debug_run_ack_ns, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(mpc_debug_run_ack_ns,0.U)}\n\tdbg_halt_state_f\t\t\t\t :=rvdffie(dbg_halt_state_ns, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(dbg_halt_state_ns,0.U)}\n\tval dbg_run_state_f\t\t\t\t =rvdffie(dbg_run_state_ns, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(dbg_run_state_ns,0.U)}\n\tio.dec_tlu_mpc_halted_only \t :=rvdffie(dec_tlu_mpc_halted_only_ns, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(dec_tlu_mpc_halted_only_ns,0.U)}\n\n\n\t// turn level sensitive requests into pulses\n\tval mpc_debug_halt_req_sync_pulse = mpc_debug_halt_req_sync & ~mpc_debug_halt_req_sync_f\n\tval mpc_debug_run_req_sync_pulse = mpc_debug_run_req_sync & ~mpc_debug_run_req_sync_f\n\t// states\n\tmpc_halt_state_ns := (mpc_halt_state_f | mpc_debug_halt_req_sync_pulse | (reset_delayed & ~io.mpc_reset_run_req)) & ~mpc_debug_run_req_sync\n\tmpc_run_state_ns := (mpc_run_state_f | (mpc_debug_run_req_sync_pulse & ~mpc_debug_run_ack_f)) & (internal_dbg_halt_mode_f & ~dcsr_single_step_running_f)\n\t// note, MPC halt can allow the jtag debugger to just start sending commands. When that happens, set the interal debugger halt state to prevent\n\t// MPC run from starting the core.\n\tdbg_halt_state_ns := (dbg_halt_state_f | (dbg_halt_req_final | dcsr_single_step_done_f | trigger_hit_dmode_r_d1 | ebreak_to_debug_mode_r_d1)) & ~io.dbg_resume_req\n\tdbg_run_state_ns := (dbg_run_state_f | io.dbg_resume_req) & (internal_dbg_halt_mode_f & ~dcsr_single_step_running_f)\n\n\t// tell dbg we are only MPC halted\n\tdec_tlu_mpc_halted_only_ns := ~dbg_halt_state_f & mpc_halt_state_f\n\n\t// this asserts from detection of bkpt until after we leave debug mode\n\tval debug_brkpt_valid = ebreak_to_debug_mode_r_d1 | trigger_hit_dmode_r_d1\n\tdebug_brkpt_status_ns := (debug_brkpt_valid | debug_brkpt_status_f) & (internal_dbg_halt_mode & ~dcsr_single_step_running_f)\n\n\t// acks back to interface\n\tmpc_debug_halt_ack_ns := mpc_halt_state_f & internal_dbg_halt_mode_f & mpc_debug_halt_req_sync & core_empty\n\tmpc_debug_run_ack_ns := (mpc_debug_run_req_sync & ~dbg_halt_state_ns & ~mpc_debug_halt_req_sync) | (mpc_debug_run_ack_f & mpc_debug_run_req_sync)\n\n\t// Pins\n\tio.mpc_debug_halt_ack := mpc_debug_halt_ack_f\n\tio.mpc_debug_run_ack := mpc_debug_run_ack_f\n\tio.debug_brkpt_status := debug_brkpt_status_f\n\n\t// DBG halt req is a pulse, fast ext int in progress has priority\n\tval dbg_halt_req_held_ns = (io.dbg_halt_req | dbg_halt_req_held) & csr.io.ext_int_freeze_d1\n\tdbg_halt_req_final := (io.dbg_halt_req | dbg_halt_req_held) & ~csr.io.ext_int_freeze_d1\n\n\t// combine MPC and DBG halt requests\n\tval debug_halt_req = (dbg_halt_req_final | mpc_debug_halt_req_sync | (reset_delayed & ~io.mpc_reset_run_req)) & ~internal_dbg_halt_mode_f & ~csr.io.ext_int_freeze_d1\n\n\tval debug_resume_req = ~debug_resume_req_f & ((mpc_run_state_ns & ~dbg_halt_state_ns) | (dbg_run_state_ns & ~mpc_halt_state_ns))\n\n\n\t// HALT\n\t// dbg/pmu/fw requests halt, service as soon as lsu is not blocking interrupts\n\tval take_halt = (debug_halt_req_f | pmu_fw_halt_req_f) & ~synchronous_flush_r & ~mret_r & ~halt_taken_f & ~dec_tlu_flush_noredir_r_d1 & ~take_reset\n\n\t// hold after we take a halt, so we don't keep taking halts\n\tval halt_taken = (dec_tlu_flush_noredir_r_d1 & !dec_tlu_flush_pause_r_d1 & !csr.io.take_ext_int_start_d1) | (halt_taken_f & !dbg_tlu_halted_f & !pmu_fw_tlu_halted_f & !interrupt_valid_r_d1)\n\n\t// After doing halt flush (RFNPC) wait until core is idle before asserting a particular halt mode\n\t// It takes a cycle for mb_empty to assert after a fetch, take_halt covers that cycle\n\tcore_empty := force_halt | (io.lsu_idle_any & lsu_idle_any_f & io.tlu_mem.ifu_miss_state_idle & ifu_miss_state_idle_f & ~debug_halt_req & ~debug_halt_req_d1 & ~io.dec_div_active)\n\tio.dec_tlu_core_empty := core_empty\n\t//--------------------------------------------------------------------------------\n\t// Debug start\n\t//\n\n\tval enter_debug_halt_req = (~internal_dbg_halt_mode_f & debug_halt_req) | dcsr_single_step_done_f | trigger_hit_dmode_r_d1 | ebreak_to_debug_mode_r_d1\n\n\t// dbg halt state active from request until non-step resume\n\tinternal_dbg_halt_mode := debug_halt_req_ns | (internal_dbg_halt_mode_f & ~(debug_resume_req_f & ~dcsr(DCSR_STEP)))\n\n\t// dbg halt can access csrs as long as we are not stepping\n\tval allow_dbg_halt_csr_write = internal_dbg_halt_mode_f & ~dcsr_single_step_running_f\n\n\n\t// hold debug_halt_req_ns high until we enter debug halt\n\n\tval dbg_tlu_halted = (debug_halt_req_f & core_empty & halt_taken) | (dbg_tlu_halted_f & ~debug_resume_req_f)\n\n\tdebug_halt_req_ns := enter_debug_halt_req | (debug_halt_req_f & ~dbg_tlu_halted)\n\tval resume_ack_ns = (debug_resume_req_f & dbg_tlu_halted_f & dbg_run_state_ns)\n\n\tval dcsr_single_step_done = io.dec_tlu_i0_valid_r & ~io.dec_tlu_dbg_halted & dcsr(DCSR_STEP) & ~rfpc_i0_r\n\n\tval dcsr_single_step_running = (debug_resume_req_f & dcsr(DCSR_STEP)) | (dcsr_single_step_running_f & ~dcsr_single_step_done_f)\n\n\tval dbg_cmd_done_ns = io.dec_tlu_i0_valid_r & io.dec_tlu_dbg_halted\n\n\t// used to hold off commits after an in-pipe debug mode request (triggers, DCSR)\n\tval request_debug_mode_r = (trigger_hit_dmode_r | ebreak_to_debug_mode_r) | (request_debug_mode_r_d1 & ~io.dec_tlu_flush_lower_wb)\n\n\tval request_debug_mode_done = (request_debug_mode_r_d1 | request_debug_mode_done_f) & ~dbg_tlu_halted_f\n\n\tdec_tlu_flush_noredir_r_d1\t\t :=rvdffie(io.tlu_ifc.dec_tlu_flush_noredir_wb, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(io.tlu_ifc.dec_tlu_flush_noredir_wb,0.U)}\n\thalt_taken_f\t\t\t\t\t :=rvdffie(halt_taken, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(halt_taken,0.U)}\n\tlsu_idle_any_f\t\t\t\t\t :=rvdffie(io.lsu_idle_any, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(io.lsu_idle_any,0.U)}\n\tifu_miss_state_idle_f\t\t\t :=rvdffie(io.tlu_mem.ifu_miss_state_idle, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(io.tlu_mem.ifu_miss_state_idle,0.U)}\n\tdbg_tlu_halted_f\t\t\t\t :=rvdffie(dbg_tlu_halted, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(dbg_tlu_halted,0.U)}\n\tio.dec_tlu_resume_ack\t\t\t :=rvdffie(resume_ack_ns, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(resume_ack_ns,0.U)}\n\tdebug_halt_req_f\t\t\t\t :=rvdffie(debug_halt_req_ns, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(debug_halt_req_ns,0.U)}\n\tdebug_resume_req_f_raw\t\t\t\t:=rvdffie(debug_resume_req, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(debug_resume_req,0.U)}\n\ttrigger_hit_dmode_r_d1\t\t\t :=rvdffie(trigger_hit_dmode_r, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(trigger_hit_dmode_r,0.U)}\n\tdcsr_single_step_done_f\t\t\t :=rvdffie(dcsr_single_step_done, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(dcsr_single_step_done,0.U)}\n\tdebug_halt_req_d1\t\t\t\t :=rvdffie(debug_halt_req, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(debug_halt_req,0.U)}\n\tval dec_tlu_wr_pause_r_d1\t\t =rvdffie(io.dec_tlu_wr_pause_r, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(io.dec_tlu_wr_pause_r,0.U)}\n\tval dec_pause_state_f\t\t\t =rvdffie(io.dec_pause_state, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(io.dec_pause_state,0.U)}\n\trequest_debug_mode_r_d1\t\t\t:=rvdffie(request_debug_mode_r, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(request_debug_mode_r,0.U)}\n\trequest_debug_mode_done_f\t\t:=rvdffie(request_debug_mode_done, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(request_debug_mode_done,0.U)}\n\tdcsr_single_step_running_f\t\t:=rvdffie(dcsr_single_step_running, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(dcsr_single_step_running,0.U)}\n\tdec_tlu_flush_pause_r_d1\t\t:=rvdffie(io.dec_tlu_flush_pause_r, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(io.dec_tlu_flush_pause_r,0.U)}\n\tdbg_halt_req_held\t\t\t \t:=rvdffie(dbg_halt_req_held_ns, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(dbg_halt_req_held_ns,0.U)}\n\n\n\t// MPC run collides with DBG halt, fix it here\n\tdebug_resume_req_f := debug_resume_req_f_raw & ~io.dbg_halt_req\n\n\tio.dec_tlu_debug_stall \t\t:= debug_halt_req_f\n\tio.dec_tlu_dbg_halted \t\t:= dbg_tlu_halted_f\n\tio.dec_tlu_debug_mode \t\t:= internal_dbg_halt_mode_f\n\tdec_tlu_pmu_fw_halted \t\t:= pmu_fw_tlu_halted_f\n\n\t// kill fetch redirection on flush if going to halt, or if there's a fence during db-halt\n\tio.tlu_ifc.dec_tlu_flush_noredir_wb := take_halt | (fence_i_r & internal_dbg_halt_mode) | io.dec_tlu_flush_pause_r | (i0_trigger_hit_r & trigger_hit_dmode_r) | take_ext_int_start\n\n\tio.dec_tlu_flush_extint := take_ext_int_start\n\n\t// 1 cycle after writing the PAUSE counter, flush with noredir to idle F1-D.\n\tio.dec_tlu_flush_pause_r := dec_tlu_wr_pause_r_d1 & ~interrupt_valid_r & ~take_ext_int_start\n\t// detect end of pause counter and rfpc\n\tpause_expired_r := ~io.dec_pause_state & dec_pause_state_f & ~(ext_int_ready | ce_int_ready | timer_int_ready | soft_int_ready | int_timer0_int_hold_f | int_timer1_int_hold_f | nmi_int_detected | csr.io.ext_int_freeze_d1) & ~interrupt_valid_r_d1 & ~debug_halt_req_f & ~pmu_fw_halt_req_f & ~halt_taken_f\n\n\tio.tlu_bp.dec_tlu_flush_leak_one_wb := io.tlu_exu.dec_tlu_flush_lower_r & dcsr(DCSR_STEP) & (io.dec_tlu_resume_ack | dcsr_single_step_running) & ~io.tlu_ifc.dec_tlu_flush_noredir_wb\n\tio.tlu_mem.dec_tlu_flush_err_wb := io.tlu_exu.dec_tlu_flush_lower_r & (ic_perr_r | iccm_sbecc_r)\n\n\t// If DM attempts to access an illegal CSR, send cmd_fail back\n\tio.dec_dbg_cmd_done := dbg_cmd_done_ns\n\tio.dec_dbg_cmd_fail := illegal_r & io.dec_dbg_cmd_done\n\n\n\t//--------------------------------------------------------------------------------\n\t//--------------------------------------------------------------------------------\n\t// Triggers\n\t//\n\n\t// Prioritize trigger hits with other exceptions.\n\t//\n\t// Trigger should have highest priority except:\n\t// - trigger is an execute-data and there is an inst_access exception (lsu triggers won't fire, inst. is nop'd by decode)\n\t// - trigger is a store-data and there is a lsu_acc_exc or lsu_ma_exc.\n\tval trigger_execute = Cat(mtdata1_t(3)(MTDATA1_EXE), mtdata1_t(2)(MTDATA1_EXE), mtdata1_t(1)(MTDATA1_EXE), mtdata1_t(0)(MTDATA1_EXE))\n\tval trigger_data\t = Cat(mtdata1_t(3)(MTDATA1_SEL), mtdata1_t(2)(MTDATA1_SEL), mtdata1_t(1)(MTDATA1_SEL), mtdata1_t(0)(MTDATA1_SEL))\n\tval trigger_store\t = Cat(mtdata1_t(3)(MTDATA1_ST), mtdata1_t(2)(MTDATA1_ST), mtdata1_t(1)(MTDATA1_ST), mtdata1_t(0)(MTDATA1_ST))\n\n\t// MSTATUS[MIE] needs to be on to take triggers unless the action is trigger to debug mode.\n\tval trigger_enabled\t = Cat((mtdata1_t(3)(MTDATA1_ACTION) | mstatus(MSTATUS_MIE)) & mtdata1_t(3)(MTDATA1_M_ENABLED),\n\t\t(mtdata1_t(2)(MTDATA1_ACTION) | mstatus(MSTATUS_MIE)) & mtdata1_t(2)(MTDATA1_M_ENABLED),\n\t\t(mtdata1_t(1)(MTDATA1_ACTION) | mstatus(MSTATUS_MIE)) & mtdata1_t(1)(MTDATA1_M_ENABLED),\n\t\t(mtdata1_t(0)(MTDATA1_ACTION) | mstatus(MSTATUS_MIE)) & mtdata1_t(0)(MTDATA1_M_ENABLED))\n\n\t// iside exceptions are always in i0\n\tval i0_iside_trigger_has_pri_r = ~((trigger_execute & trigger_data & Fill(4,inst_acc_r_raw)) | (Fill(4,io.tlu_exu.exu_i0_br_error_r | io.tlu_exu.exu_i0_br_start_error_r)))\n\n\t// lsu excs have to line up with their respective triggers since the lsu op can be i0\n\tval i0_lsu_trigger_has_pri_r = ~(trigger_store & trigger_data & Fill(4,lsu_i0_exc_r_raw))\n\n\t// trigger hits have to be eval'd to cancel side effect lsu ops even though the pipe is already frozen\n\tval i0_trigger_eval_r = io.dec_tlu_i0_valid_r\n\n\tval i0trigger_qual_r = Fill(4,i0_trigger_eval_r) & io.dec_tlu_packet_r.i0trigger(3,0) & i0_iside_trigger_has_pri_r & i0_lsu_trigger_has_pri_r & trigger_enabled\n\t// Qual trigger hits\n\tval i0_trigger_r = (~(Fill(4,io.dec_tlu_flush_lower_wb | io.dec_tlu_dbg_halted)) & i0trigger_qual_r)\n\n\t// chaining can mask raw trigger info\n\tval i0_trigger_chain_masked_r = Cat(i0_trigger_r(3) & (~mtdata1_t(2)(MTDATA1_CHAIN) | i0_trigger_r(2)),\n\t\ti0_trigger_r(2) & (~mtdata1_t(2)(MTDATA1_CHAIN) | i0_trigger_r(3)),\n\t\ti0_trigger_r(1) & (~mtdata1_t(0)(MTDATA1_CHAIN) | i0_trigger_r(0)),\n\t\ti0_trigger_r(0) & (~mtdata1_t(0)(MTDATA1_CHAIN) | i0_trigger_r(1)))\n\n\n\t// This is the highest priority by this point.\n\tval i0_trigger_hit_raw_r = i0_trigger_chain_masked_r.orR\n\n\ti0_trigger_hit_r \t:= i0_trigger_hit_raw_r\n\n\t// Actions include breakpoint, or dmode. Dmode is only possible if the DMODE bit is set.\n\t// Otherwise, take a breakpoint.\n\tval trigger_action\t = Cat(mtdata1_t(3)(MTDATA1_ACTION) & mtdata1_t(3)(MTDATA1_DMODE),\n\t\tmtdata1_t(2)(MTDATA1_ACTION) & mtdata1_t(2)(MTDATA1_DMODE) & ~mtdata1_t(2)(MTDATA1_CHAIN),\n\t\tmtdata1_t(1)(MTDATA1_ACTION) & mtdata1_t(1)(MTDATA1_DMODE),\n\t\tmtdata1_t(0)(MTDATA1_ACTION) & mtdata1_t(0)(MTDATA1_DMODE) & ~mtdata1_t(0)(MTDATA1_CHAIN))\n\n\t// this is needed to set the HIT bit in the triggers\n\tval update_hit_bit_r\t = (Fill(4,i0_trigger_r.orR & ~rfpc_i0_r) & Cat(i0_trigger_chain_masked_r(3), i0_trigger_r(2), i0_trigger_chain_masked_r(1), i0_trigger_r(0)))\n\n\t// action, 1 means dmode. Simultaneous triggers with at least 1 set for dmode force entire action to dmode.\n\tval i0_trigger_action_r = (i0_trigger_chain_masked_r & trigger_action).orR\n\n\ttrigger_hit_dmode_r := (i0_trigger_hit_r & i0_trigger_action_r)\n\n\tval mepc_trigger_hit_sel_pc_r = i0_trigger_hit_r & ~trigger_hit_dmode_r\n\n\t//\n\t// Debug end\n\n\n\t//----------------------------------------------------------------------\n\t//\n\t// Commit\n\t//\n\t//----------------------------------------------------------------------\n\n\n\n\t//--------------------------------------------------------------------------------\n\t// External halt (not debug halt)\n\t// - Fully interlocked handshake\n\t// i_cpu_halt_req ____|--------------|_______________\n\t// core_empty ---------------|___________\n\t// o_cpu_halt_ack _________________|----|__________\n\t// o_cpu_halt_status _______________|---------------------|_________\n\t// i_cpu_run_req ______|----------|____\n\t// o_cpu_run_ack ____________|------|________\n\t//\n\n\n\t// debug mode has priority, ignore PMU/FW halt/run while in debug mode\n\tval i_cpu_halt_req_sync_qual = i_cpu_halt_req_sync & ~io.dec_tlu_debug_mode & ~csr.io.ext_int_freeze_d1\n\tval i_cpu_run_req_sync_qual = i_cpu_run_req_sync & ~io.dec_tlu_debug_mode & pmu_fw_tlu_halted_f & ~csr.io.ext_int_freeze_d1\n\n\tval i_cpu_halt_req_d1\t\t\t =rvdffie(i_cpu_halt_req_sync_qual, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(i_cpu_halt_req_sync_qual,0.U)}\n\tval i_cpu_run_req_d1_raw\t =rvdffie(i_cpu_run_req_sync_qual, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(,0.U)}\n\tio.o_cpu_halt_status\t\t\t :=rvdffie(cpu_halt_status, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(cpu_halt_status,0.U)}\n\tio.o_cpu_halt_ack\t\t\t\t :=rvdffie(cpu_halt_ack, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(cpu_halt_ack,0.U)}\n\tio.o_cpu_run_ack\t\t\t\t :=rvdffie(cpu_run_ack, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(cpu_run_ack,0.U)}\n\tval internal_pmu_fw_halt_mode_f =rvdffie(internal_pmu_fw_halt_mode, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(internal_pmu_fw_halt_mode,0.U)}\n\tpmu_fw_halt_req_f\t\t\t :=rvdffie(pmu_fw_halt_req_ns, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(pmu_fw_halt_req_ns,0.U)}\n\tpmu_fw_tlu_halted_f\t\t\t :=rvdffie(pmu_fw_tlu_halted, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(pmu_fw_tlu_halted,0.U)}\n\tint_timer0_int_hold_f\t\t :=rvdffie(int_timer0_int_hold, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(int_timer0_int_hold,0.U)}\n\tint_timer1_int_hold_f\t\t :=rvdffie(int_timer1_int_hold, io.free_l2clk,reset.asAsyncReset(),io.scan_mode)//withClock(io.free_clk){RegNext(int_timer1_int_hold,0.U)}\n\n\n\t// only happens if we aren't in dgb_halt\n\tval ext_halt_pulse = i_cpu_halt_req_sync_qual & ~i_cpu_halt_req_d1\n\tval enter_pmu_fw_halt_req = ext_halt_pulse | fw_halt_req\n\tpmu_fw_halt_req_ns := (enter_pmu_fw_halt_req | (pmu_fw_halt_req_f & ~pmu_fw_tlu_halted)) & ~debug_halt_req_f\n\tinternal_pmu_fw_halt_mode := pmu_fw_halt_req_ns | (internal_pmu_fw_halt_mode_f & ~i_cpu_run_req_d1 & ~debug_halt_req_f)\n\n\t// debug halt has priority\n\tpmu_fw_tlu_halted := ((pmu_fw_halt_req_f & core_empty & halt_taken & ~enter_debug_halt_req) | (pmu_fw_tlu_halted_f & ~i_cpu_run_req_d1)) & ~debug_halt_req_f\n\n\tcpu_halt_ack := (i_cpu_halt_req_d1 & pmu_fw_tlu_halted_f) | (io.o_cpu_halt_ack & i_cpu_halt_req_sync)\n\tcpu_halt_status := (pmu_fw_tlu_halted_f & ~i_cpu_run_req_d1) | (io.o_cpu_halt_status & ~i_cpu_run_req_d1 & ~internal_dbg_halt_mode_f)\n\tcpu_run_ack := (~pmu_fw_tlu_halted_f & i_cpu_run_req_sync) | (io.o_cpu_halt_status & i_cpu_run_req_d1_raw) | (io.o_cpu_run_ack & i_cpu_run_req_sync)\n\n\tval debug_mode_status = internal_dbg_halt_mode_f\n\tio.o_debug_mode_status := debug_mode_status\n\n\t// high priority interrupts can wakeup from external halt, so can unmasked timer interrupts\n\ti_cpu_run_req_d1 := i_cpu_run_req_d1_raw | ((nmi_int_detected | timer_int_ready | soft_int_ready | int_timer0_int_hold_f | int_timer1_int_hold_f | (io.dec_pic.mhwakeup & mhwakeup_ready)) & io.o_cpu_halt_status & ~i_cpu_halt_req_d1)\n\n\t//--------------------------------------------------------------------------------\n\t//--------------------------------------------------------------------------------\n\n\tval lsu_single_ecc_error_r \t\t=io.lsu_single_ecc_error_incr\n\t// mdseac_locked_f\t\t\t\t\t:=withClock(io.free_clk){RegNext(mdseac_locked_ns,0.U)}\n\t// val lsu_single_ecc_error_r_d1\t=withClock(io.free_clk){RegNext(lsu_single_ecc_error_r,0.U)}\n\tval lsu_error_pkt_addr_r\t\t \t=io.lsu_error_pkt_r.bits.addr\n\tval lsu_exc_valid_r_raw = io.lsu_error_pkt_r.valid & ~io.dec_tlu_flush_lower_wb\n\tlsu_i0_exc_r_raw := io.lsu_error_pkt_r.valid\n\tval lsu_i0_exc_r = lsu_i0_exc_r_raw & lsu_exc_valid_r_raw & ~i0_trigger_hit_r & ~rfpc_i0_r\n\tval lsu_exc_valid_r = lsu_i0_exc_r\n\t// lsu_exc_valid_r_d1\t\t\t:=withClock(lsu_r_wb_clk){RegNext(lsu_exc_valid_r,0.U)}\n\t// val lsu_i0_exc_r_d1\t\t\t=withClock(lsu_r_wb_clk){RegNext(lsu_i0_exc_r,0.U)}\n\n\t// Single bit ECC errors on loads are RFNPC corrected, with the corrected data written to the GPR.\n\t// LSU turns the load into a store and patches the data in the DCCM\n\tval lsu_i0_rfnpc_r = io.dec_tlu_i0_valid_r & ~i0_trigger_hit_r & (~io.lsu_error_pkt_r.bits.inst_type & io.lsu_error_pkt_r.bits.single_ecc_error)\n\n\t// Final commit valids\n\tval tlu_i0_commit_cmt = io.dec_tlu_i0_valid_r & ~rfpc_i0_r & ~lsu_i0_exc_r & ~inst_acc_r & ~io.dec_tlu_dbg_halted & ~request_debug_mode_r_d1 & ~i0_trigger_hit_r\n\n\t// unified place to manage the killing of arch state writebacks\n\ttlu_i0_kill_writeb_r := rfpc_i0_r | lsu_i0_exc_r | inst_acc_r | (illegal_r & io.dec_tlu_dbg_halted) | i0_trigger_hit_r\n\tio.tlu_mem.dec_tlu_i0_commit_cmt := tlu_i0_commit_cmt\n\n\n\t// refetch PC, microarch flush\n\t// ic errors only in pipe0\n\trfpc_i0_r := ((io.dec_tlu_i0_valid_r & ~tlu_flush_lower_r_d1 & (io.tlu_exu.exu_i0_br_error_r | io.tlu_exu.exu_i0_br_start_error_r)) | ((ic_perr_r | iccm_sbecc_r) & ~csr.io.ext_int_freeze_d1)) & ~i0_trigger_hit_r & ~lsu_i0_rfnpc_r\n\n\t// From the indication of a iccm single bit error until the first commit or flush, maintain a repair state. In the repair state, rfnpc i0 commits.\n\ticcm_repair_state_ns := iccm_sbecc_r | (iccm_repair_state_d1 & ~io.tlu_exu.dec_tlu_flush_lower_r)\n\n\n\tval MCPC =0x7c2.U(12.W)\n\n\t// this is a flush of last resort, meaning only assert it if there is no other flush happening.\n\tval iccm_repair_state_rfnpc = tlu_i0_commit_cmt & iccm_repair_state_d1 & ~(ebreak_r | ecall_r | mret_r | take_reset | illegal_r | (dec_csr_wen_r_mod & (io.dec_csr_wraddr_r ===MCPC)))\n\n\tval dec_tlu_br0_error_r = WireInit(Bool(),0.B)\n\tval dec_tlu_br0_start_error_r = WireInit(Bool(),0.B)\n\tval dec_tlu_br0_v_r = WireInit(Bool(),0.B)\n\tif(BTB_ENABLE){\n\t\t// go ahead and repair the branch error on other flushes, doesn't have to be the rfpc flush\n\t\tdec_tlu_br0_error_r := io.tlu_exu.exu_i0_br_error_r & io.dec_tlu_i0_valid_r & ~tlu_flush_lower_r_d1\n\t\tdec_tlu_br0_start_error_r := io.tlu_exu.exu_i0_br_start_error_r & io.dec_tlu_i0_valid_r & ~tlu_flush_lower_r_d1\n\t\tdec_tlu_br0_v_r := io.tlu_exu.exu_i0_br_valid_r & io.dec_tlu_i0_valid_r & ~tlu_flush_lower_r_d1 & (~io.tlu_exu.exu_i0_br_mp_r | ~io.tlu_exu.exu_pmu_i0_br_ataken)\n\n\n\t\tio.tlu_bp.dec_tlu_br0_r_pkt.bits.hist \t\t\t:= io.tlu_exu.exu_i0_br_hist_r\n\t\tio.tlu_bp.dec_tlu_br0_r_pkt.bits.br_error \t\t:= dec_tlu_br0_error_r\n\t\tio.tlu_bp.dec_tlu_br0_r_pkt.bits.br_start_error \t:= dec_tlu_br0_start_error_r\n\t\tio.tlu_bp.dec_tlu_br0_r_pkt.valid \t\t\t:= dec_tlu_br0_v_r\n\t\tio.tlu_bp.dec_tlu_br0_r_pkt.bits.way \t\t\t:= io.exu_i0_br_way_r\n\t\tio.tlu_bp.dec_tlu_br0_r_pkt.bits.middle \t\t\t:= io.tlu_exu.exu_i0_br_middle_r\n\n\t}\n\t// if (pt.BTB_ENABLE==1)\n\telse {\n\t\tdec_tlu_br0_error_r := 0.U\n\t\tdec_tlu_br0_start_error_r := 0.U\n\t\tdec_tlu_br0_v_r := 0.U\n\t\tio.tlu_bp.dec_tlu_br0_r_pkt := 0.U.asTypeOf(io.tlu_bp.dec_tlu_br0_r_pkt)\n\t\t// else: !if(pt.BTB_ENABLE==1)\n\t}\n\n\n\t// only expect these in pipe 0\n\tebreak_r := (io.dec_tlu_packet_r.pmu_i0_itype === EBREAK) & io.dec_tlu_i0_valid_r & !i0_trigger_hit_r & ~dcsr(DCSR_EBREAKM) & ~rfpc_i0_r\n\tecall_r := (io.dec_tlu_packet_r.pmu_i0_itype === ECALL) & io.dec_tlu_i0_valid_r & !i0_trigger_hit_r & ~rfpc_i0_r\n\tillegal_r := ~io.dec_tlu_packet_r.legal & io.dec_tlu_i0_valid_r & !i0_trigger_hit_r & ~rfpc_i0_r\n\tmret_r := (io.dec_tlu_packet_r.pmu_i0_itype === MRET) & io.dec_tlu_i0_valid_r & !i0_trigger_hit_r & ~rfpc_i0_r\n\t// fence_i includes debug only fence_i's\n\tfence_i_r := (io.dec_tlu_packet_r.fence_i & io.dec_tlu_i0_valid_r & !i0_trigger_hit_r) & ~rfpc_i0_r\n\tic_perr_r := ifu_ic_error_start_f & ~csr.io.ext_int_freeze_d1 & (!internal_dbg_halt_mode_f | dcsr_single_step_running) & ~internal_pmu_fw_halt_mode_f\n\ticcm_sbecc_r := ifu_iccm_rd_ecc_single_err_f & ~csr.io.ext_int_freeze_d1 & (!internal_dbg_halt_mode_f | dcsr_single_step_running) & ~internal_pmu_fw_halt_mode_f\n\n\tinst_acc_r_raw := io.dec_tlu_packet_r.icaf & io.dec_tlu_i0_valid_r\n\tinst_acc_r := inst_acc_r_raw & ~rfpc_i0_r & ~i0_trigger_hit_r\n\tval inst_acc_second_r = io.dec_tlu_packet_r.icaf_second\n\n\tebreak_to_debug_mode_r := (io.dec_tlu_packet_r.pmu_i0_itype === EBREAK) & io.dec_tlu_i0_valid_r & ~i0_trigger_hit_r & dcsr(DCSR_EBREAKM) & ~rfpc_i0_r\n\n\tebreak_to_debug_mode_r_d1:= withClock(e4e5_clk){RegNext(ebreak_to_debug_mode_r,0.U)}\n\tio.tlu_mem.dec_tlu_fence_i_wb := fence_i_r\n\n\n\tint_exc.io.free_l2clk := io.free_l2clk\n\tint_exc.io.scan_mode := io.scan_mode\n\tint_exc.io.dec_csr_stall_int_ff := io.dec_csr_stall_int_ff\n\tint_exc.io.mstatus_mie_ns := mstatus_mie_ns\n\tint_exc.io.mip := mip\n\tint_exc.io.mie_ns := mie_ns\n\tint_exc.io.mret_r := mret_r\n\tint_exc.io.pmu_fw_tlu_halted_f := pmu_fw_tlu_halted_f\n\tint_exc.io.int_timer0_int_hold_f := int_timer0_int_hold_f\n\tint_exc.io.int_timer1_int_hold_f := int_timer1_int_hold_f\n\tint_exc.io.internal_dbg_halt_mode_f := internal_dbg_halt_mode_f\n\tint_exc.io.dcsr_single_step_running := dcsr_single_step_running\n\tint_exc.io.internal_dbg_halt_mode := internal_dbg_halt_mode\n\tint_exc.io.dec_tlu_i0_valid_r := io.dec_tlu_i0_valid_r\n\tint_exc.io.internal_pmu_fw_halt_mode := internal_pmu_fw_halt_mode\n\tint_exc.io.i_cpu_halt_req_d1 := i_cpu_halt_req_d1\n\tint_exc.io.ebreak_to_debug_mode_r := ebreak_to_debug_mode_r\n\tint_exc.io.lsu_fir_error := io.lsu_fir_error\n\tint_exc.io.csr_pkt := csr_pkt\n\tint_exc.io.dec_csr_any_unq_d := io.dec_csr_any_unq_d\n\tint_exc.io.lsu_fastint_stall_any := io.lsu_fastint_stall_any\n\tint_exc.io.reset_delayed := reset_delayed\n\tint_exc.io.mpc_reset_run_req := io.mpc_reset_run_req\n\tint_exc.io.nmi_int_detected := nmi_int_detected\n\tint_exc.io.dcsr_single_step_running_f := dcsr_single_step_running_f\n\tint_exc.io.dcsr_single_step_done_f := dcsr_single_step_done_f\n\tint_exc.io.dcsr := dcsr\n\tint_exc.io.mtvec := mtvec\n\tint_exc.io.tlu_i0_commit_cmt := tlu_i0_commit_cmt\n\tint_exc.io.i0_trigger_hit_r := i0_trigger_hit_r\n\tint_exc.io.pause_expired_r := pause_expired_r\n\tint_exc.io.nmi_vec := io.nmi_vec\n\tint_exc.io.lsu_i0_rfnpc_r := lsu_i0_rfnpc_r\n\tint_exc.io.fence_i_r := fence_i_r\n\tint_exc.io.iccm_repair_state_rfnpc := iccm_repair_state_rfnpc\n\tint_exc.io.i_cpu_run_req_d1 := i_cpu_run_req_d1\n\tint_exc.io.rfpc_i0_r := rfpc_i0_r\n\tint_exc.io.lsu_exc_valid_r := lsu_exc_valid_r\n\tint_exc.io.trigger_hit_dmode_r := trigger_hit_dmode_r\n\tint_exc.io.take_halt := take_halt\n\tint_exc.io.rst_vec := io.rst_vec\n\tint_exc.io.lsu_fir_addr := io.lsu_fir_addr\n\tint_exc.io.dec_tlu_i0_pc_r := io.dec_tlu_i0_pc_r\n\tint_exc.io.npc_r := npc_r\n\tint_exc.io.mepc := mepc\n\tint_exc.io.debug_resume_req_f := debug_resume_req_f\n\tint_exc.io.dpc := dpc\n\tint_exc.io.npc_r_d1 := npc_r_d1\n\tint_exc.io.tlu_flush_lower_r_d1 := tlu_flush_lower_r_d1\n\tint_exc.io.dec_tlu_dbg_halted := io.dec_tlu_dbg_halted\n\tint_exc.io.ebreak_r := ebreak_r\n\tint_exc.io.ecall_r := ecall_r\n\tint_exc.io.illegal_r := illegal_r\n\tint_exc.io.inst_acc_r := inst_acc_r\n\tint_exc.io.lsu_i0_exc_r := lsu_i0_exc_r\n\tint_exc.io.lsu_error_pkt_r := io.lsu_error_pkt_r\n\tint_exc.io.dec_tlu_wr_pause_r_d1 := dec_tlu_wr_pause_r_d1\n\t//outputs\n\tmhwakeup_ready := int_exc.io.mhwakeup_ready\n\text_int_ready := int_exc.io.ext_int_ready\n\tce_int_ready := int_exc.io.ce_int_ready\n\tsoft_int_ready := int_exc.io.soft_int_ready\n\ttimer_int_ready := int_exc.io.timer_int_ready\n\tint_timer0_int_hold := int_exc.io.int_timer0_int_hold\n\tint_timer1_int_hold := int_exc.io.int_timer1_int_hold\n\tinternal_dbg_halt_timers := int_exc.io.internal_dbg_halt_timers\n\ttake_ext_int_start := int_exc.io.take_ext_int_start\n\tint_exc.io.ext_int_freeze_d1 := csr.io.ext_int_freeze_d1\n\tint_exc.io.take_ext_int_start_d1 := csr.io.take_ext_int_start_d1\n\tint_exc.io.take_ext_int_start_d2 := csr.io.take_ext_int_start_d2\n\tint_exc.io.take_ext_int_start_d3 := csr.io.take_ext_int_start_d3\n\text_int_freeze := int_exc.io.ext_int_freeze\n\ttake_ext_int := int_exc.io.take_ext_int\n\tfast_int_meicpct := int_exc.io.fast_int_meicpct\n\tignore_ext_int_due_to_lsu_stall := int_exc.io.ignore_ext_int_due_to_lsu_stall\n\ttake_ce_int := int_exc.io.take_ce_int\n\ttake_soft_int := int_exc.io.take_soft_int\n\ttake_timer_int := int_exc.io.take_timer_int\n\ttake_int_timer0_int := int_exc.io.take_int_timer0_int\n\ttake_int_timer1_int := int_exc.io.take_int_timer1_int\n\ttake_reset := int_exc.io.take_reset\n\ttake_nmi := int_exc.io.take_nmi\n\tsynchronous_flush_r := int_exc.io.synchronous_flush_r\n\ttlu_flush_lower_r := int_exc.io.tlu_flush_lower_r\n\tio.dec_tlu_flush_lower_wb := int_exc.io.dec_tlu_flush_lower_wb\n\tio.tlu_exu.dec_tlu_flush_lower_r := int_exc.io.dec_tlu_flush_lower_r\n\tio.tlu_exu.dec_tlu_flush_path_r := int_exc.io.dec_tlu_flush_path_r\n\tinterrupt_valid_r_d1 := int_exc.io.interrupt_valid_r_d1\n\texc_or_int_valid_r_d1 := int_exc.io.exc_or_int_valid_r_d1\n\ttake_nmi_r_d1 := int_exc.io.take_nmi_r_d1\n\tpause_expired_wb := int_exc.io.pause_expired_wb\n\tinterrupt_valid_r := int_exc.io.interrupt_valid_r\n\n\t//intrputsd\n\n\tcsr.io.ext_int_freeze := int_exc.io.ext_int_freeze\n\tcsr.io.free_clk := io.free_clk\n\tcsr.io.free_l2clk := io.free_l2clk\n\tcsr.io.scan_mode := io.scan_mode\n\tcsr.io.dec_csr_wrdata_r := io.dec_csr_wrdata_r\n\tcsr.io.dec_csr_wraddr_r := io.dec_csr_wraddr_r\n\tcsr.io.dec_csr_rdaddr_d := io.dec_csr_rdaddr_d\n\tcsr.io.dec_csr_wen_unq_d := io.dec_csr_wen_unq_d\n\tcsr.io.dec_i0_decode_d := io.dec_i0_decode_d\n\tcsr.io.ifu_ic_debug_rd_data_valid := io.tlu_mem.ifu_ic_debug_rd_data_valid\n\tcsr.io.ifu_pmu_bus_trxn := io.tlu_mem.ifu_pmu_bus_trxn\n\tcsr.io.dma_iccm_stall_any :=io.tlu_dma.dma_iccm_stall_any\n\tcsr.io.dma_dccm_stall_any :=io.tlu_dma.dma_dccm_stall_any\n\tcsr.io.lsu_store_stall_any :=io.lsu_store_stall_any\n\tcsr.io.dec_pmu_presync_stall :=io.dec_pmu_presync_stall\n\tcsr.io.dec_pmu_postsync_stall :=io.dec_pmu_postsync_stall\n\tcsr.io.dec_pmu_decode_stall :=io.dec_pmu_decode_stall\n\tcsr.io.ifu_pmu_fetch_stall :=io.tlu_ifc.ifu_pmu_fetch_stall\n\tcsr.io.dec_tlu_packet_r :=io.dec_tlu_packet_r\n\tcsr.io.exu_pmu_i0_br_ataken :=io.tlu_exu.exu_pmu_i0_br_ataken\n\tcsr.io.exu_pmu_i0_br_misp :=io.tlu_exu.exu_pmu_i0_br_misp\n\tcsr.io.dec_pmu_instr_decoded :=io.dec_pmu_instr_decoded\n\tcsr.io.ifu_pmu_instr_aligned :=io.ifu_pmu_instr_aligned\n\tcsr.io.exu_pmu_i0_pc4 :=io.tlu_exu.exu_pmu_i0_pc4\n\tcsr.io.ifu_pmu_ic_miss :=io.tlu_mem.ifu_pmu_ic_miss\n\tcsr.io.ifu_pmu_ic_hit :=io.tlu_mem.ifu_pmu_ic_hit\n\tcsr.io.dec_csr_wen_r := io.dec_csr_wen_r\n\tcsr.io.dec_tlu_dbg_halted := io.dec_tlu_dbg_halted\n\tcsr.io.dma_pmu_dccm_write := io.tlu_dma.dma_pmu_dccm_write\n\tcsr.io.dma_pmu_dccm_read := io.tlu_dma.dma_pmu_dccm_read\n\tcsr.io.dma_pmu_any_write := io.tlu_dma.dma_pmu_any_write\n\tcsr.io.dma_pmu_any_read := io.tlu_dma.dma_pmu_any_read\n\tcsr.io.lsu_pmu_bus_busy := io.tlu_busbuff.lsu_pmu_bus_busy\n\tcsr.io.dec_tlu_i0_pc_r := io.dec_tlu_i0_pc_r\n\tcsr.io.dec_tlu_i0_valid_r := io.dec_tlu_i0_valid_r\n\tcsr.io.dec_csr_stall_int_ff := io.dec_csr_stall_int_ff\n\tcsr.io.dec_csr_any_unq_d := io.dec_csr_any_unq_d\n\tcsr.io.ifu_pmu_bus_busy := io.tlu_mem.ifu_pmu_bus_busy\n\tcsr.io.lsu_pmu_bus_error := io.tlu_busbuff.lsu_pmu_bus_error\n\tcsr.io.ifu_pmu_bus_error := io.tlu_mem.ifu_pmu_bus_error\n\tcsr.io.lsu_pmu_bus_misaligned := io.tlu_busbuff.lsu_pmu_bus_misaligned\n\tcsr.io.lsu_pmu_bus_trxn := io.tlu_busbuff.lsu_pmu_bus_trxn\n\tcsr.io.ifu_ic_debug_rd_data := io.tlu_mem.ifu_ic_debug_rd_data\n\tcsr.io.pic_pl := io.dec_pic.pic_pl\n\tcsr.io.pic_claimid := io.dec_pic.pic_claimid\n\tcsr.io.iccm_dma_sb_error := io.iccm_dma_sb_error\n\tcsr.io.lsu_imprecise_error_addr_any := io.tlu_busbuff.lsu_imprecise_error_addr_any\n\tcsr.io.lsu_imprecise_error_load_any := io.tlu_busbuff.lsu_imprecise_error_load_any\n\tcsr.io.lsu_imprecise_error_store_any := io.tlu_busbuff.lsu_imprecise_error_store_any\n\tcsr.io.dec_illegal_inst := io.dec_illegal_inst\n\tcsr.io.lsu_error_pkt_r := io.lsu_error_pkt_r\n\tcsr.io.mexintpend := io.dec_pic.mexintpend\n\tcsr.io.exu_npc_r := io.tlu_exu.exu_npc_r\n\tcsr.io.mpc_reset_run_req := io.mpc_reset_run_req\n\tcsr.io.rst_vec := io.rst_vec\n\tcsr.io.core_id := io.core_id\n\tcsr.io.dec_timer_rddata_d := dec_timer_rddata_d\n\tcsr.io.dec_timer_read_d := dec_timer_read_d\n\tio.dec_pic.dec_tlu_meicurpl := csr.io.dec_tlu_meicurpl\n\tio.tlu_exu.dec_tlu_meihap := csr.io.dec_tlu_meihap\n\tio.dec_pic.dec_tlu_meipt := csr.io.dec_tlu_meipt\n\tio.dec_tlu_int_valid_wb1 := csr.io.dec_tlu_int_valid_wb1\n\tio.dec_tlu_i0_exc_valid_wb1 := csr.io.dec_tlu_i0_exc_valid_wb1\n\tio.dec_tlu_i0_valid_wb1 := csr.io.dec_tlu_i0_valid_wb1\n\tio.tlu_mem.dec_tlu_ic_diag_pkt := csr.io.dec_tlu_ic_diag_pkt\n\tio.trigger_pkt_any := csr.io.trigger_pkt_any\n\tio.dec_tlu_mtval_wb1 := csr.io.dec_tlu_mtval_wb1\n\tio.dec_tlu_exc_cause_wb1 := csr.io.dec_tlu_exc_cause_wb1\n\tio.dec_tlu_perfcnt0 := csr.io.dec_tlu_perfcnt0\n\tio.dec_tlu_perfcnt1 := csr.io.dec_tlu_perfcnt1\n\tio.dec_tlu_perfcnt2 := csr.io.dec_tlu_perfcnt2\n\tio.dec_tlu_perfcnt3 := csr.io.dec_tlu_perfcnt3\n\tio.dec_tlu_misc_clk_override := csr.io.dec_tlu_misc_clk_override\n\tio.dec_tlu_picio_clk_override := csr.io.dec_tlu_picio_clk_override\n\tio.dec_tlu_dec_clk_override := csr.io.dec_tlu_dec_clk_override\n\tio.dec_tlu_ifu_clk_override := csr.io.dec_tlu_ifu_clk_override\n\tio.dec_tlu_lsu_clk_override := csr.io.dec_tlu_lsu_clk_override\n\tio.dec_tlu_bus_clk_override := csr.io.dec_tlu_bus_clk_override\n\tio.dec_tlu_pic_clk_override := csr.io.dec_tlu_pic_clk_override\n\tio.dec_tlu_dccm_clk_override := csr.io.dec_tlu_dccm_clk_override\n\tio.dec_tlu_icm_clk_override := csr.io.dec_tlu_icm_clk_override\n\tio.dec_csr_rddata_d := csr.io.dec_csr_rddata_d\n\tio.dec_tlu_pipelining_disable := csr.io.dec_tlu_pipelining_disable\n\tio.dec_tlu_wr_pause_r := csr.io.dec_tlu_wr_pause_r\n\tio.tlu_ifc.dec_tlu_mrac_ff := csr.io.dec_tlu_mrac_ff\n\tio.tlu_busbuff.dec_tlu_wb_coalescing_disable := csr.io.dec_tlu_wb_coalescing_disable\n\tio.tlu_bp.dec_tlu_bpred_disable := csr.io.dec_tlu_bpred_disable\n\tio.tlu_busbuff.dec_tlu_sideeffect_posted_disable := csr.io.dec_tlu_sideeffect_posted_disable\n\tio.tlu_mem.dec_tlu_core_ecc_disable := csr.io.dec_tlu_core_ecc_disable\n\tio.tlu_busbuff.dec_tlu_external_ldfwd_disable := csr.io.dec_tlu_external_ldfwd_disable\n\tio.tlu_dma.dec_tlu_dma_qos_prty := csr.io.dec_tlu_dma_qos_prty\n\tio.dec_tlu_trace_disable := csr.io.dec_tlu_trace_disable\n\tcsr.io.dec_illegal_inst := io.dec_illegal_inst\n\tcsr.io.lsu_error_pkt_r := io.lsu_error_pkt_r\n\tcsr.io.mexintpend := io.dec_pic.mexintpend\n\tcsr.io.exu_npc_r := io.tlu_exu.exu_npc_r\n\tcsr.io.mpc_reset_run_req := io.mpc_reset_run_req\n\tcsr.io.rst_vec := io.rst_vec\n\tcsr.io.core_id := io.core_id\n\tcsr.io.dec_timer_rddata_d := dec_timer_rddata_d\n\tcsr.io.dec_timer_read_d := dec_timer_read_d\n\n\n\tcsr.io.rfpc_i0_r := rfpc_i0_r\n\tcsr.io.i0_trigger_hit_r := i0_trigger_hit_r\n\tcsr.io.exc_or_int_valid_r := int_exc.io.exc_or_int_valid_r\n\tcsr.io.mret_r := mret_r\n\tcsr.io.dcsr_single_step_running_f := dcsr_single_step_running_f\n\tcsr.io.dec_timer_t0_pulse := dec_timer_t0_pulse\n\tcsr.io.dec_timer_t1_pulse := dec_timer_t1_pulse\n\tcsr.io.timer_int_sync := timer_int_sync\n\tcsr.io.soft_int_sync := soft_int_sync\n\tcsr.io.csr_wr_clk := csr_wr_clk\n\tcsr.io.ebreak_to_debug_mode_r := ebreak_to_debug_mode_r\n\tcsr.io.dec_tlu_pmu_fw_halted := dec_tlu_pmu_fw_halted\n\tcsr.io.lsu_fir_error := io.lsu_fir_error\n\tcsr.io.tlu_flush_lower_r_d1 := tlu_flush_lower_r_d1\n\tcsr.io.dec_tlu_flush_noredir_r_d1 := dec_tlu_flush_noredir_r_d1\n\tcsr.io.tlu_flush_path_r_d1 := int_exc.io.tlu_flush_path_r_d1\n\tcsr.io.reset_delayed := reset_delayed\n\tcsr.io.interrupt_valid_r := interrupt_valid_r\n\tcsr.io.i0_exception_valid_r := int_exc.io.i0_exception_valid_r\n\tcsr.io.lsu_exc_valid_r := lsu_exc_valid_r\n\tcsr.io.mepc_trigger_hit_sel_pc_r := mepc_trigger_hit_sel_pc_r\n\tcsr.io.lsu_single_ecc_error_r := lsu_single_ecc_error_r\n\tcsr.io.e4e5_int_clk := e4e5_int_clk\n\tcsr.io.lsu_i0_exc_r := lsu_i0_exc_r\n\tcsr.io.inst_acc_r := inst_acc_r\n\tcsr.io.inst_acc_second_r := inst_acc_second_r\n\tcsr.io.take_nmi := take_nmi\n\tcsr.io.lsu_error_pkt_addr_r := lsu_error_pkt_addr_r\n\tcsr.io.exc_cause_r := int_exc.io.exc_cause_r\n\tcsr.io.i0_valid_wb := int_exc.io.i0_valid_wb\n\tcsr.io.exc_or_int_valid_r_d1 := exc_or_int_valid_r_d1\n\tcsr.io.interrupt_valid_r_d1 := interrupt_valid_r_d1\n\tcsr.io.clk_override := clk_override\n\tcsr.io.i0_exception_valid_r_d1 := int_exc.io.i0_exception_valid_r_d1\n\t// lsu_i0_exc_r_d1 := csr.io.lsu_i0_exc_r_d1\n\tcsr.io.exc_cause_wb := int_exc.io.exc_cause_wb\n\tcsr.io.nmi_lsu_store_type := nmi_lsu_store_type\n\tcsr.io.nmi_lsu_load_type := nmi_lsu_load_type\n\tcsr.io.tlu_i0_commit_cmt := tlu_i0_commit_cmt\n\tcsr.io.ebreak_r := ebreak_r\n\tcsr.io.ecall_r := ecall_r\n\tcsr.io.illegal_r := illegal_r\n\tmdseac_locked_f := csr.io.mdseac_locked_f\n\tcsr.io.nmi_int_detected_f := nmi_int_detected_f\n\tcsr.io.internal_dbg_halt_mode_f2 := internal_dbg_halt_mode_f2\n\tcsr.io.ic_perr_r := ic_perr_r\n\tcsr.io.iccm_sbecc_r := iccm_sbecc_r\n\tcsr.io.ifu_miss_state_idle_f := ifu_miss_state_idle_f\n\tcsr.io.lsu_idle_any_f := lsu_idle_any_f\n\tcsr.io.dbg_tlu_halted_f := dbg_tlu_halted_f\n\tcsr.io.dbg_tlu_halted := dbg_tlu_halted\n\tcsr.io.debug_halt_req_f \t\t\t := debug_halt_req_f\n\tcsr.io.take_ext_int_start\t\t := take_ext_int_start\n\tcsr.io.trigger_hit_dmode_r_d1 \t := trigger_hit_dmode_r_d1\n\tcsr.io.trigger_hit_r_d1 \t := int_exc.io.trigger_hit_r_d1\n\tcsr.io.dcsr_single_step_done_f \t := dcsr_single_step_done_f\n\tcsr.io.ebreak_to_debug_mode_r_d1 := ebreak_to_debug_mode_r_d1\n\tcsr.io.debug_halt_req \t\t\t := debug_halt_req\n\tcsr.io.allow_dbg_halt_csr_write := allow_dbg_halt_csr_write\n\tcsr.io.internal_dbg_halt_mode_f := internal_dbg_halt_mode_f\n\tcsr.io.enter_debug_halt_req := enter_debug_halt_req\n\tcsr.io.internal_dbg_halt_mode := internal_dbg_halt_mode\n\tcsr.io.request_debug_mode_done := request_debug_mode_done\n\tcsr.io.request_debug_mode_r := request_debug_mode_r\n\tcsr.io.update_hit_bit_r := update_hit_bit_r\n\tcsr.io.take_timer_int := take_timer_int\n\tcsr.io.take_int_timer0_int := take_int_timer0_int\n\tcsr.io.take_int_timer1_int := take_int_timer1_int\n\tcsr.io.take_ext_int := take_ext_int\n\tcsr.io.tlu_flush_lower_r := tlu_flush_lower_r\n\tcsr.io.dec_tlu_br0_error_r := dec_tlu_br0_error_r\n\tcsr.io.dec_tlu_br0_start_error_r := dec_tlu_br0_start_error_r\n\tcsr.io.lsu_pmu_load_external_r := lsu_pmu_load_external_r\n\tcsr.io.lsu_pmu_store_external_r := lsu_pmu_store_external_r\n\tcsr.io.trigger_enabled := trigger_enabled\n\tcsr.io.csr_pkt := csr_pkt\n\n\tnpc_r := csr.io.npc_r\n\tnpc_r_d1 := csr.io.npc_r_d1\n\tmie_ns := csr.io.mie_ns\n\tmepc := csr.io.mepc\n\tmdseac_locked_ns := csr.io.mdseac_locked_ns\n\tforce_halt := csr.io.force_halt\n\tdpc := csr.io.dpc\n\tmstatus_mie_ns := csr.io.mstatus_mie_ns\n\tdec_csr_wen_r_mod := csr.io.dec_csr_wen_r_mod\n\tfw_halt_req := csr.io.fw_halt_req\n\tmstatus := csr.io.mstatus\n\tdcsr := csr.io.dcsr\n\tmtvec := csr.io.mtvec\n\tmip := csr.io.mip\n\tmtdata1_t :=csr.io.mtdata1_t\n\tval csr_read=Module(new dec_decode_csr_read)\n\tcsr_read.io.dec_csr_rdaddr_d:=io.dec_csr_rdaddr_d\n\tcsr_pkt:=csr_read.io.csr_pkt\n\n\tio.dec_tlu_presync_d := csr_pkt.presync & io.dec_csr_any_unq_d & ~io.dec_csr_wen_unq_d\n\tio.dec_tlu_postsync_d := csr_pkt.postsync & io.dec_csr_any_unq_d\n\n\t// allow individual configuration of these features\n\tval conditionally_illegal = (csr_pkt.csr_mitcnt0 | csr_pkt.csr_mitcnt1 | csr_pkt.csr_mitb0 | csr_pkt.csr_mitb1 | csr_pkt.csr_mitctl0 | csr_pkt.csr_mitctl1) & ~TIMER_LEGAL_EN.asUInt\n\tval valid_csr = ( csr_pkt.legal & (~(csr_pkt.csr_dcsr | csr_pkt.csr_dpc | csr_pkt.csr_dmst | csr_pkt.csr_dicawics | csr_pkt.csr_dicad0 | csr_pkt.csr_dicad0h | csr_pkt.csr_dicad1 | csr_pkt.csr_dicago) | dbg_tlu_halted_f) & ~fast_int_meicpct & ~conditionally_illegal)\n\n\tio.dec_csr_legal_d := ( io.dec_csr_any_unq_d &valid_csr & ~(io.dec_csr_wen_unq_d & (csr_pkt.csr_mvendorid | csr_pkt.csr_marchid | csr_pkt.csr_mimpid | csr_pkt.csr_mhartid | csr_pkt.csr_mdseac | csr_pkt.csr_meihap)) )\n}\n\ntrait CSRs{\n\tval MISA = \"h301\".U(12.W)\n\tval MVENDORID = \"hf11\".U(12.W)\n\tval MARCHID = \"hf12\".U(12.W)\n\tval MIMPID = \"hf13\".U(12.W)\n\tval MHARTID = \"hf14\".U(12.W)\n\tval MSTATUS = \"h300\".U(12.W)\n\tval MTVEC = \"h305\".U(12.W)\n\tval MIP = \"h344\".U(12.W)\n\tval MIE = \"h304\".U(12.W)\n\tval MCYCLEL = \"hb00\".U(12.W)\n\tval MCYCLEH = \"hb80\".U(12.W)\n\tval MINSTRETL = \"hb02\".U(12.W)\n\tval MINSTRETH = \"hb82\".U(12.W)\n\tval MSCRATCH = \"h340\".U(12.W)\n\tval MEPC = \"h341\".U(12.W)\n\tval MCAUSE = \"h342\".U(12.W)\n\tval MSCAUSE = \"h7ff\".U(12.W)\n\tval MTVAL = \"h343\".U(12.W)\n\tval MCGC = \"h7f8\".U(12.W)\n\tval MFDC = \"h7f9\".U(12.W)\n\tval MCPC = \"h7c2\".U(12.W)\n\tval MRAC = \"h7c0\".U(12.W)\n\tval MDEAU = \"hbc0\".U(12.W)\n\tval MDSEAC = \"hfc0\".U(12.W)\n\tval MPMC = \"h7c6\".U(12.W)\n\tval MICECT = \"h7f0\".U(12.W)\n\tval MICCMECT = \"h7f1\".U(12.W)\n\tval MDCCMECT = \"h7f2\".U(12.W)\n\tval MFDHT = \"h7ce\".U(12.W)\n\tval MFDHS = \"h7cf\".U(12.W)\n\tval MEIVT = \"hbc8\".U(12.W)\n\tval MEIHAP = \"hfc8\".U(12.W)\n\tval MEICURPL = \"hbcc\".U(12.W)\n\tval MEICIDPL = \"hbcb\".U(12.W)\n\tval MEICPCT = \"hbca\".U(12.W)\n\tval MEIPT = \"hbc9\".U(12.W)\n\tval DCSR = \"h7b0\".U(12.W)\n\tval DPC = \"h7b1\".U(12.W)\n\tval DICAWICS = \"h7c8\".U(12.W)\n\tval DICAD0 = \"h7c9\".U(12.W)\n\tval DICAD0H = \"h7cc\".U(12.W)\n\tval DICAD1 = \"h7ca\".U(12.W)\n\tval DICAGO = \"h7cb\".U(12.W)\n\tval MTSEL = \"h7a0\".U(12.W)\n\tval MTDATA1 = \"h7a1\".U(12.W)\n\tval MTDATA2 = \"h7a2\".U(12.W)\n\tval MHPMC3 = \"hB03\".U(12.W)\n\tval MHPMC3H = \"hB83\".U(12.W)\n\tval MHPMC4 = \"hB04\".U(12.W)\n\tval MHPMC4H = \"hB84\".U(12.W)\n\tval MHPMC5 = \"hB05\".U(12.W)\n\tval MHPMC5H = \"hB85\".U(12.W)\n\tval MHPMC6 = \"hB06\".U(12.W)\n\tval MHPMC6H = \"hB86\".U(12.W)\n\tval MHPME3 = \"h323\".U(12.W)\n\tval MHPME4 = \"h324\".U(12.W)\n\tval MHPME5 = \"h325\".U(12.W)\n\tval MHPME6 = \"h326\".U(12.W)\n\tval MCOUNTINHIBIT = \"h320\".U(12.W)\n\tval MSTATUS_MIE = 0.U\n\tval MIP_MCEIP = 5.U\n\tval MIP_MITIP0 = 4.U\n\tval MIP_MITIP1 = 3.U\n\tval MIP_MEIP = 2\n\tval MIP_MTIP = 1\n\tval MIP_MSIP = 0\n\tval MIE_MCEIE = 5\n\tval MIE_MITIE0 = 4\n\tval MIE_MITIE1 = 3\n\tval MIE_MEIE = 2\n\tval MIE_MTIE = 1\n\tval MIE_MSIE = 0\n\tval DCSR_EBREAKM = 15\n\tval DCSR_STEPIE = 11\n\tval DCSR_STOPC = 10\n\tval DCSR_STEP = 2\n\tval MTDATA1_DMODE = 9\n\tval MTDATA1_SEL = 7\n\tval MTDATA1_ACTION = 6\n\tval MTDATA1_CHAIN = 5\n\tval MTDATA1_MATCH = 4\n\tval MTDATA1_M_ENABLED = 3\n\tval MTDATA1_EXE = 2\n\tval MTDATA1_ST = 1\n\tval MTDATA1_LD = 0\n\tval MHPME_NOEVENT = 0.U\n\tval MHPME_CLK_ACTIVE = 1.U // OOP - out of pipe\n\tval MHPME_ICACHE_HIT = 2.U // OOP\n\tval MHPME_ICACHE_MISS = 3.U // OOP\n\tval MHPME_INST_COMMIT = 4.U\n\tval MHPME_INST_COMMIT_16B = 5.U\n\tval MHPME_INST_COMMIT_32B = 6.U\n\tval MHPME_INST_ALIGNED = 7.U // OOP\n\tval MHPME_INST_DECODED = 8.U // OOP\n\tval MHPME_INST_MUL = 9.U\n\tval MHPME_INST_DIV = 10.U\n\tval MHPME_INST_LOAD = 11.U\n\tval MHPME_INST_STORE = 12.U\n\tval MHPME_INST_MALOAD = 13.U\n\tval MHPME_INST_MASTORE = 14.U\n\tval MHPME_INST_ALU = 15.U\n\tval MHPME_INST_CSRREAD = 16.U\n\tval MHPME_INST_CSRRW = 17.U\n\tval MHPME_INST_CSRWRITE = 18.U\n\tval MHPME_INST_EBREAK = 19.U\n\tval MHPME_INST_ECALL = 20.U\n\tval MHPME_INST_FENCE = 21.U\n\tval MHPME_INST_FENCEI = 22.U\n\tval MHPME_INST_MRET = 23.U\n\tval MHPME_INST_BRANCH = 24.U\n\tval MHPME_BRANCH_MP = 25.U\n\tval MHPME_BRANCH_TAKEN = 26.U\n\tval MHPME_BRANCH_NOTP = 27.U\n\tval MHPME_FETCH_STALL = 28.U // OOP\n\t// val MHPME_ALGNR_STALL = 29.U // OOP\n\tval MHPME_DECODE_STALL = 30.U // OOP\n\tval MHPME_POSTSYNC_STALL = 31.U // OOP\n\tval MHPME_PRESYNC_STALL = 32.U // OOP\n\tval MHPME_LSU_SB_WB_STALL = 34.U // OOP\n\tval MHPME_DMA_DCCM_STALL = 35.U // OOP\n\tval MHPME_DMA_ICCM_STALL = 36.U // OOP\n\tval MHPME_EXC_TAKEN = 37.U\n\tval MHPME_TIMER_INT_TAKEN = 38.U\n\tval MHPME_EXT_INT_TAKEN = 39.U\n\tval MHPME_FLUSH_LOWER = 40.U\n\tval MHPME_BR_ERROR = 41.U\n\tval MHPME_IBUS_TRANS = 42.U // OOP\n\tval MHPME_DBUS_TRANS = 43.U // OOP\n\tval MHPME_DBUS_MA_TRANS = 44.U // OOP\n\tval MHPME_IBUS_ERROR = 45.U // OOP\n\tval MHPME_DBUS_ERROR = 46.U // OOP\n\tval MHPME_IBUS_STALL = 47.U // OOP\n\tval MHPME_DBUS_STALL = 48.U // OOP\n\tval MHPME_INT_DISABLED = 49.U // OOP\n\tval MHPME_INT_STALLED = 50.U // OOP\n\tval MHPME_INST_BITMANIP = 54.U\n\tval MHPME_DBUS_LOAD = 55.U\n\tval MHPME_DBUS_STORE = 56.U\n\t// Counts even during sleep state\n\tval MHPME_SLEEP_CYC = 512.U // OOP\n\tval MHPME_DMA_READ_ALL = 513.U // OOP\n\tval MHPME_DMA_WRITE_ALL = 514.U // OOP\n\tval MHPME_DMA_READ_DCCM = 515.U // OOP\n\tval MHPME_DMA_WRITE_DCCM = 516.U // OOP\n\n\n}\nclass CSR_IO extends Bundle with lib {\n\tval free_l2clk = Input(Clock())\n\tval free_clk = Input(Clock())\n\tval scan_mode = Input(Bool())\n\tval dec_csr_wrdata_r = Input(UInt(32.W))\n\tval dec_csr_wraddr_r = Input(UInt(12.W))\n\tval dec_csr_rdaddr_d = Input(UInt(12.W))\n\tval dec_csr_wen_unq_d = Input(UInt(1.W))\n\tval dec_i0_decode_d = Input(UInt(1.W))\n\tval dec_tlu_ic_diag_pkt = Output(new cache_debug_pkt_t)\n\tval ifu_ic_debug_rd_data_valid = Input(UInt(1.W))\n\tval trigger_pkt_any = Output(Vec(4, new trigger_pkt_t))\n\tval ifu_pmu_bus_trxn = Input(UInt(1.W))\n\tval dma_iccm_stall_any = Input(UInt(1.W))\n\tval dma_dccm_stall_any = Input(UInt(1.W))\n\tval lsu_store_stall_any = Input(UInt(1.W))\n\tval dec_pmu_presync_stall = Input(UInt(1.W))\n\tval dec_pmu_postsync_stall = Input(UInt(1.W))\n\tval dec_pmu_decode_stall = Input(UInt(1.W))\n\tval ifu_pmu_fetch_stall = Input(UInt(1.W))\n\tval dec_tlu_packet_r = Input(new trap_pkt_t)\n\tval exu_pmu_i0_br_ataken = Input(UInt(1.W))\n\tval exu_pmu_i0_br_misp = Input(UInt(1.W))\n\tval dec_pmu_instr_decoded = Input(UInt(1.W))\n\tval ifu_pmu_instr_aligned = Input(UInt(1.W))\n\tval exu_pmu_i0_pc4 = Input(UInt(1.W))\n\tval ifu_pmu_ic_miss = Input(UInt(1.W))\n\tval ifu_pmu_ic_hit = Input(UInt(1.W))\n\tval dec_tlu_int_valid_wb1 = Output(UInt(1.W))\n\tval dec_tlu_i0_exc_valid_wb1 = Output(UInt(1.W))\n\tval dec_tlu_i0_valid_wb1 = Output(UInt(1.W))\n\tval dec_csr_wen_r = Input(UInt(1.W))\n\tval dec_tlu_mtval_wb1 = Output(UInt(32.W))\n\tval dec_tlu_exc_cause_wb1 = Output(UInt(5.W))\n\tval dec_tlu_perfcnt0 = Output(UInt(1.W))\n\tval dec_tlu_perfcnt1 = Output(UInt(1.W))\n\tval dec_tlu_perfcnt2 = Output(UInt(1.W))\n\tval dec_tlu_perfcnt3 = Output(UInt(1.W))\n\tval dec_tlu_dbg_halted = Input(UInt(1.W))\n\tval dma_pmu_dccm_write = Input(UInt(1.W))\n\tval dma_pmu_dccm_read = Input(UInt(1.W))\n\tval dma_pmu_any_write = Input(UInt(1.W))\n\tval dma_pmu_any_read = Input(UInt(1.W))\n\tval lsu_pmu_bus_busy = Input(UInt(1.W))\n\tval dec_tlu_i0_pc_r = Input(UInt(31.W))\n\tval dec_tlu_i0_valid_r = Input(UInt(1.W))\n\tval dec_csr_stall_int_ff = Input(UInt(1.W))\n\tval dec_csr_any_unq_d = Input(UInt(1.W))\n\tval dec_tlu_misc_clk_override = Output(UInt(1.W))\n\tval dec_tlu_picio_clk_override = Output(UInt(1.W))\n\tval dec_tlu_dec_clk_override = Output(UInt(1.W))\n\tval dec_tlu_ifu_clk_override = Output(UInt(1.W))\n\tval dec_tlu_lsu_clk_override = Output(UInt(1.W))\n\tval dec_tlu_bus_clk_override = Output(UInt(1.W))\n\tval dec_tlu_pic_clk_override = Output(UInt(1.W))\n\tval dec_tlu_dccm_clk_override = Output(UInt(1.W))\n\tval dec_tlu_icm_clk_override = Output(UInt(1.W))\n\tval dec_csr_rddata_d = Output(UInt(32.W))\n\tval dec_tlu_pipelining_disable = Output(UInt(1.W))\n\tval dec_tlu_wr_pause_r = Output(UInt(1.W))\n\tval ifu_pmu_bus_busy = Input(UInt(1.W))\n\tval lsu_pmu_bus_error = Input(UInt(1.W))\n\tval ifu_pmu_bus_error = Input(UInt(1.W))\n\tval lsu_pmu_bus_misaligned = Input(UInt(1.W))\n\tval lsu_pmu_bus_trxn = Input(UInt(1.W))\n\tval ifu_ic_debug_rd_data = Input(UInt(71.W))\n\tval dec_tlu_meipt = Output(UInt(4.W))\n\tval pic_pl = Input(UInt(4.W))\n\tval dec_tlu_meicurpl = Output(UInt(4.W))\n\tval dec_tlu_meihap = Output(UInt(30.W))\n\tval pic_claimid = Input(UInt(8.W))\n\tval iccm_dma_sb_error = Input(UInt(1.W))\n\tval lsu_imprecise_error_addr_any = Input(UInt(32.W))\n\tval lsu_imprecise_error_load_any = Input(UInt(1.W))\n\tval lsu_imprecise_error_store_any = Input(UInt(1.W))\n\tval dec_tlu_mrac_ff = Output(UInt(32.W))\n\tval dec_tlu_wb_coalescing_disable = Output(UInt(1.W))\n\tval dec_tlu_bpred_disable = Output(UInt(1.W))\n\tval dec_tlu_sideeffect_posted_disable = Output(UInt(1.W))\n\tval dec_tlu_core_ecc_disable = Output(UInt(1.W))\n\tval dec_tlu_external_ldfwd_disable = Output(UInt(1.W))\n\tval dec_tlu_dma_qos_prty = Output(UInt(3.W))\n\tval dec_tlu_trace_disable = Output(Bool())\n\tval dec_illegal_inst = Input(UInt(32.W))\n\tval lsu_error_pkt_r = Flipped(Valid(new lsu_error_pkt_t))// lsu precise exception/error packet\n\tval mexintpend = Input(UInt(1.W))\n\tval exu_npc_r = Input(UInt(31.W))\n\tval mpc_reset_run_req = Input(UInt(1.W))\n\tval rst_vec = Input(UInt(31.W))\n\tval core_id \t\t\t\t\t\t\t = Input(UInt(28.W))\n\tval dec_timer_rddata_d = Input(UInt(32.W))\n\tval dec_timer_read_d = Input(UInt(1.W))\n\n\n\t//////////////////////////////////////////////////\n\tval dec_csr_wen_r_mod = Output(UInt(1.W))\n\tval rfpc_i0_r = Input(UInt(1.W))\n\tval i0_trigger_hit_r = Input(UInt(1.W))\n\tval fw_halt_req = Output(UInt(1.W))\n\tval mstatus = Output(UInt(2.W))\n\tval exc_or_int_valid_r = Input(UInt(1.W)) // remove this after\n\tval mret_r = Input(UInt(1.W))\n\tval mstatus_mie_ns = Output(UInt(1.W))\n\tval dcsr_single_step_running_f = Input(UInt(1.W))\n\tval dcsr = Output(UInt(16.W))\n\tval mtvec = Output(UInt(31.W))\n\tval mip = Output(UInt(6.W))\n\tval dec_timer_t0_pulse = Input(UInt(1.W))\n\tval dec_timer_t1_pulse = Input(UInt(1.W))\n\tval timer_int_sync = Input(UInt(1.W))\n\tval soft_int_sync = Input(UInt(1.W))\n\tval mie_ns = Output(UInt(6.W))\n\tval csr_wr_clk: Clock = Input(Clock()) // remove after\n\tval ebreak_to_debug_mode_r = Input(UInt(1.W))\n\tval dec_tlu_pmu_fw_halted = Input(UInt(1.W))\n\tval lsu_fir_error = Input(UInt(2.W))\n\tval npc_r = Output(UInt(31.W))\n\tval tlu_flush_lower_r_d1 = Input(UInt(1.W))\n\tval dec_tlu_flush_noredir_r_d1 = Input(UInt(1.W))\n\tval tlu_flush_path_r_d1 = Input(UInt(31.W))\n\tval npc_r_d1 = Output(UInt(31.W))\n\tval reset_delayed = Input(UInt(1.W))\n\tval mepc = Output(UInt(31.W))\n\tval interrupt_valid_r = Input(UInt(1.W))\n\tval i0_exception_valid_r = Input(UInt(1.W)) //delete after\n\tval lsu_exc_valid_r = Input(UInt(1.W))\n\tval mepc_trigger_hit_sel_pc_r = Input(UInt(1.W)) //delete after\n\tval lsu_single_ecc_error_r = Input(UInt(1.W))\n\tval e4e5_int_clk = Input(Clock()) //delete after\n\tval lsu_i0_exc_r = Input(UInt(1.W))\n\tval inst_acc_r = Input(UInt(1.W))\n\tval inst_acc_second_r = Input(UInt(1.W))\n\tval take_nmi = Input(UInt(1.W))\n\tval lsu_error_pkt_addr_r = Input(UInt(32.W))\n\tval exc_cause_r = Input(UInt(5.W))\n\tval i0_valid_wb = Input(UInt(1.W))\n\tval exc_or_int_valid_r_d1 = Input(UInt(1.W))\n\tval interrupt_valid_r_d1 = Input(Bool())\n\tval clk_override = Input(UInt(1.W))\n\tval i0_exception_valid_r_d1 = Input(UInt(1.W))\n\n\tval exc_cause_wb = Input(UInt(5.W))\n\tval nmi_lsu_store_type = Input(UInt(1.W))\n\tval nmi_lsu_load_type = Input(UInt(1.W))\n\tval tlu_i0_commit_cmt = Input(UInt(1.W))\n\tval ebreak_r = Input(UInt(1.W))\n\tval ecall_r = Input(UInt(1.W))\n\tval illegal_r = Input(UInt(1.W))\n\tval mdseac_locked_ns = Output(UInt(1.W))\n\tval mdseac_locked_f = Output(UInt(1.W))\n\tval nmi_int_detected_f = Input(UInt(1.W))\n\tval internal_dbg_halt_mode_f2 = Input(UInt(1.W))\n\tval ext_int_freeze \t\t\t\t\t = Input(UInt(1.W))\n\tval ext_int_freeze_d1 \t\t\t\t = Output(UInt(1.W))\n\tval take_ext_int_start_d1 \t\t\t= Output(UInt(1.W))\n\tval take_ext_int_start_d2 \t\t\t= Output(UInt(1.W))\n\tval take_ext_int_start_d3 \t\t\t= Output(UInt(1.W))\n\tval ic_perr_r = Input(UInt(1.W))\n\tval iccm_sbecc_r = Input(UInt(1.W))\n\n\tval ifu_miss_state_idle_f = Input(UInt(1.W))\n\tval lsu_idle_any_f = Input(UInt(1.W))\n\tval dbg_tlu_halted_f = Input(UInt(1.W))\n\tval dbg_tlu_halted = Input(UInt(1.W))\n\tval debug_halt_req_f \t\t\t = Input(UInt(1.W))\n\tval force_halt \t\t\t\t = Output(UInt(1.W))\n\tval take_ext_int_start\t\t = Input(UInt(1.W))\n\tval trigger_hit_dmode_r_d1 \t = Input(UInt(1.W))\n\tval trigger_hit_r_d1 \t = Input(UInt(1.W))\n\tval dcsr_single_step_done_f \t = Input(UInt(1.W))\n\tval ebreak_to_debug_mode_r_d1 = Input(UInt(1.W))\n\tval debug_halt_req \t\t\t = Input(UInt(1.W))\n\tval allow_dbg_halt_csr_write = Input(UInt(1.W))\n\tval internal_dbg_halt_mode_f = Input(UInt(1.W))\n\tval enter_debug_halt_req = Input(UInt(1.W))\n\tval internal_dbg_halt_mode = Input(UInt(1.W))\n\tval request_debug_mode_done = Input(UInt(1.W))\n\tval request_debug_mode_r = Input(UInt(1.W))\n\tval dpc = Output(UInt(31.W))\n\tval update_hit_bit_r = Input(UInt(4.W))\n\tval take_timer_int = Input(UInt(1.W))\n\tval take_int_timer0_int = Input(UInt(1.W))\n\tval take_int_timer1_int = Input(UInt(1.W))\n\tval take_ext_int = Input(UInt(1.W))\n\tval tlu_flush_lower_r = Input(UInt(1.W))\n\tval dec_tlu_br0_error_r = Input(UInt(1.W))\n\tval dec_tlu_br0_start_error_r = Input(UInt(1.W))\n\tval lsu_pmu_load_external_r = Input(UInt(1.W))\n\tval lsu_pmu_store_external_r = Input(UInt(1.W))\n\tval csr_pkt = Input(new dec_tlu_csr_pkt)\n\tval mtdata1_t\t\t\t\t\t = Output(Vec(4,UInt(10.W)))\n\tval trigger_enabled = Input(UInt(4.W))\n\tval lsu_exc_valid_r_d1 = Output(UInt(1.W))\n}\n\nclass csr_tlu extends Module with lib with CSRs with RequireAsyncReset {\n\tval io = IO(new CSR_IO)\n\n\t////////////////////////////////wires///////////////////////////////\n\tval miccme_ce_req = WireInit(UInt(1.W),0.U)\n\tval mice_ce_req = WireInit(UInt(1.W),0.U)\n\tval mdccme_ce_req = WireInit(UInt(1.W),0.U)\n\tval pc_r_d1 = WireInit(UInt(31.W),0.U)\n\tval mpmc_b_ns = WireInit(UInt(1.W),0.U)\n\tval mpmc_b = WireInit(UInt(1.W),0.U)\n\tval mcycleh = WireInit(UInt(32.W),0.U)\n\tval wr_minstreth_r = WireInit(UInt(1.W),0.U)\n\tval minstretl = WireInit(UInt(32.W),0.U)\n\tval minstreth = WireInit(UInt(32.W),0.U)\n\tval mfdc_ns = WireInit(UInt(16.W),0.U)\n\tval mfdc_int = WireInit(UInt(16.W),0.U)\n\tval mhpme_vec = Wire(Vec(4,UInt(10.W)))\n\tval mtdata2_t\t\t\t\t\t = Wire(Vec(4,UInt(32.W)))\n\tval wr_meicpct_r \t\t\t\t = WireInit(UInt(1.W),0.U)\n\tval force_halt_ctr_f\t\t\t = WireInit(UInt(32.W),0.U)\n\tval mdccmect_inc = WireInit(UInt(27.W),0.U)\n\tval miccmect_inc = WireInit(UInt(27.W),0.U)\n\tval micect_inc = WireInit(UInt(27.W),0.U)\n\tval mdseac_en = WireInit(UInt(1.W),0.U)\n\tval mie = WireInit(UInt(6.W),0.U)\n\tval mcyclel = WireInit(UInt(32.W),0.U)\n\tval mscratch = WireInit(UInt(32.W),0.U)\n\tval mcause = WireInit(UInt(32.W),0.U)\n\tval mscause = WireInit(UInt(4.W),0.U)\n\tval mtval = WireInit(UInt(32.W),0.U)\n\tval meicurpl \t\t\t\t\t = WireInit(UInt(4.W),0.U)\n\tval meipt \t\t\t\t\t = WireInit(UInt(4.W),0.U)\n\tval mfdc = WireInit(UInt(19.W),0.U)\n\tval mtsel = WireInit(UInt(2.W),0.U)\n\tval micect = WireInit(UInt(32.W),0.U)\n\tval miccmect = WireInit(UInt(32.W),0.U)\n\tval mdccmect = WireInit(UInt(32.W),0.U)\n\tval mfdht \t\t\t\t\t = WireInit(UInt(6.W),0.U)\n\tval mfdhs = WireInit(UInt(2.W),0.U)\n\tval mcountinhibit = WireInit(UInt(7.W),0.U)\n\tval mpmc = WireInit(UInt(1.W),0.U)\n\tval dicad1 = WireInit(UInt(32.W),0.U)\n\t/////////////////////////////////////////////////////////////////////////\n\n\tval perfmux_flop = Module(new perf_mux_and_flops)\n\tval perf_csrs = Module(new perf_csr)\n\t//----------------------------------------------------------------------\n\t//\n\t// CSRs\n\t//\n\t//----------------------------------------------------------------------\n\n\t// ----------------------------------------------------------------------\n\t// MSTATUS (RW)\n\t// [12:11] MPP : Prior priv level, always 2'b11, not flopped\n\t// [7] MPIE : Int enable previous [1]\n\t// [3] MIE : Int enable [0]\n\n\t//When executing a MRET instruction, supposing MPP holds the value 3, MIE\n\t//is set to MPIE; the privilege mode is changed to 3; MPIE is set to 1; and MPP is set to 3\n\n\tio.dec_csr_wen_r_mod := io.dec_csr_wen_r & !io.i0_trigger_hit_r & !io.rfpc_i0_r\n\tval wr_mstatus_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MSTATUS)\n\n\t// set this even if we don't go to fwhalt due to debug halt. We committed the inst, so ...\n\tval set_mie_pmu_fw_halt = !mpmc_b_ns & io.fw_halt_req\n\n\tval mstatus_ns = Mux1H(Seq(\n\t\t(!wr_mstatus_r & io.exc_or_int_valid_r).asBool -> Cat(io.mstatus(MSTATUS_MIE),0.U),\n\t\t(wr_mstatus_r & io.exc_or_int_valid_r).asBool -> Cat(io.dec_csr_wrdata_r(3),0.U),\n\t\t(io.mret_r & !io.exc_or_int_valid_r).asBool -> Cat(1.U, io.mstatus(1)),\n\t\t(set_mie_pmu_fw_halt).asBool -> Cat(io.mstatus(1), 1.U),\n\t\t(wr_mstatus_r & !io.exc_or_int_valid_r).asBool -> Cat(io.dec_csr_wrdata_r(7), io.dec_csr_wrdata_r(3)),\n\t\t(!wr_mstatus_r & !io.exc_or_int_valid_r & !io.mret_r & !set_mie_pmu_fw_halt).asBool -> io.mstatus))\n\n\n\n\t// gate MIE if we are single stepping and DCSR[STEPIE] is off\n\tio.mstatus_mie_ns := io.mstatus(MSTATUS_MIE) & (~io.dcsr_single_step_running_f | io.dcsr(DCSR_STEPIE))\n\t\n\n\t// ----------------------------------------------------------------------\n\t// MTVEC (RW)\n\t// [31:2] BASE : Trap vector base address\n\t// [1] - Reserved, not implemented, reads zero\n\t// [0] MODE : 0 = Direct, 1 = Asyncs are vectored to BASE + (4 * CAUSE)\n\n\tval wr_mtvec_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MTVEC)\n\tval mtvec_ns = Cat(io.dec_csr_wrdata_r(31, 2), io.dec_csr_wrdata_r(0))\n\tio.mtvec := rvdffe(mtvec_ns, wr_mtvec_r.asBool, clock, io.scan_mode)\n\n\t// ----------------------------------------------------------------------\n\t// MIP (RW)\n\t//\n\t// [30] MCEIP : (RO) M-Mode Correctable Error interrupt pending\n\t// [29] MITIP0 : (RO) M-Mode Internal Timer0 interrupt pending\n\t// [28] MITIP1 : (RO) M-Mode Internal Timer1 interrupt pending\n\t// [11] MEIP : (RO) M-Mode external interrupt pending\n\t// [7] MTIP : (RO) M-Mode timer interrupt pending\n\t// [3] MSIP : (RO) M-Mode software interrupt pending\n\n\tval ce_int = (mdccme_ce_req | miccme_ce_req | mice_ce_req)\n\n\tval mip_ns = Cat(ce_int, io.dec_timer_t0_pulse, io.dec_timer_t1_pulse, io.mexintpend, io.timer_int_sync, io.soft_int_sync)\n\t\n\n\t// ----------------------------------------------------------------------\n\t// MIE (RW)\n\t// [30] MCEIE : (RO) M-Mode Correctable Error interrupt enable\n\t// [29] MITIE0 : (RO) M-Mode Internal Timer0 interrupt enable\n\t// [28] MITIE1 : (RO) M-Mode Internal Timer1 interrupt enable\n\t// [11] MEIE : (RW) M-Mode external interrupt enable\n\t// [7] MTIE : (RW) M-Mode timer interrupt enable\n\t// [3] MSIE : (RW) M-Mode software interrupt enable\n\n\tval wr_mie_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MIE)\n\tio.mie_ns := Mux(wr_mie_r.asBool, Cat(io.dec_csr_wrdata_r(30, 28), io.dec_csr_wrdata_r(11), io.dec_csr_wrdata_r(7), io.dec_csr_wrdata_r(3)), mie)\n\tmie := withClock(io.csr_wr_clk) {\n\t\tRegNext(io.mie_ns,0.U)\n\t}\n\t// ----------------------------------------------------------------------\n\t// MCYCLEL (RW)\n\t// [31:0] : Lower Cycle count\n\n\tval kill_ebreak_count_r = io.ebreak_to_debug_mode_r & io.dcsr(DCSR_STOPC)\n\n\tval wr_mcyclel_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MCYCLEL)\n\n\tval mcyclel_cout_in = ~(kill_ebreak_count_r | (io.dec_tlu_dbg_halted & io.dcsr(DCSR_STOPC)) | io.dec_tlu_pmu_fw_halted | mcountinhibit(0))\n\tval mcyclel_inc1 = WireInit(UInt(9.W),0.U)\n\tval mcyclel_inc2 = WireInit(UInt(25.W),0.U)\n\tmcyclel_inc1 := mcyclel(7,0) +& Cat(0.U(7.W), 1.U(1.W))\n\tmcyclel_inc2 := mcyclel(31,8) +& Cat(0.U(23.W), mcyclel_inc1(8))\n\tval\tmcyclel_inc = Cat(mcyclel_inc2(23,0),mcyclel_inc1(7,0))\n\tval mcyclel_ns = Mux(wr_mcyclel_r.asBool, io.dec_csr_wrdata_r, mcyclel_inc(31,0))\n\tval mcyclel_cout = mcyclel_inc2(24).asBool\n\tmcyclel := Cat(rvdffe(mcyclel_ns(31,8), (wr_mcyclel_r | (mcyclel_inc1(8) & mcyclel_cout_in.asUInt).asBool), io.free_l2clk, io.scan_mode),rvdffe(mcyclel_ns(7,0),( wr_mcyclel_r | mcyclel_cout_in.asUInt).asBool, io.free_l2clk, io.scan_mode))\n\t// ----------------------------------------------------------------------\n\t// MCYCLEH (RW)\n\t// [63:32] : Higher Cycle count\n\t// Chained with mcyclel. Note: mcyclel overflow due to a mcycleh write gets ignored.\n\n\tval wr_mcycleh_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MCYCLEH)\n\n\tval mcycleh_inc = mcycleh + Cat(0.U(31.W), perfmux_flop.io.mcyclel_cout_f)\n\tval mcycleh_ns = Mux(wr_mcycleh_r.asBool, io.dec_csr_wrdata_r, mcycleh_inc)\n\n\tmcycleh := rvdffe(mcycleh_ns, (wr_mcycleh_r | perfmux_flop.io.mcyclel_cout_f).asBool, io.free_l2clk, io.scan_mode)\n\n\n\t// ----------------------------------------------------------------------\n\t// MINSTRETL (RW)\n\t// [31:0] : Lower Instruction retired count\n\t// From the spec \"Some CSRs, such as the instructions retired counter, instret, may be modified as side effects\n\t// of instruction execution. In these cases, if a CSR access instruction reads a CSR, it reads the\n\t// value prior to the execution of the instruction. If a CSR access instruction writes a CSR, the\n\t// update occurs after the execution of the instruction. In particular, a value written to instret by\n\t// one instruction will be the value read by the following instruction (i.e., the increment of instret\n\t// caused by the first instruction retiring happens before the write of the new value).\"\n\n\n\tval i0_valid_no_ebreak_ecall_r = (io.dec_tlu_i0_valid_r & !(io.ebreak_r | io.ecall_r | io.ebreak_to_debug_mode_r | io.illegal_r | mcountinhibit(2))).asBool()\n\n\tval wr_minstretl_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MINSTRETL)\n\tval minstretl_inc1 = WireInit(UInt(9.W),0.U)\n\tval minstretl_inc2 = WireInit(UInt(25.W),0.U)\n\tminstretl_inc1 := minstretl(7,0) +& Cat(0.U(7.W), 1.U(1.W))\n\tminstretl_inc2 := minstretl(31,8) +& Cat(0.U(23.W), minstretl_inc1(8))\n\tval minstretl_cout = minstretl_inc2(24)\n\tval minstretl_inc = Cat(minstretl_inc2(23,0),minstretl_inc1(7,0))\n\tval minstret_enable = (i0_valid_no_ebreak_ecall_r & io.tlu_i0_commit_cmt) | wr_minstretl_r\n\tval minstretl_cout_ns = minstretl_cout & !wr_minstreth_r & i0_valid_no_ebreak_ecall_r & !io.dec_tlu_dbg_halted\n\n\n\tval minstretl_ns = Mux(wr_minstretl_r.asBool, io.dec_csr_wrdata_r , minstretl_inc(31,0))\n\n\tminstretl := Cat(rvdffe(minstretl_ns(31,8),wr_minstretl_r | (minstretl_inc1(8) & minstret_enable),clock,io.scan_mode),rvdffe(minstretl_ns(7,0),minstret_enable.asBool,clock,io.scan_mode))\n\t\n\tval minstretl_read = minstretl\n\t// ----------------------------------------------------------------------\n\t// MINSTRETH (RW)\n\t// [63:32] : Higher Instret count\n\t// Chained with minstretl. Note: minstretl overflow due to a minstreth write gets ignored.\n\n\twr_minstreth_r := (io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MINSTRETH)).asBool\n\n\tval minstreth_inc = minstreth + Cat(0.U(31.W), perfmux_flop.io.minstretl_cout_f )\n\tval minstreth_ns = Mux(wr_minstreth_r.asBool, io.dec_csr_wrdata_r, minstreth_inc)\n\n\tminstreth := rvdffe(minstreth_ns, (perfmux_flop.io.minstret_enable_f & perfmux_flop.io.minstretl_cout_f ) | wr_minstreth_r, clock, io.scan_mode)\n\n\tval minstreth_read = minstreth_inc\n\n\t// ----------------------------------------------------------------------\n\t// mscratch (RW)\n\t// [31:0] : Scratch register\n\n\tval wr_mscratch_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MSCRATCH)\n\n\tmscratch := rvdffe(io.dec_csr_wrdata_r,wr_mscratch_r.asBool,clock,io.scan_mode)\n\n\n\t// ---------------------------meivt-------------------------------------------\n\t// MEPC (RW)\n\t// [31:1] : Exception PC\n\n\t// NPC\n\n\tval sel_exu_npc_r = !io.dec_tlu_dbg_halted & !io.tlu_flush_lower_r_d1 & io.dec_tlu_i0_valid_r\n\tval sel_flush_npc_r = !io.dec_tlu_dbg_halted & io.tlu_flush_lower_r_d1 & !io.dec_tlu_flush_noredir_r_d1\n\tval sel_hold_npc_r = !sel_exu_npc_r & !sel_flush_npc_r\n\n\tio.npc_r := Mux1H(Seq(\n\t\tsel_exu_npc_r.asBool -> io.exu_npc_r,\n\t\t(!io.mpc_reset_run_req & io.reset_delayed).asBool -> io.rst_vec, // init to reset vector for mpc halt on reset case\n\t\tsel_flush_npc_r.asBool -> io.tlu_flush_path_r_d1,\n\t\tsel_hold_npc_r.asBool -> io.npc_r_d1 ))\n\n\tio.npc_r_d1 := rvdffpcie(io.npc_r,(sel_exu_npc_r | sel_flush_npc_r | io.reset_delayed).asBool,reset.asAsyncReset(),clock,io.scan_mode)\n\t// PC has to be captured for exceptions and interrupts. For MRET, we could execute it and then take an\n\t// interrupt before the next instruction.\n\tval pc0_valid_r = (!io.dec_tlu_dbg_halted & io.dec_tlu_i0_valid_r).asBool\n\n\tval pc_r = Mux1H( Seq(\n\t\tpc0_valid_r -> io.dec_tlu_i0_pc_r,\n\t\t~pc0_valid_r -> pc_r_d1 ))\n\n\tpc_r_d1 := rvdffpcie(pc_r, pc0_valid_r,reset.asAsyncReset(), clock, io.scan_mode)\n\n\tval wr_mepc_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MEPC)\n\n\tval mepc_ns = Mux1H( Seq(\n\t\t(io.i0_exception_valid_r | io.lsu_exc_valid_r | io.mepc_trigger_hit_sel_pc_r).asBool -> pc_r,\n\t\t(io.interrupt_valid_r).asBool -> io.npc_r,\n\t\t(wr_mepc_r & !io.exc_or_int_valid_r).asBool -> io.dec_csr_wrdata_r(31,1),\n\t\t(!wr_mepc_r & !io.exc_or_int_valid_r).asBool -> io.mepc) )\n\n\tio.mepc := rvdffe(mepc_ns,io.i0_exception_valid_r | io.lsu_exc_valid_r | io.mepc_trigger_hit_sel_pc_r | io.interrupt_valid_r | wr_mepc_r,clock, io.scan_mode)//withClock(io.e4e5_int_clk){RegNext(mepc_ns,0.U)}\n\n\n\n\t// ----------------------------------------------------------------------\n\t// MCAUSE (RW)\n\t// [31:0] : Exception Cause\n\n\tval wr_mcause_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MCAUSE)\n\tval mcause_sel_nmi_store = io.exc_or_int_valid_r & io.take_nmi & io.nmi_lsu_store_type\n\tval mcause_sel_nmi_load = io.exc_or_int_valid_r & io.take_nmi & io.nmi_lsu_load_type\n\tval mcause_sel_nmi_ext =io.exc_or_int_valid_r & io.take_nmi & io.take_ext_int_start_d3 & io.lsu_fir_error.orR & !io.nmi_int_detected_f\n\n\t// FIR value decoder\n\t// 0 –no error\n\t// 1 –uncorrectable ecc => f000_1000\n\t// 2 –dccm region access error => f000_1001\n\t// 3 –non dccm region access error => f000_1002\n\tval mcause_fir_error_type = Cat(io.lsu_fir_error.andR, (io.lsu_fir_error(1) & ~io.lsu_fir_error(0)))\n\n\tval mcause_ns = Mux1H(Seq(\n\t\tmcause_sel_nmi_store.asBool -> \"hf000_0000\".U(32.W),\n\t\tmcause_sel_nmi_load.asBool -> \"hf000_0001\".U(32.W),\n\t\tmcause_sel_nmi_ext.asBool -> Cat(\"hf000_100\".U(28.W), 0.U(2.W), mcause_fir_error_type),\n\t\t(io.exc_or_int_valid_r & !io.take_nmi).asBool -> Cat(io.interrupt_valid_r, 0.U(26.W), io.exc_cause_r),\n\t\t(wr_mcause_r & !io.exc_or_int_valid_r).asBool -> io.dec_csr_wrdata_r,\n\t\t(!wr_mcause_r & !io.exc_or_int_valid_r).asBool -> mcause) )\n\n\tmcause := rvdffe(mcause_ns,io.exc_or_int_valid_r | wr_mcause_r,clock,io.scan_mode)//withClock(io.e4e5_int_clk){RegNext(mcause_ns,0.U)}\n\n\n\t// ----------------------------------------------------------------------\n\t// MSCAUSE (RW)\n\t// [2:0] : Secondary exception Cause\n\n\tval wr_mscause_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MSCAUSE)\n\n\tval ifu_mscause = Mux((io.dec_tlu_packet_r.icaf_type === 0.U(2.W)), \"b1001\".U, Cat(0.U(2.W) , io.dec_tlu_packet_r.icaf_type))\n\n\tval mscause_type = Mux1H( Seq(\n\t\tio.lsu_i0_exc_r.asBool -> io.lsu_error_pkt_r.bits.mscause,\n\t\tio.i0_trigger_hit_r.asBool -> \"b0001\".U(4.W),\n\t\tio.ebreak_r.asBool -> \"b0010\".U(4.W),\n\t\tio.inst_acc_r.asBool -> ifu_mscause ))\n\n\n\tval mscause_ns = Mux1H( Seq(\n\t\t(io.exc_or_int_valid_r).asBool -> mscause_type,\n\t\t(wr_mscause_r & !io.exc_or_int_valid_r).asBool -> io.dec_csr_wrdata_r(3,0),\n\t\t(!wr_mscause_r & !io.exc_or_int_valid_r).asBool -> mscause))\n\n\tmscause := withClock(io.e4e5_int_clk){RegNext(mscause_ns,0.U)}\n\n\t// ----------------------------------------------------------------------\n\t// MTVAL (RW)\n\t// [31:0] : Exception address if relevant\n\n\n\tval wr_mtval_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MTVAL)\n\tval mtval_capture_pc_r = io.exc_or_int_valid_r & (io.ebreak_r | (io.inst_acc_r & ~io.inst_acc_second_r) | io.mepc_trigger_hit_sel_pc_r) & ~io.take_nmi\n\tval mtval_capture_pc_plus2_r = io.exc_or_int_valid_r & (io.inst_acc_r & io.inst_acc_second_r) & ~io.take_nmi\n\tval mtval_capture_inst_r = io.exc_or_int_valid_r & io.illegal_r & ~io.take_nmi\n\tval mtval_capture_lsu_r = io.exc_or_int_valid_r & io.lsu_exc_valid_r & ~io.take_nmi\n\tval mtval_clear_r = io.exc_or_int_valid_r & ~mtval_capture_pc_r & ~mtval_capture_inst_r & ~mtval_capture_lsu_r & ~io.mepc_trigger_hit_sel_pc_r\n\n\n\tval mtval_ns = Mux1H(Seq(\n\t\t(mtval_capture_pc_r).asBool -> Cat(pc_r, 0.U(1.W)),\n\t\t(mtval_capture_pc_plus2_r).asBool -> Cat(pc_r + 1.U(31.W), 0.U(1.W)),\n\t\t(mtval_capture_inst_r).asBool -> io.dec_illegal_inst,\n\t\t(mtval_capture_lsu_r).asBool -> io.lsu_error_pkt_addr_r,\n\t\t(wr_mtval_r & ~io.interrupt_valid_r.asUInt).asBool -> io.dec_csr_wrdata_r,\n\t\t(~io.take_nmi & ~wr_mtval_r & ~mtval_capture_pc_r & ~mtval_capture_inst_r & ~mtval_clear_r & ~mtval_capture_lsu_r).asBool -> mtval ))\n\n\tmtval := rvdffe(mtval_ns,io.tlu_flush_lower_r | wr_mtval_r,clock,io.scan_mode)// withClock(io.e4e5_int_clk){RegNext(mtval_ns,0.U)}\n\n\n\t// ----------------------------------------------------------------------\n\t// MCGC (RW) Clock gating control\n\t// [31:10]: Reserved, reads 0x0\n\t// [9] : picio_clk_override\n\t// [8] : misc_clk_override\n\t// [7] : dec_clk_override\n\t// [6] : Unused\n\t// [5] : ifu_clk_override\n\t// [4] : lsu_clk_override\n\t// [3] : bus_clk_override\n\t// [2] : pic_clk_override\n\t// [1] : dccm_clk_override\n\t// [0] : icm_clk_override\n\t//\n\tval mcgc_int = WireInit(UInt(10.W),0.U)\n\tval wr_mcgc_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MCGC)\n\tval mcgc_ns = Mux(wr_mcgc_r, Cat(~io.dec_csr_wrdata_r(9), io.dec_csr_wrdata_r(8,0)), mcgc_int)\n\tmcgc_int := rvdffe(mcgc_ns,wr_mcgc_r.asBool,clock,io.scan_mode)\n\tval mcgc = Cat(~mcgc_int(9), mcgc_int(8,0))\n\tio.dec_tlu_picio_clk_override := mcgc(9)\n\tio.dec_tlu_misc_clk_override := mcgc(8)\n\tio.dec_tlu_dec_clk_override := mcgc(7)\n\tio.dec_tlu_ifu_clk_override := mcgc(5)\n\tio.dec_tlu_lsu_clk_override := mcgc(4)\n\tio.dec_tlu_bus_clk_override := mcgc(3)\n\tio.dec_tlu_pic_clk_override := mcgc(2)\n\tio.dec_tlu_dccm_clk_override := mcgc(1)\n\tio.dec_tlu_icm_clk_override := mcgc(0)\n\n\t// ----------------------------------------------------------------------\n\t// MFDC (RW) Feature Disable Control\n\t// [31:19] : Reserved, reads 0x0\n\t// [18:16] : DMA QoS Prty\n\t// [15:13] : Reserved, reads 0x0\n\t// [12] : Disable trace\n\t// [11] : Disable external load forwarding\n\t// [10] : Disable dual issue\n\t// [9] : Disable pic multiple ints\n\t// [8] : Disable core ecc\n\t// [7] : Disable secondary alu?s\n\t// [6] : Unused, 0x0\n\t// [5] : Disable non-blocking loads/divides\n\t// [4] : Disable fast divide\n\t// [3] : Disable branch prediction and return stack\n\t// [2] : Disable write buffer coalescing\n\t// [1] : Disable load misses that bypass the write buffer\n\t// [0] : Disable pipelining - Enable single instruction execution\n\t//\n\tval wr_mfdc_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MFDC)\n\n\n\n\tmfdc_int := rvdffe(mfdc_ns,wr_mfdc_r.asBool,clock,io.scan_mode)\n\t\n\t// flip poweron value of bit 6 for AXI build\n\tif(BUILD_AXI4){\n\t\t// flip poweron valid of bit 12\n\t\tmfdc_ns := Cat(~io.dec_csr_wrdata_r(18,16),io.dec_csr_wrdata_r(12),io.dec_csr_wrdata_r(11,7), ~io.dec_csr_wrdata_r(6), io.dec_csr_wrdata_r(5,0))\n\t\tmfdc := Cat(~mfdc_int(15,13),0.U(3.W),mfdc_int(12), mfdc_int(11,7), ~mfdc_int(6), mfdc_int(5,0))\n\t}\n\telse {\n\t\t// flip poweron valid of bit 12\n\t\tmfdc_ns := Cat(~io.dec_csr_wrdata_r(18,16),io.dec_csr_wrdata_r(12,0))\n\t\tmfdc := Cat(~mfdc_int(15,13),0.U(3.W), mfdc_int(12,0))\n\t}\n\n\n\n\tio.dec_tlu_dma_qos_prty := mfdc(18,16)\n\tio.dec_tlu_trace_disable := mfdc(12)\n\tio.dec_tlu_external_ldfwd_disable := mfdc(11)\n\tio.dec_tlu_core_ecc_disable := mfdc(8)\n\tio.dec_tlu_sideeffect_posted_disable := mfdc(6)\n\tio.dec_tlu_bpred_disable := mfdc(3)\n\tio.dec_tlu_wb_coalescing_disable := mfdc(2)\n\tio.dec_tlu_pipelining_disable := mfdc(0)\n\n\n\t// ----------------------------------------------------------------------\n\t// MCPC (RW) Pause counter\n\t// [31:0] : Reads 0x0, decs in the wb register in decode_ctl\n\n\n\n\tio.dec_tlu_wr_pause_r := io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MCPC) & ~io.interrupt_valid_r & ~io.take_ext_int_start\n\n\n\t// ----------------------------------------------------------------------\n\t// MRAC (RW)\n\t// [31:0] : Region Access Control Register, 16 regions, {side_effect, cachable} pairs\n\n\tval wr_mrac_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MRAC)\n\n\t// prevent pairs of 0x11, side_effect and cacheable\n\tval mrac_in = Cat(io.dec_csr_wrdata_r(31), io.dec_csr_wrdata_r(30) & ~io.dec_csr_wrdata_r(31),\n\t\tio.dec_csr_wrdata_r(29), io.dec_csr_wrdata_r(28) & ~io.dec_csr_wrdata_r(29),\n\t\tio.dec_csr_wrdata_r(27), io.dec_csr_wrdata_r(26) & ~io.dec_csr_wrdata_r(27),\n\t\tio.dec_csr_wrdata_r(25), io.dec_csr_wrdata_r(24) & ~io.dec_csr_wrdata_r(25),\n\t\tio.dec_csr_wrdata_r(23), io.dec_csr_wrdata_r(22) & ~io.dec_csr_wrdata_r(23),\n\t\tio.dec_csr_wrdata_r(21), io.dec_csr_wrdata_r(20) & ~io.dec_csr_wrdata_r(21),\n\t\tio.dec_csr_wrdata_r(19), io.dec_csr_wrdata_r(18) & ~io.dec_csr_wrdata_r(19),\n\t\tio.dec_csr_wrdata_r(17), io.dec_csr_wrdata_r(16) & ~io.dec_csr_wrdata_r(17),\n\t\tio.dec_csr_wrdata_r(15), io.dec_csr_wrdata_r(14) & ~io.dec_csr_wrdata_r(15),\n\t\tio.dec_csr_wrdata_r(13), io.dec_csr_wrdata_r(12) & ~io.dec_csr_wrdata_r(13),\n\t\tio.dec_csr_wrdata_r(11), io.dec_csr_wrdata_r(10) & ~io.dec_csr_wrdata_r(11),\n\t\tio.dec_csr_wrdata_r(9), io.dec_csr_wrdata_r(8) & ~io.dec_csr_wrdata_r(9),\n\t\tio.dec_csr_wrdata_r(7), io.dec_csr_wrdata_r(6) & ~io.dec_csr_wrdata_r(7),\n\t\tio.dec_csr_wrdata_r(5), io.dec_csr_wrdata_r(4) & ~io.dec_csr_wrdata_r(5),\n\t\tio.dec_csr_wrdata_r(3), io.dec_csr_wrdata_r(2) & ~io.dec_csr_wrdata_r(3),\n\t\tio.dec_csr_wrdata_r(1), io.dec_csr_wrdata_r(0) & ~io.dec_csr_wrdata_r(1))\n\n\n\tval mrac = rvdffe(mrac_in,wr_mrac_r.asBool,clock,io.scan_mode)\n\t// drive to LSU/IFU\n\tio.dec_tlu_mrac_ff := mrac\n\n\n\t// ----------------------------------------------------------------------\n\t// MDEAU (WAR0)\n\t// [31:0] : Dbus Error Address Unlock register\n\t//\n\n\tval wr_mdeau_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MDEAU)\n\n\n\t// ----------------------------------------------------------------------\n\t// MDSEAC (R)\n\t// [31:0] : Dbus Store Error Address Capture register\n\t//\n\n\n\t// only capture error bus if the MDSEAC reg is not locked\n\tio.mdseac_locked_ns := mdseac_en | (io.mdseac_locked_f & ~wr_mdeau_r)\n\n\tmdseac_en := (io.lsu_imprecise_error_store_any | io.lsu_imprecise_error_load_any) & ~io.nmi_int_detected_f & ~io.mdseac_locked_f\n\n\tval mdseac = rvdffe(io.lsu_imprecise_error_addr_any,mdseac_en.asBool,clock,io.scan_mode)\n\n\t// ----------------------------------------------------------------------\n\t// MPMC (R0W1)\n\t// [0] : FW halt\n\t// [1] : Set MSTATUS[MIE] on halt\n\n\n\n\tval wr_mpmc_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r === MPMC)\n\n\t// allow the cycle of the dbg halt flush that contains the wr_mpmc_r to\n\t// set the io.mstatus bit potentially, use delayed version of internal dbg halt.\n\tio.fw_halt_req := wr_mpmc_r & io.dec_csr_wrdata_r(0) & ~io.internal_dbg_halt_mode_f2 & ~io.ext_int_freeze_d1\n\tval fw_halted_ns = WireInit(UInt(1.W),0.U)\n\t// val fw_halted = withClock(io.free_clk){RegNext(fw_halted_ns,0.U)}\n\tfw_halted_ns := (io.fw_halt_req | perfmux_flop.io.fw_halted) & ~set_mie_pmu_fw_halt\n\tmpmc_b_ns := Mux(wr_mpmc_r.asBool, ~io.dec_csr_wrdata_r(1), ~mpmc)\n\n\tmpmc_b := withClock(io.csr_wr_clk){RegNext(mpmc_b_ns,0.U)}\n\n\n\tmpmc := ~mpmc_b\n\n\t// ----------------------------------------------------------------------\n\t// MICECT (I-Cache error counter/threshold)\n\t// [31:27] : Icache parity error threshold\n\t// [26:0] : Icache parity error count\n\n\n\n\tval csr_sat = Mux((io.dec_csr_wrdata_r(31,27) > 26.U(5.W)), 26.U(5.W), io.dec_csr_wrdata_r(31,27))\n\n\tval wr_micect_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r === MICECT)\n\tmicect_inc := micect(26,0) + Cat(0.U(26.W), io.ic_perr_r)\n\tval micect_ns = Mux(wr_micect_r.asBool, Cat(csr_sat, io.dec_csr_wrdata_r(26,0)) , Cat(micect(31,27), micect_inc))\n\n\tmicect := rvdffe(micect_ns,(wr_micect_r | io.ic_perr_r).asBool,clock,io.scan_mode)\n\n\tmice_ce_req := ((\"hffffffff\".U(32.W) << micect(31,27)) & Cat(0.U(5.W), micect(26,0))).orR\n\n\t// ----------------------------------------------------------------------\n\t// MICCMECT (ICCM error counter/threshold)\n\t// [31:27] : ICCM parity error threshold\n\t// [26:0] : ICCM parity error count\n\n\n\n\tval wr_miccmect_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MICCMECT)\n\tmiccmect_inc := miccmect(26,0) + Cat(0.U(26.W), (io.iccm_sbecc_r | io.iccm_dma_sb_error))\n\tval miccmect_ns = Mux(wr_miccmect_r.asBool, Cat(csr_sat, io.dec_csr_wrdata_r(26,0)) , Cat(miccmect(31,27), miccmect_inc))\n\n\tmiccmect := rvdffe(miccmect_ns,(wr_miccmect_r | io.iccm_sbecc_r | io.iccm_dma_sb_error).asBool,io.free_l2clk,io.scan_mode)\n\n\tmiccme_ce_req := ((\"hffffffff\".U(32.W) << miccmect(31,27)) & Cat(0.U(5.W), miccmect(26,0))).orR\n\t//miccme_ce_req := (Bits(\"hffffffff\".U(32.W)) << miccmect(31,27) & Cat(0.U(5.W), miccmect(26,0))).orR\n\t// ----------------------------------------------------------------------\n\t// MDCCMECT (DCCM error counter/threshold)\n\t// [31:27] : DCCM parity error threshold\n\t// [26:0] : DCCM parity error count\n\n\n\n\tval wr_mdccmect_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MDCCMECT)\n\tmdccmect_inc := mdccmect(26,0) + Cat(0.U(26.W), perfmux_flop.io.lsu_single_ecc_error_r_d1 )\n\tval mdccmect_ns = Mux(wr_mdccmect_r.asBool, Cat(csr_sat, io.dec_csr_wrdata_r(26,0)) , Cat(mdccmect(31,27), mdccmect_inc))\n\n\tmdccmect := rvdffe(mdccmect_ns, (wr_mdccmect_r | perfmux_flop.io.lsu_single_ecc_error_r_d1 ).asBool, io.free_l2clk, io.scan_mode)\n\tmdccme_ce_req := ((\"hffffffff\".U(32.W) << mdccmect(31,27)) & Cat(0.U(5.W), mdccmect(26,0))).orR\n\n\n\t// ----------------------------------------------------------------------\n\t// MFDHT (Force Debug Halt Threshold)\n\t// [5:1] : Halt timeout threshold (power of 2)\n\t// [0] : Halt timeout enabled\n\n\n\n\tval wr_mfdht_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MFDHT)\n\n\tval mfdht_ns = Mux(wr_mfdht_r.asBool, io.dec_csr_wrdata_r(5,0) , mfdht)\n\n\tmfdht := withClock(io.csr_wr_clk){RegEnable(mfdht_ns,0.U,wr_mfdht_r)}\n\n\t// ----------------------------------------------------------------------\n\t// MFDHS(RW)\n\t// [1] : LSU operation pending when debug halt threshold reached\n\t// [0] : IFU operation pending when debug halt threshold reached\n\n\n\n\tval wr_mfdhs_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MFDHS)\n\n\tval mfdhs_ns = Mux(wr_mfdhs_r.asBool, io.dec_csr_wrdata_r(1,0) ,\n\t\tMux((io.dbg_tlu_halted & ~io.dbg_tlu_halted_f).asBool, Cat(~io.lsu_idle_any_f, ~io.ifu_miss_state_idle_f) , mfdhs))\n\n\tmfdhs := withClock(io.free_clk){RegEnable(mfdhs_ns,0.U,(wr_mfdhs_r | io.dbg_tlu_halted).asBool)}\n\n\tval force_halt_ctr = Mux(io.debug_halt_req_f.asBool, (force_halt_ctr_f + 1.U(32.W)) ,\n\t\tMux(io.dbg_tlu_halted_f.asBool, 0.U(32.W) , force_halt_ctr_f))\n\n\tforce_halt_ctr_f := rvdffe(force_halt_ctr,mfdht(0),clock,io.scan_mode)//withClock(io.active_clk){RegEnable(force_halt_ctr,0.U,mfdht(0))}\n\n\tio.force_halt := mfdht(0) & (force_halt_ctr_f & (\"hffffffff\".U(32.W) << mfdht(5,1))).orR\n\n\n\t// ----------------------------------------------------------------------\n\t// MEIVT (External Interrupt Vector Table (R/W))\n\t// [31:10]: Base address (R/W)\n\t// [9:0] : Reserved, reads 0x0\n\n\tval wr_meivt_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MEIVT)\n\n\tval meivt = rvdffe(io.dec_csr_wrdata_r(31,10),wr_meivt_r.asBool,clock,io.scan_mode)\n\n\t// ----------------------------------------------------------------------\n\t// MEIHAP (External Interrupt Handler Access Pointer (R))\n\t// [31:10]: Base address (R/W)\n\t// [9:2] : ClaimID (R)\n\t// [1:0] : Reserved, 0x0\n\n\n\n\tval wr_meihap_r = wr_meicpct_r\n\n\tval meihap = rvdffe(io.pic_claimid,wr_meihap_r.asBool,clock,io.scan_mode)\n\tio.dec_tlu_meihap := Cat(meivt, meihap)\n\n\t// ----------------------------------------------------------------------\n\t// MEICURPL (R/W)\n\t// [31:4] : Reserved (read 0x0)\n\t// [3:0] : CURRPRI - Priority level of current interrupt service routine (R/W)\n\n\n\n\tval wr_meicurpl_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MEICURPL)\n\tval meicurpl_ns = Mux(wr_meicurpl_r.asBool, io.dec_csr_wrdata_r(3,0) , meicurpl)\n\n\tmeicurpl := withClock(io.csr_wr_clk){RegNext(meicurpl_ns,0.U)}\n\t// PIC needs this reg\n\tio.dec_tlu_meicurpl := meicurpl\n\n\n\t// ----------------------------------------------------------------------\n\t// MEICIDPL (R/W)\n\t// [31:4] : Reserved (read 0x0)\n\t// [3:0] : External Interrupt Claim ID's Priority Level Register\n\n\n\n\tval wr_meicidpl_r = (io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MEICIDPL)) | io.take_ext_int_start\n\n\tval meicidpl_ns = Mux(wr_meicpct_r.asBool, io.pic_pl,\n\t\tMux(wr_meicidpl_r.asBool, io.dec_csr_wrdata_r(3,0) , perfmux_flop.io.meicidpl))\n\n\t// meicidpl := withClock(io.free_clk){RegNext(meicidpl_ns,0.U)}\n\n\t// ----------------------------------------------------------------------\n\t// MEICPCT (Capture CLAIMID in MEIHAP and PL in MEICIDPL\n\t// [31:1] : Reserved (read 0x0)\n\t// [0] : Capture (W1, Read 0)\n\n\twr_meicpct_r := (io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MEICPCT)) | io.take_ext_int_start\n\n\t// ----------------------------------------------------------------------\n\t// MEIPT (External Interrupt Priority Threshold)\n\t// [31:4] : Reserved (read 0x0)\n\t// [3:0] : PRITHRESH\n\n\n\n\tval wr_meipt_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MEIPT)\n\tval meipt_ns = Mux(wr_meipt_r.asBool, io.dec_csr_wrdata_r(3,0), meipt)\n\n\tmeipt := withClock(io.csr_wr_clk){RegNext(meipt_ns,0.U)}\n\t// to PIC\n\tio.dec_tlu_meipt := meipt\n\n\t// ----------------------------------------------------------------------\n\t// DCSR (R/W) (Only accessible in debug mode)\n\t// [31:28] : xdebugver (hard coded to 0x4) RO\n\t// [27:16] : 0x0, reserved\n\t// [15] : ebreakm\n\t// [14] : 0x0, reserved\n\t// [13] : ebreaks (0x0 for this core)\n\t// [12] : ebreaku (0x0 for this core)\n\t// [11] : stepie\n\t// [10] : stopcount\n\t// [9] : 0x0 //stoptime\n\t// [8:6] : cause (RO)\n\t// [5:4] : 0x0, reserved\n\t// [3] : nmip\n\t// [2] : step\n\t// [1:0] : prv (0x3 for this core)\n\t//\n\n\t// RV has clarified that 'priority 4' in the spec means top priority.\n\t// 4. single step. 3. Debugger request. 2. Ebreak. 1. Trigger.\n\n\t// RV debug spec indicates a cause priority change for trigger hits during single step.\n\n\n\tval trigger_hit_for_dscr_cause_r_d1 = io.trigger_hit_dmode_r_d1 | (io.trigger_hit_r_d1 & io.dcsr_single_step_done_f);\n\n\tval dcsr_cause = Mux1H(Seq(\n\t\t(io.dcsr_single_step_done_f & ~io.ebreak_to_debug_mode_r_d1 & ~trigger_hit_for_dscr_cause_r_d1 & ~io.debug_halt_req).asBool -> \"b100\".U(3.W),\n\t\t(io.debug_halt_req & ~io.ebreak_to_debug_mode_r_d1 & ~trigger_hit_for_dscr_cause_r_d1).asBool -> \"b011\".U(3.W),\n\t\t(io.ebreak_to_debug_mode_r_d1 & ~trigger_hit_for_dscr_cause_r_d1).asBool -> \"b001\".U(3.W),\n\t\t(trigger_hit_for_dscr_cause_r_d1).asBool -> \"b010\".U(3.W) ))\n\n\tval wr_dcsr_r = io.allow_dbg_halt_csr_write & io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === DCSR)\n\n\n\n\t// Multiple halt enter requests can happen before we are halted.\n\t// We have to continue to upgrade based on dcsr_cause priority but we can't downgrade.\n\tval dcsr_cause_upgradeable = io.internal_dbg_halt_mode_f & (io.dcsr(8,6) === \"b011\".U(3.W))\n\tval enter_debug_halt_req_le = io.enter_debug_halt_req & (~io.dbg_tlu_halted | dcsr_cause_upgradeable)\n\n\tval nmi_in_debug_mode = io.nmi_int_detected_f & io.internal_dbg_halt_mode_f\n\tval dcsr_ns = Mux(enter_debug_halt_req_le.asBool, Cat(io.dcsr(15,9), dcsr_cause, io.dcsr(5,2),\"b11\".U(2.W)) ,//prv 0x3 for this core\n\t\tMux(wr_dcsr_r.asBool, Cat(io.dec_csr_wrdata_r(15), 0.U(3.W), io.dec_csr_wrdata_r(11,10), 0.U(1.W), io.dcsr(8,6), 0.U(2.W), nmi_in_debug_mode | io.dcsr(3), io.dec_csr_wrdata_r(2), \"b11\".U(2.W)) , Cat(io.dcsr(15,4), nmi_in_debug_mode, io.dcsr(2),\"b11\".U(2.W))))\n\n\n\tio.dcsr := rvdffe(dcsr_ns, (enter_debug_halt_req_le | wr_dcsr_r | io.internal_dbg_halt_mode | io.take_nmi).asBool, io.free_l2clk, io.scan_mode)\n\n\t// ----------------------------------------------------------------------\n\t// DPC (R/W) (Only accessible in debug mode)\n\t// [31:0] : Debug PC\n\n\n\n\tval wr_dpc_r = io.allow_dbg_halt_csr_write & io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === DPC)\n\tval dpc_capture_npc = io.dbg_tlu_halted & ~io.dbg_tlu_halted_f & ~io.request_debug_mode_done\n\tval dpc_capture_pc = io.request_debug_mode_r\n\n\tval dpc_ns = Mux1H(Seq(\n\t\t(~dpc_capture_pc & ~dpc_capture_npc & wr_dpc_r).asBool -> io.dec_csr_wrdata_r(31,1),\n\t\t(dpc_capture_pc).asBool -> pc_r,\n\t\t(~dpc_capture_pc & dpc_capture_npc).asBool -> io.npc_r ))\n\n\tio.dpc := rvdffe(dpc_ns,(wr_dpc_r | dpc_capture_pc | dpc_capture_npc).asBool,clock,io.scan_mode)\n\n\t// ----------------------------------------------------------------------\n\t// DICAWICS (R/W) (Only accessible in debug mode)\n\t// [31:25] : Reserved\n\t// [24] : Array select, 0 is data, 1 is tag\n\t// [23:22] : Reserved\n\t// [21:20] : Way select\n\t// [19:17] : Reserved\n\t// [16:3] : Index\n\t// [2:0] : Reserved\n\n\n\n\tval dicawics_ns = Cat(io.dec_csr_wrdata_r(24), io.dec_csr_wrdata_r(21,20), io.dec_csr_wrdata_r(16,3))\n\tval wr_dicawics_r = io.allow_dbg_halt_csr_write & io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === DICAWICS)\n\n\tval dicawics = rvdffe(dicawics_ns,wr_dicawics_r.asBool,clock,io.scan_mode)\n\n\t// ----------------------------------------------------------------------\n\t// DICAD0 (R/W) (Only accessible in debug mode)\n\t//\n\t// If io.dicawics[array] is 0\n\t// [31:0] : inst data\n\t//\n\t// If io.dicawics[array] is 1\n\t// [31:16] : Tag\n\t// [15:7] : Reserved\n\t// [6:4] : LRU\n\t// [3:1] : Reserved\n\t// [0] : Valid\n\n\n\tval wr_dicad0_r = io.allow_dbg_halt_csr_write & io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === DICAD0)\n\tval dicad0_ns = Mux(wr_dicad0_r.asBool, io.dec_csr_wrdata_r, io.ifu_ic_debug_rd_data(31,0))\n\n\tval dicad0 = rvdffe(dicad0_ns, (wr_dicad0_r | io.ifu_ic_debug_rd_data_valid).asBool, clock, io.scan_mode)\n\n\t// ----------------------------------------------------------------------\n\t// DICAD0H (R/W) (Only accessible in debug mode)\n\t//\n\t// If io.dicawics[array] is 0\n\t// [63:32] : inst data\n\t//\n\n\n\tval wr_dicad0h_r = io.allow_dbg_halt_csr_write & io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === DICAD0H)\n\n\tval dicad0h_ns = Mux(wr_dicad0h_r.asBool, io.dec_csr_wrdata_r, io.ifu_ic_debug_rd_data(63,32))\n\n\tval dicad0h = rvdffe(dicad0h_ns,(wr_dicad0h_r | io.ifu_ic_debug_rd_data_valid).asBool,clock,io.scan_mode)\n\n\tif (ICACHE_ECC) {\n\t\t// ----------------------------------------------------------------------\n\t\t// DICAD1 (R/W) (Only accessible in debug mode)\n\t\t// [6:0] : ECC\n\n\t\tval dicad1_raw = WireInit(UInt(7.W),0.U)\n\t\tval wr_dicad1_r = io.allow_dbg_halt_csr_write & io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === DICAD1)\n\n\t\tval dicad1_ns = Mux(wr_dicad1_r.asBool, io.dec_csr_wrdata_r(6,0), io.ifu_ic_debug_rd_data(70,64))\n\n\t\tdicad1_raw := rvdffe(dicad1_ns,(wr_dicad1_r | io.ifu_ic_debug_rd_data_valid).asBool,clock,io.scan_mode)//withClock(io.active_clk){RegEnable(dicad1_ns,0.U,(wr_dicad1_r | io.ifu_ic_debug_rd_data_valid).asBool)}\n\t\tdicad1 := Cat(0.U(25.W), dicad1_raw)\n\n\t}\n\telse {\n\t\t// ----------------------------------------------------------------------\n\t\t// DICAD1 (R/W) (Only accessible in debug mode)\n\t\t// [3:0] : Parity\n\n\n\t\tval dicad1_raw = WireInit(UInt(4.W),0.U)\n\t\tval wr_dicad1_r = io.allow_dbg_halt_csr_write & io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === DICAD1)\n\n\t\tval dicad1_ns = Mux(wr_dicad1_r.asBool, io.dec_csr_wrdata_r(3,0), io.ifu_ic_debug_rd_data(67,64))\n\n\t\tdicad1_raw :=withClock(io.free_clk){RegEnable(dicad1_ns,0.U,(wr_dicad1_r | io.ifu_ic_debug_rd_data_valid).asBool)}\n\t\tdicad1 := Cat(0.U(28.W), dicad1_raw)\n\t}\n\n\t// ----------------------------------------------------------------------\n\t// DICAGO (R/W) (Only accessible in debug mode)\n\t// [0] : Go\n\n\tif (ICACHE_ECC) io.dec_tlu_ic_diag_pkt.icache_wrdata := Cat(dicad1(6,0), dicad0h(31,0), dicad0(31,0))\n\telse io.dec_tlu_ic_diag_pkt.icache_wrdata := Cat(0.U(3.W),dicad1(3,0), dicad0h(31,0), dicad0(31,0))\n\n\tio.dec_tlu_ic_diag_pkt.icache_dicawics := dicawics\n\n\tval icache_rd_valid = io.allow_dbg_halt_csr_write & io.dec_csr_any_unq_d & io.dec_i0_decode_d & ~io.dec_csr_wen_unq_d & (io.dec_csr_rdaddr_d(11,0) === DICAGO)\n\tval icache_wr_valid = io.allow_dbg_halt_csr_write & io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === DICAGO)\n\n\n\tio.dec_tlu_ic_diag_pkt.icache_rd_valid := perfmux_flop.io.icache_rd_valid_f\n\tio.dec_tlu_ic_diag_pkt.icache_wr_valid := perfmux_flop.io.icache_wr_valid_f\n\n\t// ----------------------------------------------------------------------\n\t// MTSEL (R/W)\n\t// [1:0] : Trigger select : 00, 01, 10 are data/address triggers. 11 is inst count\n\n\n\n\tval wr_mtsel_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MTSEL)\n\tval mtsel_ns = Mux(wr_mtsel_r.asBool, io.dec_csr_wrdata_r(1,0), mtsel)\n\n\tmtsel := withClock(io.csr_wr_clk){RegNext(mtsel_ns,0.U)}\n\t// ----------------------------------------------------------------------\n\t// MTDATA1 (R/W)\n\t// [31:0] : Trigger Data 1\n\t// for triggers 0, 1, 2 and 3 aka Match Control\n\t// [31:28] : type, hard coded to 0x2\n\t// [27] : dmode\n\t// [26:21] : hard coded to 0x1f\n\t// [20] : hit\n\t// [19] : select (0 - address, 1 - data)\n\t// [18] : timing, always 'before', reads 0x0\n\t// [17:12] : action, bits [17:13] not implemented and reads 0x0\n\t// [11] : chain\n\t// [10:7] : match, bits [10:8] not implemented and reads 0x0\n\t// [6] : M\n\t// [5:3] : not implemented, reads 0x0\n\t// [2] : execute\n\t// [1] : store\n\t// [0] : load\n\t//\n\t// decoder ring\n\t// [27] : => 9\n\t// [20] : => 8\n\t// [19] : => 7\n\t// [12] : => 6\n\t// [11] : => 5\n\t// [7] : => 4\n\t// [6] : => 3\n\t// [2] : => 2\n\t// [1] : => 1\n\t// [0] : => 0\n\n\n\n\t// don't allow setting load-data.\n\tval tdata_load = io.dec_csr_wrdata_r(0) & ~io.dec_csr_wrdata_r(19)\n\t// don't allow setting execute-data.\n\tval tdata_opcode = io.dec_csr_wrdata_r(2) & ~io.dec_csr_wrdata_r(19)\n\t// don't allow clearing DMODE and action=1\n\tval tdata_action = (io.dec_csr_wrdata_r(27) & io.dbg_tlu_halted_f) & io.dec_csr_wrdata_r(12)\n\n\t// Chain bit has conditions: WARL for triggers without chains. Force to zero if dmode is 0 but next trigger dmode is 1.\n\tval tdata_chain = Mux(mtsel(0), 0.U(1.W), // triggers 1 and 3 chain bit is always zero\n\t\tMux(mtsel(1), io.dec_csr_wrdata_r(11) & ~(io.mtdata1_t(3)(MTDATA1_DMODE) & ~io.dec_csr_wrdata_r(27)), // trigger 2\n\t\t\tio.dec_csr_wrdata_r(11) & ~(io.mtdata1_t(1)(MTDATA1_DMODE) & ~io.dec_csr_wrdata_r(27)) )) // trigger 0\n\n\t// Kill mtdata1 write if dmode=1 but prior trigger has dmode=0/chain=1. Only applies to T1 and T3\n\tval tdata_kill_write = Mux(mtsel(1), io.dec_csr_wrdata_r(27) & (~io.mtdata1_t(2)(MTDATA1_DMODE) & io.mtdata1_t(2)(MTDATA1_CHAIN)), // trigger 3\n\t\tio.dec_csr_wrdata_r(27) & (~io.mtdata1_t(0)(MTDATA1_DMODE) & io.mtdata1_t(0)(MTDATA1_CHAIN))) // trigger 1\n\n\tval tdata_wrdata_r = Cat(io.dec_csr_wrdata_r(27) & io.dbg_tlu_halted_f, io.dec_csr_wrdata_r(20,19), tdata_action, tdata_chain, io.dec_csr_wrdata_r(7,6), tdata_opcode, io.dec_csr_wrdata_r(1), tdata_load)\n\n\t// If the DMODE bit is set, tdata1 can only be updated in debug_mode\n\tval wr_mtdata1_t_r = VecInit.tabulate(4)(i => if(i == 0 || i == 2){io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MTDATA1) & (mtsel === i.U(2.W)) & (!io.mtdata1_t(i)(MTDATA1_DMODE) | io.dbg_tlu_halted_f)}else{io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MTDATA1) & (mtsel === i.U(2.W)) & (!io.mtdata1_t(i)(MTDATA1_DMODE) | io.dbg_tlu_halted_f) & !tdata_kill_write })\n\n\tval mtdata1_t_ns = VecInit.tabulate(4)(i => Mux(wr_mtdata1_t_r(i).asBool, tdata_wrdata_r, Cat(io.mtdata1_t(i)(9), io.update_hit_bit_r(i) | io.mtdata1_t(i)(8), io.mtdata1_t(i)(7,0))))\n\n\n\n\tfor(i <- 0 until 4) { io.mtdata1_t(i) := rvdffe(mtdata1_t_ns(i),io.trigger_enabled(i) | wr_mtdata1_t_r(i),clock,io.scan_mode)}//withClock(io.active_clk){RegNext(mtdata1_t_ns(i),0.U)}}\n\n\n\tval mtdata1_tsel_out = Mux1H((0 until 4).map(i => (mtsel === i.U(2.W)) -> Cat(2.U(4.W), io.mtdata1_t(i)(9), \"b011111\".U(6.W), io.mtdata1_t(i)(8,7), 0.U(6.W), io.mtdata1_t(i)(6,5), 0.U(3.W), io.mtdata1_t(i)(4,3), 0.U(3.W), io.mtdata1_t(i)(2,0))))\n\tfor(i <- 0 until 4 ){\n\t\tio.trigger_pkt_any(i).select := io.mtdata1_t(i)(MTDATA1_SEL)\n\t\tio.trigger_pkt_any(i).match_pkt := io.mtdata1_t(i)(MTDATA1_MATCH)\n\t\tio.trigger_pkt_any(i).store := io.mtdata1_t(i)(MTDATA1_ST)\n\t\tio.trigger_pkt_any(i).load := io.mtdata1_t(i)(MTDATA1_LD)\n\t\tio.trigger_pkt_any(i).execute := io.mtdata1_t(i)(MTDATA1_EXE)\n\t\tio.trigger_pkt_any(i).m := io.mtdata1_t(i)(MTDATA1_M_ENABLED)\n\t}\n\n\t// ----------------------------------------------------------------------\n\t// MTDATA2 (R/W)\n\t// [31:0] : Trigger Data 2\n\t// If the DMODE bit is set, tdata2 can only be updated in debug_mode\n\tval wr_mtdata2_t_r = VecInit.tabulate(4)(i => io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MTDATA2) & (mtsel === i.U(2.W)) & (~io.mtdata1_t(i)(MTDATA1_DMODE) | io.dbg_tlu_halted_f))\n\tfor(i <- 0 until 4) { mtdata2_t(i) := rvdffe(io.dec_csr_wrdata_r,wr_mtdata2_t_r(i).asBool,clock,io.scan_mode)}\n\n\n\n\tval mtdata2_tsel_out = Mux1H((0 until 4).map(i =>(mtsel === i.U(2.W)) -> mtdata2_t(i)))\n\tfor(i <- 0 until 4) {io.trigger_pkt_any(i).tdata2 := mtdata2_t(i)}\n\n\n\t//----------------------------------------------------------------------\n\t// Performance Monitor Counters section starts\n\t//----------------------------------------------------------------------\n\n\t// Pack the event selects into a vector for genvar\n\tmhpme_vec(0) := perf_csrs.io.mhpme3\n\tmhpme_vec(1) := perf_csrs.io.mhpme4\n\tmhpme_vec(2) := perf_csrs.io.mhpme5\n\tmhpme_vec(3) := perf_csrs.io.mhpme6\n\n\t// Generate the muxed incs for all counters based on event type\n\n\tperfmux_flop.io.mcountinhibit := mcountinhibit\n\tperfmux_flop.io.mhpme_vec := mhpme_vec\n\tperfmux_flop.io.ifu_pmu_ic_hit := io.ifu_pmu_ic_hit\n\tperfmux_flop.io.ifu_pmu_ic_miss := io.ifu_pmu_ic_miss\n\tperfmux_flop.io.tlu_i0_commit_cmt := io.tlu_i0_commit_cmt\n\tperfmux_flop.io.illegal_r := io.illegal_r\n\tperfmux_flop.io.exu_pmu_i0_pc4 := io.exu_pmu_i0_pc4\n\tperfmux_flop.io.ifu_pmu_instr_aligned := io.ifu_pmu_instr_aligned\n\tperfmux_flop.io.dec_pmu_instr_decoded := io.dec_pmu_instr_decoded\n\tperfmux_flop.io.dec_tlu_packet_r := io.dec_tlu_packet_r\n\tperfmux_flop.io.exu_pmu_i0_br_misp := io.exu_pmu_i0_br_misp\n\tperfmux_flop.io.dec_pmu_decode_stall := io.dec_pmu_decode_stall\n\tperfmux_flop.io.exu_pmu_i0_br_ataken := io.exu_pmu_i0_br_ataken\n\tperfmux_flop.io.ifu_pmu_fetch_stall := io.ifu_pmu_fetch_stall\n\tperfmux_flop.io.dec_pmu_postsync_stall := io.dec_pmu_postsync_stall\n\tperfmux_flop.io.dec_pmu_presync_stall := io.dec_pmu_presync_stall\n\tperfmux_flop.io.lsu_store_stall_any := io.lsu_store_stall_any\n\tperfmux_flop.io.dma_dccm_stall_any := io.dma_dccm_stall_any\n\tperfmux_flop.io.dma_iccm_stall_any := io.dma_iccm_stall_any\n\tperfmux_flop.io.i0_exception_valid_r := io.i0_exception_valid_r\n\tperfmux_flop.io.dec_tlu_pmu_fw_halted := io.dec_tlu_pmu_fw_halted\n\tperfmux_flop.io.dma_pmu_any_read := io.dma_pmu_any_read\n\tperfmux_flop.io.dma_pmu_any_write := io.dma_pmu_any_write\n\tperfmux_flop.io.dma_pmu_dccm_read := io.dma_pmu_dccm_read\n\tperfmux_flop.io.dma_pmu_dccm_write := io.dma_pmu_dccm_write\n\tperfmux_flop.io.lsu_pmu_load_external_r := io.lsu_pmu_load_external_r\n\tperfmux_flop.io.lsu_pmu_store_external_r := io.lsu_pmu_store_external_r\n\tio.mstatus := perfmux_flop.io.mstatus\n\tio.mip := perfmux_flop.io.mip\n\tperfmux_flop.io.mie := mie\n\tperfmux_flop.io.ifu_pmu_bus_trxn := io.ifu_pmu_bus_trxn\n\tperfmux_flop.io.lsu_pmu_bus_trxn := io.lsu_pmu_bus_trxn\n\tperfmux_flop.io.lsu_pmu_bus_misaligned := io.lsu_pmu_bus_misaligned\n\tperfmux_flop.io.ifu_pmu_bus_error := io.ifu_pmu_bus_error\n\tperfmux_flop.io.lsu_pmu_bus_error := io.lsu_pmu_bus_error\n\tperfmux_flop.io.ifu_pmu_bus_busy := io.ifu_pmu_bus_busy\n\tperfmux_flop.io.lsu_pmu_bus_busy := io.lsu_pmu_bus_busy\n\tperfmux_flop.io.i0_trigger_hit_r := io.i0_trigger_hit_r\n\tperfmux_flop.io.lsu_exc_valid_r := io.lsu_exc_valid_r\n\tperfmux_flop.io.take_timer_int := io.take_timer_int\n\tperfmux_flop.io.take_int_timer0_int := io.take_int_timer0_int\n\tperfmux_flop.io.take_int_timer1_int := io.take_int_timer1_int\n\tperfmux_flop.io.take_ext_int := io.take_ext_int\n\tperfmux_flop.io.tlu_flush_lower_r := io.tlu_flush_lower_r\n\tperfmux_flop.io.dec_tlu_br0_error_r := io.dec_tlu_br0_error_r\n\tperfmux_flop.io.rfpc_i0_r := io.rfpc_i0_r\n\tperfmux_flop.io.dec_tlu_br0_start_error_r := io.dec_tlu_br0_start_error_r\n\t//flop outputs\n\tio.mdseac_locked_f := perfmux_flop.io.mdseac_locked_f\n\tio.lsu_exc_valid_r_d1 := perfmux_flop.io.lsu_exc_valid_r_d1\n\tio.take_ext_int_start_d1 := perfmux_flop.io.take_ext_int_start_d1\n\tio.take_ext_int_start_d2 := perfmux_flop.io.take_ext_int_start_d2\n\tio.take_ext_int_start_d3 := perfmux_flop.io.take_ext_int_start_d3\n\tio.ext_int_freeze_d1 := perfmux_flop.io.ext_int_freeze_d1\n\n\n\t//flop inputs\n\tperfmux_flop.io.mdseac_locked_ns := io.mdseac_locked_ns\n\tperfmux_flop.io.lsu_single_ecc_error_r := io.lsu_single_ecc_error_r\n\tperfmux_flop.io.lsu_i0_exc_r := io.lsu_i0_exc_r\n\tperfmux_flop.io.take_ext_int_start := io.take_ext_int_start\n\tperfmux_flop.io.ext_int_freeze := io.ext_int_freeze\n\tperfmux_flop.io.mip_ns := mip_ns\n\tperfmux_flop.io.mcyclel_cout := mcyclel_cout\n\tperfmux_flop.io.wr_mcycleh_r := wr_mcycleh_r\n\tperfmux_flop.io.mcyclel_cout_in := mcyclel_cout_in\n\tperfmux_flop.io.minstret_enable := minstret_enable\n\tperfmux_flop.io.minstretl_cout_ns := minstretl_cout_ns\n\tperfmux_flop.io.fw_halted_ns := fw_halted_ns\n\tperfmux_flop.io.meicidpl_ns := meicidpl_ns\n\tperfmux_flop.io.icache_rd_valid := icache_rd_valid\n\tperfmux_flop.io.icache_wr_valid := icache_wr_valid\n\tperfmux_flop.io.perfcnt_halted := ((io.dec_tlu_dbg_halted & io.dcsr(DCSR_STOPC)) | io.dec_tlu_pmu_fw_halted)\n\tperfmux_flop.io.mstatus_ns := mstatus_ns\n\tperfmux_flop.io.scan_mode := io.scan_mode\n\tperfmux_flop.io.free_l2clk := io.free_l2clk\n\t////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\t//Inputs\n\tperf_csrs.io.free_l2clk := io.free_l2clk\n\tperf_csrs.io.scan_mode := io.scan_mode\n\tperf_csrs.io.dec_tlu_dbg_halted := io.dec_tlu_dbg_halted\n\tperf_csrs.io.dcsr := io.dcsr\n\tperf_csrs.io.dec_tlu_pmu_fw_halted := io.dec_tlu_pmu_fw_halted\n\tperf_csrs.io.mhpme_vec := mhpme_vec\n\tperf_csrs.io.dec_csr_wen_r_mod := io.dec_csr_wen_r_mod\n\tperf_csrs.io.dec_csr_wraddr_r := io.dec_csr_wraddr_r\n\tperf_csrs.io.dec_csr_wrdata_r := io.dec_csr_wrdata_r\n\tperf_csrs.io.mhpmc_inc_r := perfmux_flop.io.mhpmc_inc_r\n\tperf_csrs.io.mhpmc_inc_r_d1 := perfmux_flop.io.mhpmc_inc_r_d1\n\tperf_csrs.io.perfcnt_halted_d1 := perfmux_flop.io.perfcnt_halted_d1\n\t//Outputs\n\tio.dec_tlu_perfcnt0 := perf_csrs.io.dec_tlu_perfcnt0\n\tio.dec_tlu_perfcnt1 := perf_csrs.io.dec_tlu_perfcnt1\n\tio.dec_tlu_perfcnt2 := perf_csrs.io.dec_tlu_perfcnt2\n\tio.dec_tlu_perfcnt3 := perf_csrs.io.dec_tlu_perfcnt3\n\t//----------------------------------------------------------------------\n\t// Performance Monitor Counters section ends\n\t//----------------------------------------------------------------------\n\t// ----------------------------------------------------------------------\n\n\t// MCOUNTINHIBIT(RW)\n\t// [31:7] : Reserved, read 0x0\n\t// [6] : HPM6 disable\n\t// [5] : HPM5 disable\n\t// [4] : HPM4 disable\n\t// [3] : HPM3 disable\n\t// [2] : MINSTRET disable\n\t// [1] : reserved, read 0x0\n\t// [0] : MCYCLE disable\n\n\tval wr_mcountinhibit_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MCOUNTINHIBIT)\n\n\tval temp_ncount0 = WireInit(UInt(1.W),mcountinhibit(0))\n\tval temp_ncount1 = WireInit(UInt(1.W),mcountinhibit(1))\n\tval temp_ncount6_2 = WireInit(UInt(5.W),mcountinhibit(6,2))\n\ttemp_ncount6_2 := withClock(io.csr_wr_clk){RegEnable(io.dec_csr_wrdata_r(6,2),0.U,wr_mcountinhibit_r.asBool)}\n\n\ttemp_ncount0 := withClock(io.csr_wr_clk){RegEnable(io.dec_csr_wrdata_r(0),0.U,wr_mcountinhibit_r.asBool)}\n\tmcountinhibit := Cat(temp_ncount6_2, 0.U(1.W),temp_ncount0)\n\t//--------------------------------------------------------------------------------\n\t// trace\n\t//--------------------------------------------------------------------------------\n\n\tio.dec_tlu_i0_valid_wb1 := !io.dec_tlu_trace_disable & io.i0_valid_wb\n\tio.dec_tlu_i0_exc_valid_wb1 := !io.dec_tlu_trace_disable & (io.i0_exception_valid_r_d1 | perfmux_flop.io.lsu_i0_exc_r_d1 | (io.trigger_hit_r_d1 & !io.trigger_hit_dmode_r_d1))\n\tval dec_tlu_exc_cause_wb1_raw = Fill(5,!io.dec_tlu_trace_disable) & io.exc_cause_wb\n\tval dec_tlu_int_valid_wb1_raw = !io.dec_tlu_trace_disable & io.interrupt_valid_r_d1\n\n\t// skid buffer for ints, reduces trace port count by 1\n\tval dec_tlu_exc_cause_wb2 = rvdffie(dec_tlu_exc_cause_wb1_raw,clock,reset.asAsyncReset(),io.scan_mode)\n\tval dec_tlu_int_valid_wb2 = rvdffie(dec_tlu_int_valid_wb1_raw,clock,reset.asAsyncReset(),io.scan_mode)\n\t//skid for ints\n\tio.dec_tlu_exc_cause_wb1 := Mux(dec_tlu_int_valid_wb2, dec_tlu_exc_cause_wb2, dec_tlu_exc_cause_wb1_raw)\n\tio.dec_tlu_int_valid_wb1 := dec_tlu_int_valid_wb2\n\tio.dec_tlu_mtval_wb1 := mtval\n\n\t// end trace\n\t//--------------------------------------------------------------------------------\n\t// CSR read mux\n\t//\tio.dec_csr_rddata_d:=0.U\n\tio.dec_csr_rddata_d:=Mux1H(Seq(\n\t\tio.csr_pkt.csr_misa.asBool -> 0x40001104.U(32.W),\n\t\tio.csr_pkt.csr_mvendorid.asBool -> 0x00000045.U(32.W),\n\t\tio.csr_pkt.csr_marchid.asBool -> 0x00000010.U(32.W),\n\t\tio.csr_pkt.csr_mimpid.asBool -> 0x3.U(32.W),\n\t\tio.csr_pkt.csr_mhartid.asBool -> Cat(io.core_id,0.U(4.W)),\n\t\tio.csr_pkt.csr_mstatus.asBool -> Cat(0.U(19.W), 3.U(2.W), 0.U(3.W), io.mstatus(1), 0.U(3.W), io.mstatus(0), 0.U(3.W)),\n\t\tio.csr_pkt.csr_mtvec.asBool -> Cat(io.mtvec(30,1), 0.U(1.W), io.mtvec(0)),\n\t\tio.csr_pkt.csr_mip.asBool -> Cat(0.U(1.W), io.mip(5,3), 0.U(16.W), io.mip(2), 0.U(3.W), io.mip(1), 0.U(3.W), io.mip(0), 0.U(3.W)),\n\t\tio.csr_pkt.csr_mie.asBool -> Cat(0.U(1.W), mie(5,3), 0.U(16.W), mie(2), 0.U(3.W), mie(1), 0.U(3.W), mie(0), 0.U(3.W)),\n\t\tio.csr_pkt.csr_mcyclel.asBool -> mcyclel(31,0),\n\t\tio.csr_pkt.csr_mcycleh.asBool -> mcycleh_inc(31,0),\n\t\tio.csr_pkt.csr_minstretl.asBool -> minstretl_read(31,0),\n\t\tio.csr_pkt.csr_minstreth.asBool -> minstreth_read(31,0),\n\t\tio.csr_pkt.csr_mscratch.asBool -> mscratch(31,0),\n\t\tio.csr_pkt.csr_mepc.asBool -> Cat(io.mepc,0.U(1.W)),\n\t\tio.csr_pkt.csr_mcause.asBool -> mcause(31,0),\n\t\tio.csr_pkt.csr_mscause.asBool -> Cat(0.U(28.W), mscause(3,0)),\n\t\tio.csr_pkt.csr_mtval.asBool -> mtval(31,0),\n\t\tio.csr_pkt.csr_mrac.asBool -> mrac(31,0),\n\t\tio.csr_pkt.csr_mdseac.asBool -> mdseac(31,0),\n\t\tio.csr_pkt.csr_meivt.asBool -> Cat(meivt, 0.U(10.W)),\n\t\tio.csr_pkt.csr_meihap.asBool -> Cat(meivt, meihap, 0.U(2.W)),\n\t\tio.csr_pkt.csr_meicurpl.asBool -> Cat(0.U(28.W), meicurpl(3,0)),\n\t\tio.csr_pkt.csr_meicidpl.asBool -> Cat(0.U(28.W), perfmux_flop.io.meicidpl(3,0)),\n\t\tio.csr_pkt.csr_meipt.asBool -> Cat(0.U(28.W), meipt(3,0)),\n\t\tio.csr_pkt.csr_mcgc.asBool -> Cat(0.U(22.W), mcgc(9,0)),\n\t\tio.csr_pkt.csr_mfdc.asBool -> Cat(0.U(13.W), mfdc(18,0)),\n\t\tio.csr_pkt.csr_dcsr.asBool -> Cat(0x4000.U(16.W), io.dcsr(15,2), 3.U(2.W)),\n\t\tio.csr_pkt.csr_dpc.asBool -> Cat(io.dpc, 0.U(1.W)),\n\t\tio.csr_pkt.csr_dicad0.asBool -> dicad0(31,0),\n\t\tio.csr_pkt.csr_dicad0h.asBool -> dicad0h(31,0),\n\t\tio.csr_pkt.csr_dicad1.asBool -> dicad1(31,0),\n\t\tio.csr_pkt.csr_dicawics.asBool -> Cat(0.U(7.W), dicawics(16), 0.U(2.W), dicawics(15,14), 0.U(3.W), dicawics(13,0), 0.U(3.W)),\n\t\tio.csr_pkt.csr_mtsel.asBool -> Cat(0.U(30.W), mtsel(1,0)),\n\t\tio.csr_pkt.csr_mtdata1.asBool -> mtdata1_tsel_out(31,0),\n\t\tio.csr_pkt.csr_mtdata2.asBool -> mtdata2_tsel_out(31,0),\n\t\tio.csr_pkt.csr_micect.asBool -> micect(31,0),\n\t\tio.csr_pkt.csr_miccmect.asBool -> miccmect(31,0),\n\t\tio.csr_pkt.csr_mdccmect.asBool -> mdccmect(31,0),\n\t\tio.csr_pkt.csr_mhpmc3.asBool -> perf_csrs.io.mhpmc3(31,0),\n\t\tio.csr_pkt.csr_mhpmc4.asBool -> perf_csrs.io.mhpmc4(31,0),\n\t\tio.csr_pkt.csr_mhpmc5.asBool -> perf_csrs.io.mhpmc5(31,0),\n\t\tio.csr_pkt.csr_mhpmc6.asBool -> perf_csrs.io.mhpmc6(31,0),\n\t\tio.csr_pkt.csr_mhpmc3h.asBool -> perf_csrs.io.mhpmc3h(31,0),\n\t\tio.csr_pkt.csr_mhpmc4h.asBool -> perf_csrs.io.mhpmc4h(31,0),\n\t\tio.csr_pkt.csr_mhpmc5h.asBool -> perf_csrs.io.mhpmc5h(31,0),\n\t\tio.csr_pkt.csr_mhpmc6h.asBool -> perf_csrs.io.mhpmc6h(31,0),\n\t\tio.csr_pkt.csr_mfdht.asBool -> Cat(0.U(26.W), mfdht(5,0)),\n\t\tio.csr_pkt.csr_mfdhs.asBool -> Cat(0.U(30.W), mfdhs(1,0)),\n\t\tio.csr_pkt.csr_mhpme3.asBool -> Cat(0.U(22.W), perf_csrs.io.mhpme3(9,0)),\n\t\tio.csr_pkt.csr_mhpme4.asBool -> Cat(0.U(22.W), perf_csrs.io.mhpme4(9,0)),\n\t\tio.csr_pkt.csr_mhpme5.asBool -> Cat(0.U(22.W),perf_csrs.io.mhpme5(9,0)),\n\t\tio.csr_pkt.csr_mhpme6.asBool -> Cat(0.U(22.W),perf_csrs.io.mhpme6(9,0)),\n\t\tio.csr_pkt.csr_mcountinhibit.asBool -> Cat(0.U(25.W), mcountinhibit(6,0)),\n\t\tio.csr_pkt.csr_mpmc.asBool -> Cat(0.U(30.W), mpmc, 0.U(1.W)),\n\t\tio.dec_timer_read_d.asBool -> io.dec_timer_rddata_d(31,0)\n\t))\n}\n\nclass perf_csr extends Module with CSRs with lib with RequireAsyncReset{\n\tval io = IO(new Bundle{\n\t\tval free_l2clk = Input(Clock())\n\t\tval scan_mode = Input(Bool())\n\t\tval dec_tlu_dbg_halted = Input(UInt(1.W))\n\t\tval dcsr = Input(UInt(16.W))\n\t\tval dec_tlu_pmu_fw_halted = Input(UInt(1.W))\n\t\tval mhpme_vec = Input(Vec(4,UInt(10.W)))\n\t\tval dec_csr_wen_r_mod = Input(UInt(1.W))\n\t\tval dec_csr_wraddr_r\t\t = Input(UInt(12.W))\n\t\tval dec_csr_wrdata_r\t\t = Input(UInt(32.W))\n\t\tval mhpmc_inc_r = Input(Vec(4,UInt(1.W)))\n\t\tval mhpmc_inc_r_d1 = Input(Vec(4,UInt(1.W)))\n\t\tval perfcnt_halted_d1 = Input(Bool())\n\n\n\t\tval mhpmc3h = Output(UInt(32.W))\n\t\tval mhpmc3 = Output(UInt(32.W))\n\t\tval mhpmc4h = Output(UInt(32.W))\n\t\tval mhpmc4 = Output(UInt(32.W))\n\t\tval mhpmc5h = Output(UInt(32.W))\n\t\tval mhpmc5 = Output(UInt(32.W))\n\t\tval mhpmc6h = Output(UInt(32.W))\n\t\tval mhpmc6 = Output(UInt(32.W))\n\t\tval mhpme3 = Output(UInt(10.W))\n\t\tval mhpme4 = Output(UInt(10.W))\n\t\tval mhpme5 = Output(UInt(10.W))\n\t\tval mhpme6 = Output(UInt(10.W))\n\t\tval dec_tlu_perfcnt0 = Output(UInt(1.W))\n\t\tval dec_tlu_perfcnt1 = Output(UInt(1.W))\n\t\tval dec_tlu_perfcnt2 = Output(UInt(1.W))\n\t\tval dec_tlu_perfcnt3 = Output(UInt(1.W))\n\t})\n\tval perfcnt_halted = ((io.dec_tlu_dbg_halted & io.dcsr(DCSR_STOPC)) | io.dec_tlu_pmu_fw_halted)\n\tval perfcnt_during_sleep = (Fill(4,!(io.dec_tlu_dbg_halted & io.dcsr(DCSR_STOPC)))) & Cat(io.mhpme_vec(3)(9),io.mhpme_vec(2)(9),io.mhpme_vec(1)(9),io.mhpme_vec(0)(9))\n\n\n\tio.dec_tlu_perfcnt0 := io.mhpmc_inc_r_d1(0) & !(io.perfcnt_halted_d1 & !perfcnt_during_sleep(0))\n\tio.dec_tlu_perfcnt1 := io.mhpmc_inc_r_d1(1) & !(io.perfcnt_halted_d1 & !perfcnt_during_sleep(1))\n\tio.dec_tlu_perfcnt2 := io.mhpmc_inc_r_d1(2) & !(io.perfcnt_halted_d1 & !perfcnt_during_sleep(2))\n\tio.dec_tlu_perfcnt3 := io.mhpmc_inc_r_d1(3) & !(io.perfcnt_halted_d1 & !perfcnt_during_sleep(3))\n\n\t// ----------------------------------------------------------------------\n\t// MHPMC3H(RW), MHPMC3(RW)\n\t// [63:32][31:0] : Hardware Performance Monitor Counter 3\n\n\tval mhpmc3_wr_en0 = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MHPMC3)\n\tval mhpmc3_wr_en1 = (~perfcnt_halted | perfcnt_during_sleep(0)) & ((io.mhpmc_inc_r(0)).orR)\n\tval mhpmc3_wr_en = mhpmc3_wr_en0 | mhpmc3_wr_en1\n\n\n\tval mhpmc3_incr = Cat(io.mhpmc3h(31,0),io.mhpmc3(31,0)) + Cat(0.U(63.W),1.U(1.W))\n\tval mhpmc3_ns = Mux(mhpmc3_wr_en0.asBool, io.dec_csr_wrdata_r, mhpmc3_incr(31,0))\n\n\tio.mhpmc3 := rvdffe(mhpmc3_ns,mhpmc3_wr_en.asBool,io.free_l2clk,io.scan_mode)\n\n\tval mhpmc3h_wr_en0 = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MHPMC3H)\n\tval mhpmc3h_wr_en = mhpmc3h_wr_en0 | mhpmc3_wr_en1\n\tval mhpmc3h_ns = Mux(mhpmc3h_wr_en0.asBool, io.dec_csr_wrdata_r, mhpmc3_incr(63,32))\n\n\tio.mhpmc3h := rvdffe(mhpmc3h_ns, mhpmc3h_wr_en.asBool, io.free_l2clk, io.scan_mode)\n\n\n\t// ----------------------------------------------------------------------\n\t// MHPMC4H(RW), MHPMC4(RW)\n\t// [63:32][31:0] : Hardware Performance Monitor Counter 4\n\n\tval mhpmc4_wr_en0 = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MHPMC4)\n\tval mhpmc4_wr_en1 = (~perfcnt_halted | perfcnt_during_sleep(1)) & ((io.mhpmc_inc_r(1)).orR)\n\tval mhpmc4_wr_en = mhpmc4_wr_en0 | mhpmc4_wr_en1\n\n\n\n\tval mhpmc4_incr = Cat(io.mhpmc4h(31,0),io.mhpmc4(31,0)) + Cat(0.U(63.W),1.U(1.W))\n\tval mhpmc4_ns = Mux(mhpmc4_wr_en0.asBool, io.dec_csr_wrdata_r(31,0), mhpmc4_incr(31,0))\n\tio.mhpmc4 := rvdffe(mhpmc4_ns, mhpmc4_wr_en.asBool, io.free_l2clk, io.scan_mode)\n\n\tval mhpmc4h_wr_en0 = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MHPMC4H)\n\tval mhpmc4h_wr_en = mhpmc4h_wr_en0 | mhpmc4_wr_en1\n\tval mhpmc4h_ns = Mux(mhpmc4h_wr_en0.asBool, io.dec_csr_wrdata_r, mhpmc4_incr(63,32))\n\tio.mhpmc4h := rvdffe(mhpmc4h_ns, mhpmc4h_wr_en.asBool, io.free_l2clk, io.scan_mode)\n\n\t// ----------------------------------------------------------------------\n\t// MHPMC5H(RW), MHPMC5(RW)\n\t// [63:32][31:0] : Hardware Performance Monitor Counter 5\n\n\tval mhpmc5_wr_en0 = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MHPMC5)\n\tval mhpmc5_wr_en1 = (~perfcnt_halted | perfcnt_during_sleep(2)) & ((io.mhpmc_inc_r(2)).orR)\n\tval mhpmc5_wr_en = mhpmc5_wr_en0 | mhpmc5_wr_en1\n\n\tval mhpmc5_incr = Cat(io.mhpmc5h(31,0),io.mhpmc5(31,0)) + Cat(0.U(63.W),1.U(1.W))\n\tval mhpmc5_ns = Mux(mhpmc5_wr_en0.asBool, io.dec_csr_wrdata_r, mhpmc5_incr(31,0))\n\n\tio.mhpmc5 := rvdffe(mhpmc5_ns, mhpmc5_wr_en.asBool, io.free_l2clk, io.scan_mode)\n\n\tval mhpmc5h_wr_en0 = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MHPMC5H)\n\tval mhpmc5h_wr_en = mhpmc5h_wr_en0 | mhpmc5_wr_en1\n\tval mhpmc5h_ns = Mux(mhpmc5h_wr_en0.asBool, io.dec_csr_wrdata_r, mhpmc5_incr(63,32))\n\n\tio.mhpmc5h := rvdffe(mhpmc5h_ns, mhpmc5h_wr_en.asBool, io.free_l2clk, io.scan_mode)\n\n\n\t// ----------------------------------------------------------------------\n\t// MHPMC6H(RW), MHPMC6(RW)\n\t// [63:32][31:0] : Hardware Performance Monitor Counter 6\n\n\tval mhpmc6_wr_en0 = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MHPMC6)\n\tval mhpmc6_wr_en1 = (~perfcnt_halted | perfcnt_during_sleep(3)) & ((io.mhpmc_inc_r(3)).orR)\n\tval mhpmc6_wr_en = mhpmc6_wr_en0 | mhpmc6_wr_en1\n\n\tval mhpmc6_incr = Cat(io.mhpmc6h(31,0),io.mhpmc6(31,0)) + Cat(0.U(63.W),1.U(1.W))\n\tval mhpmc6_ns = Mux(mhpmc6_wr_en0.asBool, io.dec_csr_wrdata_r, mhpmc6_incr(31,0))\n\n\n\tio.mhpmc6 := rvdffe(mhpmc6_ns, mhpmc6_wr_en.asBool, io.free_l2clk, io.scan_mode)\n\n\tval mhpmc6h_wr_en0 = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MHPMC6H)\n\tval mhpmc6h_wr_en = mhpmc6h_wr_en0 | mhpmc6_wr_en1\n\tval mhpmc6h_ns = Mux(mhpmc6h_wr_en0.asBool, io.dec_csr_wrdata_r, mhpmc6_incr(63,32))\n\n\tio.mhpmc6h := rvdffe(mhpmc6h_ns, mhpmc6h_wr_en.asBool, io.free_l2clk, io.scan_mode)\n\t// ----------------------------------------------------------------------\n\t// MHPME3(RW)\n\t// [9:0] : Hardware Performance Monitor Event 3\n\n\t// we only have events 0-56 with holes, 512-516, HPME* are WARL so zero otherwise.\n\tval zero_event_r = ((io.dec_csr_wrdata_r(9,0) > 516.U(10.W)) | (io.dec_csr_wrdata_r(31,10).orR) |\n\t\t((io.dec_csr_wrdata_r(9,0) < 512.U(10.W)) & (io.dec_csr_wrdata_r(9,0) > 56.U(10.W))) |\n\t\t((io.dec_csr_wrdata_r(9,0) < 54.U(10.W)) & (io.dec_csr_wrdata_r(9,0) > 50.U(10.W))) |\n\t\t(io.dec_csr_wrdata_r(9,0) === 29.U(10.W)) | (io.dec_csr_wrdata_r(9,0) === 33.U(10.W)))\n\n\tval event_r = Mux(zero_event_r, 0.U(10.W), io.dec_csr_wrdata_r(9,0))\n\tval wr_mhpme3_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MHPME3)\n\n\tio.mhpme3 := rvdffe(event_r,wr_mhpme3_r,clock,io.scan_mode)//withClock(io.active_clk){RegEnable(event_r,0.U,wr_mhpme3_r.asBool)}\n\t// ----------------------------------------------------------------------\n\t// MHPME4(RW)\n\t// [9:0] : Hardware Performance Monitor Event 4\n\n\tval wr_mhpme4_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MHPME4)\n\tio.mhpme4 := rvdffe(event_r,wr_mhpme4_r,clock,io.scan_mode)//withClock(io.active_clk){RegEnable(event_saturate_r,0.U,wr_mhpme4_r.asBool)}\n\n\t// ----------------------------------------------------------------------\n\t// MHPME5(RW)\n\t// [9:0] : Hardware Performance Monitor Event 5\n\n\tval wr_mhpme5_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MHPME5)\n\tio.mhpme5 := rvdffe(event_r,wr_mhpme5_r,clock,io.scan_mode)//withClock(io.active_clk){RegEnable(event_saturate_r,0.U,wr_mhpme5_r.asBool)}\n\n\t// ----------------------------------------------------------------------\n\t// MHPME6(RW)\n\t// [9:0] : Hardware Performance Monitor Event 6\n\n\tval wr_mhpme6_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r(11,0) === MHPME6)\n\tio.mhpme6 := rvdffe(event_r,wr_mhpme6_r,clock,io.scan_mode)//withClock(io.active_clk){RegEnable(event_saturate_r,0.U,wr_mhpme6_r.asBool)}\n}\nclass perf_mux_and_flops extends Module with CSRs with lib with RequireAsyncReset{\n\tval io = IO(new Bundle{\n\t\tval mhpmc_inc_r = Output(Vec(4,UInt(1.W)))\n\t\tval mcountinhibit = Input(UInt(7.W))\n\t\tval mhpme_vec =Input(Vec(4,UInt(10.W)))\n\t\tval ifu_pmu_ic_hit = Input(UInt(1.W))\n\t\tval ifu_pmu_ic_miss = Input(UInt(1.W))\n\t\tval tlu_i0_commit_cmt = Input(UInt(1.W))\n\t\tval illegal_r = Input(UInt(1.W))\n\t\tval exu_pmu_i0_pc4 = Input(UInt(1.W))\n\t\tval ifu_pmu_instr_aligned = Input(UInt(1.W))\n\t\tval dec_pmu_instr_decoded = Input(UInt(1.W))\n\t\tval dec_tlu_packet_r = Input(new trap_pkt_t)\n\t\tval exu_pmu_i0_br_misp = Input(UInt(1.W))\n\t\tval dec_pmu_decode_stall = Input(UInt(1.W))\n\t\tval exu_pmu_i0_br_ataken = Input(UInt(1.W))\n\t\tval ifu_pmu_fetch_stall = Input(UInt(1.W))\n\t\tval dec_pmu_postsync_stall = Input(UInt(1.W))\n\t\tval dec_pmu_presync_stall = Input(UInt(1.W))\n\t\tval lsu_store_stall_any = Input(UInt(1.W))\n\t\tval dma_dccm_stall_any = Input(UInt(1.W))\n\t\tval dma_iccm_stall_any = Input(UInt(1.W))\n\t\tval i0_exception_valid_r = Input(UInt(1.W))\n\t\tval dec_tlu_pmu_fw_halted = Input(UInt(1.W))\n\t\tval dma_pmu_any_read = Input(UInt(1.W))\n\t\tval dma_pmu_any_write = Input(UInt(1.W))\n\t\tval dma_pmu_dccm_read = Input(UInt(1.W))\n\t\tval dma_pmu_dccm_write = Input(UInt(1.W))\n\t\tval lsu_pmu_load_external_r = Input(UInt(1.W))\n\t\tval lsu_pmu_store_external_r = Input(UInt(1.W))\n\t\tval mstatus = Output(UInt(2.W))\n\n\t\tval mie = Input(UInt(6.W))\n\t\tval ifu_pmu_bus_trxn = Input(UInt(1.W))\n\t\tval lsu_pmu_bus_trxn = Input(UInt(1.W))\n\t\tval lsu_pmu_bus_misaligned = Input(UInt(1.W))\n\t\tval ifu_pmu_bus_error = Input(UInt(1.W))\n\t\tval lsu_pmu_bus_error = Input(UInt(1.W))\n\t\tval ifu_pmu_bus_busy = Input(UInt(1.W))\n\t\tval lsu_pmu_bus_busy = Input(UInt(1.W))\n\t\tval i0_trigger_hit_r = Input(UInt(1.W))\n\t\tval lsu_exc_valid_r = Input(UInt(1.W))\n\t\tval take_timer_int = Input(UInt(1.W))\n\t\tval take_int_timer0_int = Input(UInt(1.W))\n\t\tval take_int_timer1_int = Input(UInt(1.W))\n\t\tval take_ext_int = Input(UInt(1.W))\n\t\tval tlu_flush_lower_r = Input(UInt(1.W))\n\t\tval dec_tlu_br0_error_r = Input(UInt(1.W))\n\t\tval rfpc_i0_r = Input(UInt(1.W))\n\t\tval dec_tlu_br0_start_error_r = Input(UInt(1.W))\n\n\n\t\tval mcyclel_cout_f =Output(Bool())\n\t\tval minstret_enable_f =Output(Bool())\n\t\tval minstretl_cout_f =Output(Bool())\n\t\tval fw_halted =Output(Bool())\n\t\tval meicidpl =Output(UInt(4.W))\n\t\tval icache_rd_valid_f =Output(Bool())\n\t\tval icache_wr_valid_f =Output(Bool())\n\t\tval mhpmc_inc_r_d1 =Output(Vec(4,UInt(1.W)))\n\t\tval perfcnt_halted_d1 =Output(Bool())\n\t\tval mdseac_locked_f =Output(Bool())\n\t\tval lsu_single_ecc_error_r_d1 =Output(Bool())\n\t\tval lsu_exc_valid_r_d1 =Output(Bool())\n\t\tval lsu_i0_exc_r_d1 =Output(Bool())\n\t\tval take_ext_int_start_d1 =Output(Bool())\n\t\tval take_ext_int_start_d2 =Output(Bool())\n\t\tval take_ext_int_start_d3 =Output(Bool())\n\t\tval ext_int_freeze_d1 =Output(Bool())\n\t\tval mip = Output(UInt(6.W))\n\t\tval mdseac_locked_ns = Input(Bool())\n\t\tval lsu_single_ecc_error_r = Input(Bool())\n\t\tval lsu_i0_exc_r = Input(Bool())\n\t\tval take_ext_int_start = Input(Bool())\n\t\tval ext_int_freeze = Input(Bool())\n\t\tval mip_ns = Input(UInt(6.W))\n\t\tval mcyclel_cout = Input(Bool())\n\t\tval wr_mcycleh_r = Input(Bool())\n\t\tval mcyclel_cout_in = Input(Bool())\n\t\tval minstret_enable = Input(Bool())\n\t\tval minstretl_cout_ns = Input(Bool())\n\t\tval fw_halted_ns = Input(Bool())\n\t\tval meicidpl_ns = Input(UInt(4.W))\n\t\tval icache_rd_valid = Input(Bool())\n\t\tval icache_wr_valid = Input(Bool())\n\t\tval perfcnt_halted = Input(Bool())\n\t\tval mstatus_ns = Input(UInt(2.W))\n\t\tval scan_mode = Input(Bool())\n\t\tval free_l2clk = Input(Clock())\n\n\n\t})\n\timport inst_pkt_t._\n\tval pmu_i0_itype_qual = io.dec_tlu_packet_r.pmu_i0_itype & Fill(4,io.tlu_i0_commit_cmt)\n\tfor(i <- 0 until 4) {\n\t\tio.mhpmc_inc_r(i) := (~io.mcountinhibit(i+3) & (Mux1H(Seq(\n\t\t\t(io.mhpme_vec(i) === MHPME_CLK_ACTIVE ).asBool -> 1.U,\n\t\t\t(io.mhpme_vec(i) === MHPME_ICACHE_HIT ).asBool -> io.ifu_pmu_ic_hit,\n\t\t\t(io.mhpme_vec(i) === MHPME_ICACHE_MISS ).asBool -> io.ifu_pmu_ic_miss,\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_COMMIT ).asBool -> (io.tlu_i0_commit_cmt & ~io.illegal_r),\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_COMMIT_16B ).asBool -> (io.tlu_i0_commit_cmt & ~io.exu_pmu_i0_pc4 & ~io.illegal_r),\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_COMMIT_32B ).asBool -> (io.tlu_i0_commit_cmt & io.exu_pmu_i0_pc4 & ~io.illegal_r),\n\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_ALIGNED ).asBool -> io.ifu_pmu_instr_aligned,\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_DECODED ).asBool -> io.dec_pmu_instr_decoded,\n\t\t\t(io.mhpme_vec(i) === MHPME_DECODE_STALL ).asBool -> io.dec_pmu_decode_stall,\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_MUL ).asBool -> (pmu_i0_itype_qual === MUL),\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_DIV ).asBool -> (io.dec_tlu_packet_r.pmu_divide & io.tlu_i0_commit_cmt & !io.illegal_r),\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_LOAD ).asBool -> (pmu_i0_itype_qual === LOAD),\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_STORE ).asBool -> (pmu_i0_itype_qual === STORE),\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_MALOAD ).asBool -> (pmu_i0_itype_qual === LOAD & io.dec_tlu_packet_r.pmu_lsu_misaligned),\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_MASTORE\t ).asBool -> (pmu_i0_itype_qual === STORE & io.dec_tlu_packet_r.pmu_lsu_misaligned.asBool),\n\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_ALU\t).asBool -> (pmu_i0_itype_qual === ALU),\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_CSRREAD ).asBool -> (pmu_i0_itype_qual === CSRREAD),\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_CSRWRITE).asBool -> (pmu_i0_itype_qual === CSRWRITE),\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_CSRRW ).asBool -> (pmu_i0_itype_qual === CSRRW),\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_EBREAK ).asBool -> (pmu_i0_itype_qual === EBREAK),\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_ECALL ).asBool -> (pmu_i0_itype_qual === ECALL),\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_FENCE ).asBool -> (pmu_i0_itype_qual === FENCE),\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_FENCEI ).asBool -> (pmu_i0_itype_qual === FENCEI),\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_MRET ).asBool -> (pmu_i0_itype_qual === MRET),\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_BRANCH ).asBool -> ((pmu_i0_itype_qual === CONDBR) | (pmu_i0_itype_qual === JAL)),\n\n\t\t\t(io.mhpme_vec(i) === MHPME_BRANCH_MP ).asBool -> (io.exu_pmu_i0_br_misp & io.tlu_i0_commit_cmt & !io.illegal_r),\n\t\t\t(io.mhpme_vec(i) === MHPME_BRANCH_TAKEN ).asBool -> (io.exu_pmu_i0_br_ataken & io.tlu_i0_commit_cmt & !io.illegal_r),\n\t\t\t(io.mhpme_vec(i) === MHPME_BRANCH_NOTP ).asBool -> (io.dec_tlu_packet_r.pmu_i0_br_unpred & io.tlu_i0_commit_cmt & !io.illegal_r),\n\t\t\t(io.mhpme_vec(i) === MHPME_FETCH_STALL ).asBool -> io.ifu_pmu_fetch_stall,\n\t\t\t(io.mhpme_vec(i) === MHPME_DECODE_STALL ).asBool -> io.dec_pmu_decode_stall,\n\t\t\t(io.mhpme_vec(i) === MHPME_POSTSYNC_STALL ).asBool -> io.dec_pmu_postsync_stall,\n\t\t\t(io.mhpme_vec(i) === MHPME_PRESYNC_STALL ).asBool -> io.dec_pmu_presync_stall,\n\t\t\t(io.mhpme_vec(i) === MHPME_LSU_SB_WB_STALL ).asBool -> io.lsu_store_stall_any,\n\t\t\t(io.mhpme_vec(i) === MHPME_DMA_DCCM_STALL ).asBool -> io.dma_dccm_stall_any,\n\t\t\t(io.mhpme_vec(i) === MHPME_DMA_ICCM_STALL ).asBool -> io.dma_iccm_stall_any,\n\t\t\t(io.mhpme_vec(i) === MHPME_EXC_TAKEN ).asBool -> (io.i0_exception_valid_r | io.i0_trigger_hit_r | io.lsu_exc_valid_r),\n\t\t\t(io.mhpme_vec(i) === MHPME_TIMER_INT_TAKEN ).asBool -> (io.take_timer_int | io.take_int_timer0_int | io.take_int_timer1_int),\n\t\t\t(io.mhpme_vec(i) === MHPME_EXT_INT_TAKEN ).asBool -> io.take_ext_int,\n\t\t\t(io.mhpme_vec(i) === MHPME_FLUSH_LOWER ).asBool -> io.tlu_flush_lower_r,\n\t\t\t(io.mhpme_vec(i) === MHPME_BR_ERROR ).asBool -> ((io.dec_tlu_br0_error_r | io.dec_tlu_br0_start_error_r) & io.rfpc_i0_r),\n\n\t\t\t(io.mhpme_vec(i) === MHPME_IBUS_TRANS ).asBool -> io.ifu_pmu_bus_trxn,\n\t\t\t(io.mhpme_vec(i) === MHPME_DBUS_TRANS ).asBool -> io.lsu_pmu_bus_trxn,\n\t\t\t(io.mhpme_vec(i) === MHPME_DBUS_MA_TRANS ).asBool -> io.lsu_pmu_bus_misaligned,\n\t\t\t(io.mhpme_vec(i) === MHPME_IBUS_ERROR ).asBool -> io.ifu_pmu_bus_error,\n\t\t\t(io.mhpme_vec(i) === MHPME_DBUS_ERROR ).asBool -> io.lsu_pmu_bus_error,\n\t\t\t(io.mhpme_vec(i) === MHPME_IBUS_STALL ).asBool -> io.ifu_pmu_bus_busy,\n\t\t\t(io.mhpme_vec(i) === MHPME_DBUS_STALL ).asBool -> io.lsu_pmu_bus_busy,\n\t\t\t(io.mhpme_vec(i) === MHPME_INT_DISABLED ).asBool -> (~io.mstatus(MSTATUS_MIE)),\n\t\t\t(io.mhpme_vec(i) === MHPME_INT_STALLED ).asBool -> (~io.mstatus(MSTATUS_MIE) & (io.mip(5,0) & io.mie(5,0)).orR),\n\t\t\t(io.mhpme_vec(i) === MHPME_INST_BITMANIP ).asBool -> (pmu_i0_itype_qual === BITMANIPU),\n\t\t\t(io.mhpme_vec(i) === MHPME_DBUS_LOAD ).asBool -> (io.tlu_i0_commit_cmt & io.lsu_pmu_load_external_r & !io.illegal_r),\n\t\t\t(io.mhpme_vec(i) === MHPME_DBUS_STORE ).asBool -> (io.tlu_i0_commit_cmt & io.lsu_pmu_store_external_r & !io.illegal_r),\n\t\t\t// These count even during sleep\n\t\t\t(io.mhpme_vec(i) === MHPME_SLEEP_CYC ).asBool -> io.dec_tlu_pmu_fw_halted,\n\t\t\t(io.mhpme_vec(i) === MHPME_DMA_READ_ALL ).asBool -> io.dma_pmu_any_read,\n\t\t\t(io.mhpme_vec(i) === MHPME_DMA_WRITE_ALL ).asBool -> io.dma_pmu_any_write,\n\t\t\t(io.mhpme_vec(i) === MHPME_DMA_READ_DCCM ).asBool -> io.dma_pmu_dccm_read,\n\t\t\t(io.mhpme_vec(i) === MHPME_DMA_WRITE_DCCM ).asBool -> io.dma_pmu_dccm_write ))))\n\t}\n\n\n\n\n\n\n\n\n\tif(FAST_INTERRUPT_REDIRECT) {\n\t\tio.mdseac_locked_f :=rvdffie(io.mdseac_locked_ns,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.lsu_single_ecc_error_r_d1 :=rvdffie(io.lsu_single_ecc_error_r,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.lsu_exc_valid_r_d1 :=rvdffie(io.lsu_exc_valid_r,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.lsu_i0_exc_r_d1 :=rvdffie(io.lsu_i0_exc_r,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.take_ext_int_start_d1 :=rvdffie(io.take_ext_int_start,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.take_ext_int_start_d2 :=rvdffie(io.take_ext_int_start_d1,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.take_ext_int_start_d3 :=rvdffie(io.take_ext_int_start_d2,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.ext_int_freeze_d1 :=rvdffie(io.ext_int_freeze,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.mip :=rvdffie(io.mip_ns,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.mcyclel_cout_f :=rvdffie(io.mcyclel_cout & ~io.wr_mcycleh_r & io.mcyclel_cout_in,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.minstret_enable_f :=rvdffie(io.minstret_enable,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.minstretl_cout_f :=rvdffie(io.minstretl_cout_ns,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.fw_halted :=rvdffie(io.fw_halted_ns,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.meicidpl :=rvdffie(io.meicidpl_ns,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.icache_rd_valid_f :=rvdffie(io.icache_rd_valid,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.icache_wr_valid_f :=rvdffie(io.icache_wr_valid,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.mhpmc_inc_r_d1 :=rvdffie(io.mhpmc_inc_r,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.perfcnt_halted_d1 :=rvdffie(io.perfcnt_halted,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.mstatus :=rvdffie(io.mstatus_ns,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t}\n\telse{\n\t\tio.take_ext_int_start_d1 := 0.U\n\t\tio.take_ext_int_start_d2 :=0.U\n\t\tio.take_ext_int_start_d3 :=0.U\n\t\tio.ext_int_freeze_d1 :=0.U\n\t\tio.mdseac_locked_f :=rvdffie(io.mdseac_locked_ns,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.lsu_single_ecc_error_r_d1 :=rvdffie(io.lsu_single_ecc_error_r,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.lsu_exc_valid_r_d1 :=rvdffie(io.lsu_exc_valid_r,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.lsu_i0_exc_r_d1 :=rvdffie(io.lsu_i0_exc_r,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.mip :=rvdffie(io.mip_ns,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.mcyclel_cout_f :=rvdffie((io.mcyclel_cout & !io.wr_mcycleh_r & io.mcyclel_cout_in),io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.minstret_enable_f :=rvdffie(io.minstret_enable,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.minstretl_cout_f :=rvdffie(io.minstretl_cout_ns,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.fw_halted :=rvdffie(io.fw_halted_ns,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.meicidpl :=rvdffie(io.meicidpl_ns,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.icache_rd_valid_f :=rvdffie(io.icache_rd_valid,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.icache_wr_valid_f :=rvdffie(io.icache_wr_valid,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.mhpmc_inc_r_d1 :=rvdffie(io.mhpmc_inc_r,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.perfcnt_halted_d1 :=rvdffie(io.perfcnt_halted,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t\tio.mstatus :=rvdffie(io.mstatus_ns,io.free_l2clk,reset.asAsyncReset(),io.scan_mode)\n\t}\n}\n\nclass int_exc extends Module with CSRs with lib with RequireAsyncReset{\n\tval io = IO(new Bundle{\n\t\tval mhwakeup_ready = Output(Bool())\n\t\tval ext_int_ready = Output(Bool())\n\t\tval ce_int_ready = Output(Bool())\n\t\tval soft_int_ready = Output(Bool())\n\t\tval timer_int_ready = Output(Bool())\n\t\tval int_timer0_int_hold = Output(UInt(1.W))\n\t\tval int_timer1_int_hold = Output(UInt(1.W))\n\t\tval internal_dbg_halt_timers\t\t = Output(UInt(1.W))\n\t\tval take_ext_int_start = Output(UInt(1.W))\n\t\tval ext_int_freeze_d1 = Input(UInt(1.W))\n\t\tval take_ext_int_start_d1 = Input(UInt(1.W))\n\t\tval take_ext_int_start_d2 = Input(UInt(1.W))\n\t\tval take_ext_int_start_d3 = Input(UInt(1.W))\n\t\tval ext_int_freeze = Output(UInt(1.W))\n\t\tval take_ext_int = Output(UInt(1.W))\n\t\tval fast_int_meicpct = Output(UInt(1.W))\n\t\tval ignore_ext_int_due_to_lsu_stall = Output(UInt(1.W))\n\t\tval take_ce_int = Output(UInt(1.W))\n\t\tval take_soft_int = Output(UInt(1.W))\n\t\tval take_timer_int = Output(UInt(1.W))\n\t\tval take_int_timer0_int = Output(UInt(1.W))\n\t\tval take_int_timer1_int = Output(UInt(1.W))\n\t\tval take_reset = Output(UInt(1.W))\n\t\tval take_nmi = Output(UInt(1.W))\n\t\tval synchronous_flush_r = Output(UInt(1.W))\n\t\tval tlu_flush_lower_r = Output(UInt(1.W))\n\t\tval dec_tlu_flush_lower_wb = Output(UInt(1.W))\n\t\tval dec_tlu_flush_lower_r = Output(UInt(1.W))\n\t\tval dec_tlu_flush_path_r = Output(UInt(31.W))\n\t\tval interrupt_valid_r_d1 = Output(Bool())\n\t\tval i0_exception_valid_r_d1 = Output(UInt(1.W))\n\t\tval exc_or_int_valid_r_d1 = Output(UInt(1.W))\n\t\tval exc_cause_wb = Output(UInt(5.W))\n\t\tval i0_valid_wb = Output(UInt(1.W))\n\t\tval trigger_hit_r_d1 = Output(UInt(1.W))\n\t\tval take_nmi_r_d1 = Output(UInt(1.W))\n\t\tval pause_expired_wb = Output(UInt(1.W))\n\t\tval interrupt_valid_r = Output(UInt(1.W))\n\t\tval exc_cause_r = Output(UInt(5.W))\n\t\tval i0_exception_valid_r = Output(UInt(1.W))\n\t\tval tlu_flush_path_r_d1 = Output(UInt(31.W))\n\t\tval exc_or_int_valid_r =Output(UInt(1.W))\n\n\t\tval free_l2clk = Input(Clock())\n\t\tval scan_mode = Input(Bool())\n\t\tval dec_csr_stall_int_ff = Input(UInt(1.W))\n\t\tval mstatus_mie_ns = Input(UInt(1.W))\n\t\tval mip = Input(UInt(6.W))\n\t\tval mie_ns = Input(UInt(6.W))\n\t\tval mret_r \t\t\t\t\t = Input(UInt(1.W))\n\t\tval pmu_fw_tlu_halted_f\t\t\t = Input(UInt(1.W))\n\t\tval int_timer0_int_hold_f\t\t\t = Input(UInt(1.W))\n\t\tval int_timer1_int_hold_f\t\t\t = Input(UInt(1.W))\n\t\tval internal_dbg_halt_mode_f\t\t = Input(UInt(1.W))\n\t\tval dcsr_single_step_running = Input(UInt(1.W))\n\t\tval internal_dbg_halt_mode\t\t = Input(UInt(1.W))\n\t\tval dec_tlu_i0_valid_r = Input(UInt(1.W))\n\t\tval internal_pmu_fw_halt_mode\t = Input(UInt(1.W))\n\t\tval i_cpu_halt_req_d1 = Input(UInt(1.W))\n\t\tval ebreak_to_debug_mode_r \t\t \t = Input(UInt(1.W))\n\t\tval lsu_fir_error = Input(UInt(2.W))\n\t\tval csr_pkt = Input(new dec_tlu_csr_pkt)\n\t\tval dec_csr_any_unq_d = Input(UInt(1.W))\n\t\tval lsu_fastint_stall_any = Input(UInt(1.W))\n\t\tval reset_delayed\t\t\t\t\t = Input(UInt(1.W))\n\t\tval mpc_reset_run_req = Input(UInt(1.W))\n\t\tval nmi_int_detected \t\t\t = Input(UInt(1.W))\n\t\tval dcsr_single_step_running_f\t \t = Input(UInt(1.W))\n\t\tval dcsr_single_step_done_f\t\t\t = Input(UInt(1.W))\n\t\tval dcsr = Input(UInt(16.W))\n\t\tval mtvec = Input(UInt(31.W))\n\n\t\tval tlu_i0_commit_cmt = Input(UInt(1.W))\n\t\tval i0_trigger_hit_r = Input(UInt(1.W))\n\t\tval pause_expired_r\t\t\t\t\t = Input(UInt(1.W))\n\t\tval nmi_vec = Input(UInt(31.W))\n\t\tval lsu_i0_rfnpc_r = Input(UInt(1.W))\n\t\tval fence_i_r\t\t\t\t\t\t = Input(UInt(1.W))\n\t\tval iccm_repair_state_rfnpc = Input(UInt(1.W))\n\t\tval i_cpu_run_req_d1\t\t\t\t = Input(UInt(1.W))\n\t\tval rfpc_i0_r \t\t\t\t\t\t = Input(UInt(1.W))\n\t\tval lsu_exc_valid_r = Input(UInt(1.W))\n\t\tval trigger_hit_dmode_r \t\t\t = Input(UInt(1.W))\n\t\tval take_halt = Input(UInt(1.W))\n\t\tval rst_vec = Input(UInt(31.W))\n\t\tval lsu_fir_addr = Input(UInt(31.W))\n\t\tval dec_tlu_i0_pc_r = Input(UInt(31.W))\n\t\tval npc_r = Input(UInt(31.W))\n\t\tval mepc = Input(UInt(31.W))\n\t\tval debug_resume_req_f\t\t\t\t = Input(UInt(1.W))\n\t\tval dpc = Input(UInt(31.W))\n\t\tval npc_r_d1 = Input(UInt(31.W))\n\t\tval tlu_flush_lower_r_d1 = Input(UInt(1.W))\n\t\tval dec_tlu_dbg_halted = Input(UInt(1.W))\n\t\tval ebreak_r = Input(UInt(1.W))\n\t\tval ecall_r = Input(UInt(1.W))\n\t\tval illegal_r = Input(UInt(1.W))\n\t\tval inst_acc_r = Input(UInt(1.W))\n\t\tval lsu_i0_exc_r = Input(UInt(1.W))\n\t\tval lsu_error_pkt_r = Flipped(Valid(new lsu_error_pkt_t))\n\t\tval dec_tlu_wr_pause_r_d1 = Input(UInt(1.W))\n\t})\n\tval lsu_exc_ma_r = io.lsu_i0_exc_r & !io.lsu_error_pkt_r.bits.exc_type\n\tval lsu_exc_acc_r = io.lsu_i0_exc_r & io.lsu_error_pkt_r.bits.exc_type\n\tval lsu_exc_st_r = io.lsu_i0_exc_r & io.lsu_error_pkt_r.bits.inst_type\n\t//\n\t// Exceptions\n\t//\n\t// - MEPC <- PC\n\t// - PC <- MTVEC, assert flush_lower\n\t// - MCAUSE <- cause\n\t// - MSCAUSE <- secondary cause\n\t// - MTVAL <-\n\t// - MPIE <- MIE\n\t// - MIE <- 0\n\t//\n\tio.i0_exception_valid_r := (io.ebreak_r | io.ecall_r | io.illegal_r | io.inst_acc_r) & ~io.rfpc_i0_r & ~io.dec_tlu_dbg_halted\n\n\t// Cause:\n\t//\n\t// 0x2 : illegal\n\t// 0x3 : breakpoint\n\t// 0xb : Environment call M-mode\n\n\tio.exc_cause_r := ~Fill(5,io.take_nmi) & Mux1H(Seq(\n\t\t(io.take_ext_int).asBool \t\t\t\t-> 0x0b.U(5.W),\n\t\t(io.take_timer_int ).asBool \t\t\t\t-> 0x07.U(5.W),\n\t\t(io.take_soft_int).asBool \t\t\t\t-> 0x03.U(5.W),\n\t\t(io.take_int_timer0_int ).asBool \t\t\t\t-> 0x1d.U(5.W),\n\t\t(io.take_int_timer1_int).asBool \t\t\t\t-> 0x1c.U(5.W),\n\t\t(io.take_ce_int).asBool \t\t\t\t-> 0x1e.U(5.W),\n\t\t(io.illegal_r).asBool \t\t\t\t-> 0x02.U(5.W),\n\t\t(io.ecall_r).asBool \t\t\t\t-> 0x0b.U(5.W),\n\t\t(io.inst_acc_r ).asBool \t\t\t\t-> 0x01.U(5.W),\n\t\t((io.ebreak_r | io.i0_trigger_hit_r)).asBool \t-> 0x03.U(5.W),\n\t\t(lsu_exc_ma_r & !lsu_exc_st_r).asBool \t-> 0x04.U(5.W),\n\t\t(lsu_exc_acc_r & !lsu_exc_st_r).asBool \t-> 0x05.U(5.W),\n\t\t(lsu_exc_ma_r & lsu_exc_st_r ).asBool \t-> 0x06.U(5.W),\n\t\t(lsu_exc_acc_r & lsu_exc_st_r ).asBool \t-> 0x07.U(5.W)\n\t))\n\t//\n\t// Interrupts\n\t//\n\t// exceptions that are committed have already happened and will cause an int at E4 to wait a cycle\n\t// or more if MSTATUS[MIE] is cleared.\n\t//\n\t// -in priority order, highest to lowest\n\t// -single cycle window where a csr write to MIE/MSTATUS is at E4 when the other conditions for externals are met.\n\t// Hold off externals for a cycle to make sure we are consistent with what was just written\n\tio.mhwakeup_ready := !io.dec_csr_stall_int_ff & io.mstatus_mie_ns & io.mip(MIP_MEIP) & io.mie_ns(MIE_MEIE)\n\tio.ext_int_ready := !io.dec_csr_stall_int_ff & io.mstatus_mie_ns & io.mip(MIP_MEIP) & io.mie_ns(MIE_MEIE) & ~io.ignore_ext_int_due_to_lsu_stall\n\tio.ce_int_ready := !io.dec_csr_stall_int_ff & io.mstatus_mie_ns & io.mip(MIP_MCEIP) & io.mie_ns(MIE_MCEIE)\n\tio.soft_int_ready := !io.dec_csr_stall_int_ff & io.mstatus_mie_ns & io.mip(MIP_MSIP) & io.mie_ns(MIE_MSIE)\n\tio.timer_int_ready := !io.dec_csr_stall_int_ff & io.mstatus_mie_ns & io.mip(MIP_MTIP) & io.mie_ns(MIE_MTIE)\n\n\t// MIP for internal timers pulses for 1 clock, resets the timer counter. Mip won't hold past the various stall conditions.\n\tval int_timer0_int_possible = io.mstatus_mie_ns & io.mie_ns(MIE_MITIE0)\n\tval int_timer0_int_ready = io.mip(MIP_MITIP0) & int_timer0_int_possible\n\tval int_timer1_int_possible = io.mstatus_mie_ns & io.mie_ns(MIE_MITIE1)\n\tval int_timer1_int_ready = io.mip(MIP_MITIP1) & int_timer1_int_possible\n\n\t// Internal timers pulse and reset. If core is PMU/FW halted, the pulse will cause an exit from halt, but won't stick around\n\t// Make it sticky, also for 1 cycle stall conditions.\n\tval int_timer_stalled = io.dec_csr_stall_int_ff | io.synchronous_flush_r | io.exc_or_int_valid_r_d1 | io.mret_r\n\n\tio.int_timer0_int_hold := (int_timer0_int_ready & (io.pmu_fw_tlu_halted_f | int_timer_stalled)) | (int_timer0_int_possible & io.int_timer0_int_hold_f & ~io.interrupt_valid_r & ~io.take_ext_int_start & ~io.internal_dbg_halt_mode_f)\n\tio.int_timer1_int_hold := (int_timer1_int_ready & (io.pmu_fw_tlu_halted_f | int_timer_stalled)) | (int_timer1_int_possible & io.int_timer1_int_hold_f & ~io.interrupt_valid_r & ~io.take_ext_int_start & ~io.internal_dbg_halt_mode_f)\n\n\tio.internal_dbg_halt_timers := io.internal_dbg_halt_mode_f & ~io.dcsr_single_step_running\n\n\tval block_interrupts = ((io.internal_dbg_halt_mode & (~io.dcsr_single_step_running | io.dec_tlu_i0_valid_r)) | io.internal_pmu_fw_halt_mode | io.i_cpu_halt_req_d1 | io.take_nmi | io.ebreak_to_debug_mode_r | io.synchronous_flush_r | io.exc_or_int_valid_r_d1 | io.mret_r | io.ext_int_freeze_d1)\n\n\n\tif(FAST_INTERRUPT_REDIRECT) {\n\t\tio.take_ext_int_start := io.ext_int_ready & ~block_interrupts;\n\t\tio.ext_int_freeze := io.take_ext_int_start | io.take_ext_int_start_d1 | io.take_ext_int_start_d2 | io.take_ext_int_start_d3\n\t\tio.take_ext_int := io.take_ext_int_start_d3 & ~io.lsu_fir_error.orR\n\t\tio.fast_int_meicpct := io.csr_pkt.csr_meicpct & io.dec_csr_any_unq_d // MEICPCT becomes illegal if fast ints are enabled\n\t\tio.ignore_ext_int_due_to_lsu_stall := io.lsu_fastint_stall_any\n\t}else{\n\t\tio.take_ext_int_start := 0.U(1.W)\n\t\tio.ext_int_freeze := 0.U(1.W)\n\t\tio.fast_int_meicpct := 0.U(1.W)\n\t\tio.ignore_ext_int_due_to_lsu_stall := 0.U(1.W)\n\t\tio.take_ext_int := io.ext_int_ready & ~block_interrupts\n\t}\n\n\tio.take_ce_int := io.ce_int_ready & ~io.ext_int_ready & ~block_interrupts\n\tio.take_soft_int := io.soft_int_ready & ~io.ext_int_ready & ~io.ce_int_ready & ~block_interrupts\n\tio.take_timer_int := io.timer_int_ready & ~io.soft_int_ready & ~io.ext_int_ready & ~io.ce_int_ready & ~block_interrupts\n\tio.take_int_timer0_int := (int_timer0_int_ready | io.int_timer0_int_hold_f) & int_timer0_int_possible & ~io.dec_csr_stall_int_ff & ~io.timer_int_ready & ~io.soft_int_ready & ~io.ext_int_ready & ~io.ce_int_ready & ~block_interrupts\n\tio.take_int_timer1_int := (int_timer1_int_ready | io.int_timer1_int_hold_f) & int_timer1_int_possible & ~io.dec_csr_stall_int_ff & ~(int_timer0_int_ready | io.int_timer0_int_hold_f) & ~io.timer_int_ready & ~io.soft_int_ready & ~io.ext_int_ready & ~io.ce_int_ready & ~block_interrupts\n\tio.take_reset := io.reset_delayed & io.mpc_reset_run_req\n\tio.take_nmi := io.nmi_int_detected & ~io.internal_pmu_fw_halt_mode & (~io.internal_dbg_halt_mode | (io.dcsr_single_step_running_f & io.dcsr(DCSR_STEPIE) & ~io.dec_tlu_i0_valid_r & ~io.dcsr_single_step_done_f))& ~io.synchronous_flush_r & ~io.mret_r & ~io.take_reset & ~io.ebreak_to_debug_mode_r & (~io.ext_int_freeze_d1 | (io.take_ext_int_start_d3 & io.lsu_fir_error.orR))\n\n\n\n\tio.interrupt_valid_r := io.take_ext_int | io.take_timer_int | io.take_soft_int | io.take_nmi | io.take_ce_int | io.take_int_timer0_int | io.take_int_timer1_int\n\n\n\t// Compute interrupt path:\n\t// If vectored async is set in mtvec, flush path for interrupts is MTVEC + (4 * CAUSE);\n\tval vectored_path = Cat(io.mtvec(30,1),0.U(1.W)) + Cat(0.U(25.W),io.exc_cause_r, 0.U(1.W)) ///After Combining Code revisit this\n\tval interrupt_path = Mux(io.take_nmi.asBool, io.nmi_vec, Mux(io.mtvec(0) === 1.U, vectored_path, Cat(io.mtvec(30,1),0.U(1.W))))///After Combining Code revisit this\n\tval sel_npc_r = io.lsu_i0_rfnpc_r | io.fence_i_r | io.iccm_repair_state_rfnpc | (io.i_cpu_run_req_d1 & ~io.interrupt_valid_r) | (io.rfpc_i0_r & ~io.dec_tlu_i0_valid_r)\n\tval sel_npc_resume = (io.i_cpu_run_req_d1 & io.pmu_fw_tlu_halted_f) | io.pause_expired_r\n\tval sel_fir_addr = io.take_ext_int_start_d3 & !(io.lsu_fir_error.orR)\n\tio.synchronous_flush_r := io.i0_exception_valid_r | io.rfpc_i0_r | io.lsu_exc_valid_r | io.fence_i_r | io.lsu_i0_rfnpc_r | io.iccm_repair_state_rfnpc | io.debug_resume_req_f | sel_npc_resume | io.dec_tlu_wr_pause_r_d1 | io.i0_trigger_hit_r\n\tio.tlu_flush_lower_r := io.interrupt_valid_r | io.mret_r | io.synchronous_flush_r | io.take_halt | io.take_reset | io.take_ext_int_start\n\t///After Combining Code revisit this\n\tval tlu_flush_path_r = Mux(io.take_reset.asBool, io.rst_vec,Mux1H(Seq(\n\t\t(sel_fir_addr).asBool\t -> io.lsu_fir_addr,\n\t\t(io.take_nmi===0.U & sel_npc_r===1.U)\t\t-> io.npc_r,\n\t\t(io.take_nmi===0.U & io.rfpc_i0_r===1.U & io.dec_tlu_i0_valid_r===1.U & sel_npc_r===0.U) -> io.dec_tlu_i0_pc_r,\n\t\t(io.interrupt_valid_r===1.U & sel_fir_addr===0.U) -> interrupt_path,\n\t\t((io.i0_exception_valid_r | io.lsu_exc_valid_r | (io.i0_trigger_hit_r & ~io.trigger_hit_dmode_r)) & ~io.interrupt_valid_r & ~sel_fir_addr).asBool\t-> Cat(io.mtvec(30,1),0.U(1.W)),\n\t\t(~io.take_nmi & io.mret_r).asBool \t\t\t\t-> io.mepc,\n\t\t(~io.take_nmi & io.debug_resume_req_f).asBool\t-> io.dpc,\n\t\t(~io.take_nmi & sel_npc_resume).asBool\t\t-> io.npc_r_d1\n\t)))\n\n\tio.tlu_flush_path_r_d1:=rvdffpcie(tlu_flush_path_r,io.tlu_flush_lower_r,reset.asAsyncReset(),clock, io.scan_mode)//withClock(e4e5_int_clk){RegNext(tlu_flush_path_r,0.U)} ///After Combining Code revisit this\n\n\tio.dec_tlu_flush_lower_wb \t:= io.tlu_flush_lower_r_d1\n\tio.dec_tlu_flush_lower_r \t:= io.tlu_flush_lower_r\n\tio.dec_tlu_flush_path_r \t:= tlu_flush_path_r ///After Combining Code revisit this\n\n\tio.exc_or_int_valid_r := io.lsu_exc_valid_r | io.i0_exception_valid_r | io.interrupt_valid_r | (io.i0_trigger_hit_r & ~io.trigger_hit_dmode_r)\n\n\tio.interrupt_valid_r_d1\t\t\t\t :=rvdffie(io.interrupt_valid_r, clock,reset.asAsyncReset(),io.scan_mode)//withClock(e4e5_int_clk){RegNext(interrupt_valid_r,0.U)}\n\tio.i0_exception_valid_r_d1\t\t :=rvdffie(io.i0_exception_valid_r, clock,reset.asAsyncReset(),io.scan_mode)//withClock(e4e5_int_clk){RegNext(i0_exception_valid_r,0.U)}\n\tio.exc_or_int_valid_r_d1\t\t :=rvdffie(io.exc_or_int_valid_r, clock,reset.asAsyncReset(),io.scan_mode)//withClock(e4e5_int_clk){RegNext(exc_or_int_valid_r,0.U)}\n\tio.exc_cause_wb\t\t\t\t\t :=rvdffie(io.exc_cause_r, clock,reset.asAsyncReset(),io.scan_mode)//withClock(e4e5_int_clk){RegNext(exc_cause_r,0.U)}\n\tio.i0_valid_wb\t\t\t\t\t\t :=rvdffie(io.tlu_i0_commit_cmt & !io.illegal_r, clock,reset.asAsyncReset(),io.scan_mode)//withClock(e4e5_int_clk){RegNext((tlu_i0_commit_cmt & ~illegal_r),0.U)}\n\tio.trigger_hit_r_d1\t\t\t\t :=rvdffie(io.i0_trigger_hit_r, clock,reset.asAsyncReset(),io.scan_mode)//withClock(e4e5_int_clk){RegNext(i0_trigger_hit_r,0.U)}\n\tio.take_nmi_r_d1\t\t\t\t\t \t:=rvdffie(io.take_nmi, clock,reset.asAsyncReset(),io.scan_mode)//withClock(e4e5_int_clk){RegNext(take_nmi,0.U)}\n\tio.pause_expired_wb\t\t\t\t\t :=rvdffie(io.pause_expired_r, clock,reset.asAsyncReset(),io.scan_mode)//withClock(e4e5_int_clk){RegNext(pause_expired_r,0.U)}\n\n}\n\nclass dec_decode_csr_read_IO extends Bundle{\n\tval dec_csr_rdaddr_d=Input(UInt(12.W))\n\tval csr_pkt=Output(new dec_tlu_csr_pkt)\n}\n\nclass dec_decode_csr_read extends Module with RequireAsyncReset{\n\tval io=IO(new dec_decode_csr_read_IO)\n\n", "right_context": "\t// 'z' is used for !io.dec_csr_rdaddr_d(0)\n\tio.csr_pkt.csr_misa \t\t\t\t:=pattern(List(-11,-6,-5,-2,0))\n\tio.csr_pkt.csr_mvendorid\t\t\t:=pattern(List(10,-7,-1,0))\n\tio.csr_pkt.csr_marchid\t\t\t\t:=pattern(List(10,-7,1,'z'))\n\tio.csr_pkt.csr_mimpid \t\t\t\t:=pattern(List(10,-6,1,0))\n\tio.csr_pkt.csr_mhartid\t\t\t\t:=pattern(List(10,-7,2))\n\tio.csr_pkt.csr_mstatus\t\t\t\t:=pattern(List(-11,-6,-5,-2,'z'))\n\tio.csr_pkt.csr_mtvec \t\t\t\t:=pattern(List(-11,-6,-5,2,0))\n\tio.csr_pkt.csr_mip \t\t\t\t\t:=pattern(List(-7,6,2))\n\tio.csr_pkt.csr_mie \t\t\t\t\t:=pattern(List(-11,-6,-5,2,'z'))\n\tio.csr_pkt.csr_mcyclel \t\t\t\t:=pattern(List(11,-7,-4,-3,-2,-1))\n\tio.csr_pkt.csr_mcycleh \t\t\t\t:=pattern(List(7,-6,-5,-4,-3,-2,-1))\n\tio.csr_pkt.csr_minstretl \t\t\t:=pattern(List(-7,-6,-4,-3,-2,1,'z'))\n\tio.csr_pkt.csr_minstreth \t\t\t:=pattern(List(-10,7,-4,-3,-2,1,'z'))\n\tio.csr_pkt.csr_mscratch \t\t\t:=pattern(List(-7,6,-2,-1,'z'))\n\tio.csr_pkt.csr_mepc \t\t\t\t:=pattern(List(-7,6,-1,0))\n\tio.csr_pkt.csr_mcause \t\t\t\t:=pattern(List(-7,6,1,'z'))\n\tio.csr_pkt.csr_mscause \t\t\t\t:=pattern(List(6,5,2))\n\tio.csr_pkt.csr_mtval\t\t\t\t:=pattern(List(-7,6,1,0))\n\tio.csr_pkt.csr_mrac \t\t\t\t:=pattern(List(-11,7,-5,-3,-2,-1))\n\tio.csr_pkt.csr_dmst \t\t\t\t:=pattern(List(10,-4,-3,2,-1))\n\tio.csr_pkt.csr_mdseac \t\t\t\t:=pattern(List(11,10,-4,-3))\n\tio.csr_pkt.csr_meihap \t\t\t\t:=pattern(List(11,10,3))\n\tio.csr_pkt.csr_meivt \t\t\t\t:=pattern(List(-10,6,3,-2,-1,'z'))\n\tio.csr_pkt.csr_meipt \t\t\t\t:=pattern(List(11,6,-1,0))\n\tio.csr_pkt.csr_meicurpl \t\t\t:=pattern(List(11,6,2))\n\tio.csr_pkt.csr_meicidpl \t\t\t:=pattern(List(11,6,1,0))\n\tio.csr_pkt.csr_dcsr \t\t\t\t:=pattern(List(10,-6,5,4,'z'))\n\tio.csr_pkt.csr_mcgc \t\t\t\t:=pattern(List(10,4,3,'z'))\n\tio.csr_pkt.csr_mfdc \t\t\t\t:=pattern(List(10,4,3,-1,0))\n\tio.csr_pkt.csr_dpc \t\t\t\t\t:=pattern(List(10,-6,5,4,0))\n\tio.csr_pkt.csr_mtsel \t\t\t\t:=pattern(List(10,5,-4,-1,'z'))\n\tio.csr_pkt.csr_mtdata1 \t\t\t\t:=pattern(List(10,-4,-3,0))\n\tio.csr_pkt.csr_mtdata2 \t\t\t\t:=pattern(List(10,5,-4,1))\n\tio.csr_pkt.csr_mhpmc3 \t\t\t\t:=pattern(List(11,-7,-4,-3,-2,0))\n\tio.csr_pkt.csr_mhpmc4 \t\t\t\t:=pattern(List(11,-7,-4,-3,2,-1,'z'))\n\tio.csr_pkt.csr_mhpmc5 \t\t\t\t:=pattern(List(11,-7,-4,-3,-1,0))\n\tio.csr_pkt.csr_mhpmc6 \t\t\t\t:=pattern(List(-7,-5,-4,-3,2,1,'z'))\n\tio.csr_pkt.csr_mhpmc3h \t\t\t\t:=pattern(List(7,-4,-3,-2,1,0))\n\tio.csr_pkt.csr_mhpmc4h \t\t\t\t:=pattern(List(7,-6,-4,-3,2,-1,'z'))\n\tio.csr_pkt.csr_mhpmc5h \t\t\t\t:=pattern(List(7,-4,-3,2,-1,0))\n\tio.csr_pkt.csr_mhpmc6h \t\t\t\t:=pattern(List(7,-6,-4,-3,2,1,'z'))\n\tio.csr_pkt.csr_mhpme3 \t\t\t\t:=pattern(List(-7,5,-4,-3,-2,0))\n\tio.csr_pkt.csr_mhpme4 \t\t\t\t:=pattern(List(5,-4,-3,2,-1,'z'))\n\tio.csr_pkt.csr_mhpme5 \t\t\t\t:=pattern(List(5,-4,-3,2,-1,0))\n\tio.csr_pkt.csr_mhpme6 \t\t\t\t:=pattern(List(5,-4,-3,2,1,'z'))\n\tio.csr_pkt.csr_mcountinhibit \t\t:=pattern(List(-7,5,-4,-3,-2,'z'))\n\tio.csr_pkt.csr_mitctl0 \t\t\t\t:=pattern(List(6,-5,4,-1,'z'))\n\tio.csr_pkt.csr_mitctl1 \t\t\t\t:=pattern(List(6,-3,2,1,0))\n\tio.csr_pkt.csr_mitb0 \t\t\t\t:=pattern(List(6,-5,4,-2,0))\n\tio.csr_pkt.csr_mitb1 \t\t\t\t:=pattern(List(6,4,2,1,'z'))\n\tio.csr_pkt.csr_mitcnt0 \t\t\t\t:=pattern(List(6,-5,4,-2,'z'))\n\tio.csr_pkt.csr_mitcnt1 \t\t\t\t:=pattern(List(6,2,-1,0))\n\tio.csr_pkt.csr_mpmc \t\t\t\t:=pattern(List(6,-4,-3,2,1))\n\tio.csr_pkt.csr_meicpct \t\t\t\t:=pattern(List(11,6,1,'z'))\n\tio.csr_pkt.csr_micect \t\t\t\t:=pattern(List(6,5,-3,-1,'z'))\n\tio.csr_pkt.csr_miccmect \t\t\t:=pattern(List(6,5,-3,0))\n\tio.csr_pkt.csr_mdccmect \t\t\t:=pattern(List(6,5,1,'z'))\n\tio.csr_pkt.csr_mfdht \t\t\t\t:=pattern(List(6,3,2,1,'z'))\n\tio.csr_pkt.csr_mfdhs \t\t\t\t:=pattern(List(6,-4,2,0))\n\tio.csr_pkt.csr_dicawics \t\t\t:=pattern(List(-11,-5,3,-2,-1,'z'))\n\tio.csr_pkt.csr_dicad0h \t\t\t\t:=pattern(List(10,3,2,-1))\n\tio.csr_pkt.csr_dicad0 \t\t\t\t:=pattern(List(10,-4,3,-1,0))\n\tio.csr_pkt.csr_dicad1 \t\t\t\t:=pattern(List(10,3,-2,1,'z'))\n\tio.csr_pkt.csr_dicago \t\t\t\t:=pattern(List(10,3,-2,1,0))\n\tio.csr_pkt.presync\t := \tpattern(List(10,4,3,-1,0)) \t\t| pattern(List(-7,5,-4,-3,-2,'z')) \t| pattern(List(-6,-5,-4,-3,-2,1)) |\n\t\tpattern(List(11,-4,-3,2,-1)) \t| pattern(List(11,-4,-3,1,'z')) \t| pattern(List(7,-5,-4,-3,-2,1))\n\tio.csr_pkt.postsync := \tpattern(List(10,4,3,-1,0)) \t\t| pattern(List(-11,-6,-5,2,0)) \t\t| pattern(List(-7,6,-1,0)) \t\t |\n\t\tpattern(List(10,-4,-3,0)) \t\t| pattern(List(-11,-7,-6,-4,-3,-2,'z'))\t| pattern(List(-11,7,6,-4,-3,-1))|\n\t\tpattern(List(10,-4,-3,-2,1))\n\tio.csr_pkt.legal := pattern(List(-11,10,9,8,7,6,4,-3,-2,1,'z')) \t| pattern(List(-11,-10,9,8,-7,-6,-5,-4,-3,-1)) \t|\n\t\tpattern(List(-11,-10,9,8,-7,-6,5,-1,'z')) \t\t| pattern(List(11,9,8,7,6,-5,-4,-2,-1,'z')) \t|\n\t\tpattern(List(11,-10,9,8,-6,-5,'z')) \t\t\t| pattern(List(-11,10,9,8,7,6,5,4,3,2,1,0)) \t|\n\t\tpattern(List(-11,10,9,8,7,6,5,4,-2,-1)) \t\t| pattern(List(11,9,8,-7,-6,-5,4,-3,-2,0)) \t\t|\n\t\tpattern(List(-11,10,9,8,7,-6,5,-3,-2,-1)) \t\t| pattern(List(-11,-10,9,8,-7,-6,5,2)) \t\t\t|\n\t\tpattern(List(11,9,8,-7,-6,-5,4,-3,2,-1,'z')) \t| pattern(List(-11,10,9,8,7,6,-5,-4,3,1)) \t\t|\n\t\tpattern(List(-11,10,9,8,7,6,-5,4,-3,2)) \t\t| pattern(List(11,9,8,-7,-6,-5,4,-3,-2,1)) \t\t|\n\t\tpattern(List(-11,-10,9,8,-7,-6,5,1,0)) \t\t\t| pattern(List(11,-10,9,8,7,-5,-4,3,-2)) \t\t|\n\t\tpattern(List(11,-10,9,8,7,-5,-4,3,-1,'z')) \t\t| pattern(List(11,-10,9,8,-6,-5,2)) \t\t\t|\n\t\tpattern(List(-11,10,9,8,7,6,-5 ,4,-3,1)) \t\t| pattern(List(-11,10,9,8,7,6 ,-5,-4,'z')) \t\t|\n\t\tpattern(List(-11,10,9,8,7,6 ,-5,-4,3,-2)) \t\t| pattern(List(-11,10,9,8,7,-6,5,-4,-3,-2,'z')) |\n\t\tpattern(List(11,-10,9,8,-6,-5,1)) \t\t\t\t| pattern(List(-11,-10,9,8,-7,6,-5,-4,-3,-2)) \t|\n\t\tpattern(List(-11,-10,9,8,-7,-5,-4,-3,-1,'z'))\t| pattern(List(-11,-10,9,8,-7,-6,5,3)) \t\t\t|\n\t\tpattern(List(11,-10,9,8,-6,-5,3)) \t\t\t\t| pattern(List(-11,-10,9,8,-7,-6,5,4)) \t\t\t|\n\t\tpattern(List(11,-10,9,8,-6,-5,4))\n}\n\n\nclass dec_timer_ctl extends Module with lib with RequireAsyncReset{\n\tval io=IO(new dec_timer_ctl_IO)\n\tval MITCTL_ENABLE=0\n\tval MITCTL_ENABLE_HALTED=1\n\tval MITCTL_ENABLE_PAUSED=2\n\n\tval mitctl1=WireInit(UInt(4.W),0.U)\n\tval mitctl0=WireInit(UInt(3.W),0.U)\n\tval mitb1 =WireInit(UInt(32.W),0.U)\n\tval mitb0 =WireInit(UInt(32.W),0.U)\n\tval mitcnt1=WireInit(UInt(32.W),0.U)\n\tval mitcnt0=WireInit(UInt(32.W),0.U)\n\n\tval mit0_match_ns=(mitcnt0 >= mitb0).asUInt\n\tval mit1_match_ns=(mitcnt1 >= mitb1).asUInt\n\n\tio.dec_timer_t0_pulse := mit0_match_ns\n\tio.dec_timer_t1_pulse := mit1_match_ns\n\t// ----------------------------------------------------------------------\n\t// MITCNT0 (RW)\n\t// [31:0] : Internal Timer Counter 0\n\n\tval MITCNT0 =0x7d2.U(12.W)\n\n\tval wr_mitcnt0_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r === MITCNT0)\n\n\tval mitcnt0_inc_ok = mitctl0(MITCTL_ENABLE) & (~io.dec_pause_state | mitctl0(MITCTL_ENABLE_PAUSED)) & (~io.dec_tlu_pmu_fw_halted | mitctl0(MITCTL_ENABLE_HALTED)) & ~io.internal_dbg_halt_timers\n\tval mitcnt0_inc1 = WireInit(UInt(9.W),0.U)\n\tval mitcnt0_inc2 = WireInit(UInt(24.W),0.U)\n\tmitcnt0_inc1 := mitcnt0(7,0) + Cat(0.U(7.W), 1.U(1.W))\n\tval mitcnt0_inc_cout = mitcnt0_inc1(8)\n\tmitcnt0_inc2 := mitcnt0(31,8) + Cat(0.U(23.W), mitcnt0_inc_cout)\n\tval mitcnt0_inc = Cat(mitcnt0_inc2,mitcnt0_inc1(7,0))\n\n\tval mitcnt0_ns = Mux(wr_mitcnt0_r, io.dec_csr_wrdata_r, Mux(mit0_match_ns, 0.U, mitcnt0_inc))\n\n\n\tmitcnt0\t\t:=Cat(rvdffe(mitcnt0_ns(31,8),(wr_mitcnt0_r | (mitcnt0_inc_ok & mitcnt0_inc_cout) | mit0_match_ns).asBool,io.free_l2clk,io.scan_mode),\n\t\trvdffe(mitcnt0_ns(7,0),(wr_mitcnt0_r | mitcnt0_inc_ok | mit0_match_ns).asBool,io.free_l2clk,io.scan_mode))\n\n\t// ----------------------------------------------------------------------\n\t// MITCNT1 (RW)\n\t// [31:0] : Internal Timer Counter 0\n\n\tval MITCNT1=0x7d5.U(12.W)\n\tval wr_mitcnt1_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r === MITCNT1).asUInt\n\n\tval mitcnt1_inc_ok = mitctl1(MITCTL_ENABLE) & (~io.dec_pause_state | mitctl1(MITCTL_ENABLE_PAUSED)) & (~io.dec_tlu_pmu_fw_halted | mitctl1(MITCTL_ENABLE_HALTED)) & ~io.internal_dbg_halt_timers & (~mitctl1(3) | mit0_match_ns)\n\n\t// only inc MITCNT1 if not cascaded with 0, or if 0 overflows\n\tval mitcnt1_inc1 = WireInit(UInt(9.W),0.U)\n\tval mitcnt1_inc2 = WireInit(UInt(24.W),0.U)\n\tmitcnt1_inc1 := mitcnt1(7,0) + Cat(0.U(7.W), 1.U(1.W))\n\tval mitcnt1_inc_cout = mitcnt1_inc1(8)\n\tmitcnt1_inc2 := mitcnt1(31,8) + Cat(0.U(23.W), mitcnt1_inc_cout)\n\tval mitcnt1_inc = Cat(mitcnt1_inc2,mitcnt1_inc1(7,0))\n\n\tval mitcnt1_ns =Mux(wr_mitcnt1_r.asBool, io.dec_csr_wrdata_r, Mux(mit1_match_ns.asBool, 0.U,mitcnt1_inc))\n\n\tmitcnt1\t\t:=Cat(rvdffe(mitcnt1_ns(31,8),(wr_mitcnt1_r | (mitcnt1_inc_ok & mitcnt1_inc_cout) | mit1_match_ns).asBool,io.free_l2clk,io.scan_mode),\n\t\trvdffe(mitcnt1_ns(7,0),(wr_mitcnt1_r | mitcnt1_inc_ok | mit1_match_ns).asBool,io.free_l2clk,io.scan_mode))\n\n\n\n\t// ----------------------------------------------------------------------\n\t// MITB0 (RW)\n\t// [31:0] : Internal Timer Bound 0\n\tval MITB0 =0x7d3.U(12.W)\n\n\tval wr_mitb0_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r === MITB0)\n\tval mitb0_b\t = rvdffe((~io.dec_csr_wrdata_r),wr_mitb0_r.asBool,clock,io.scan_mode)\n\tmitb0\t := ~mitb0_b\n\n\t// ----------------------------------------------------------------------\n\t// MITB1 (RW)\n\t// [31:0] : Internal Timer Bound 1\n\n\tval MITB1 =0x7d6.U(12.W)\n\tval wr_mitb1_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r=== MITB1)\n\tval mitb1_b=rvdffe((~io.dec_csr_wrdata_r),wr_mitb1_r.asBool,clock,io.scan_mode)\n\tmitb1 := ~mitb1_b\n\n\t// ----------------------------------------------------------------------\n\t// MITCTL0 (RW) Internal Timer Ctl 0\n\t// [31:3] : Reserved, reads 0x0\n\t// [2] : Enable while PAUSEd\n\t// [1] : Enable while HALTed\n\t// [0] : Enable (resets to 0x1)\n\n\tval MITCTL0 =0x7d4.U(12.W)\n\n\tval wr_mitctl0_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r === MITCTL0)\n\tval mitctl0_ns\t = Mux(wr_mitctl0_r.asBool, io.dec_csr_wrdata_r(2,0), mitctl0(2,0))\n\n\tval mitctl0_0_b_ns = ~mitctl0_ns(0)\n\tval mitctl0_0_b = withClock(io.csr_wr_clk){RegEnable(mitctl0_0_b_ns,0.U,wr_mitctl0_r)}\n\tmitctl0\t \t :=Cat(withClock(io.csr_wr_clk){RegEnable(mitctl0_ns(2,1),0.U,wr_mitctl0_r)},~mitctl0_0_b)\n\n\t// ----------------------------------------------------------------------\n\t// MITCTL1 (RW) Internal Timer Ctl 1\n\t// [31:4] : Reserved, reads 0x0\n\t// [3] : Cascade\n\t// [2] : Enable while PAUSEd\n\t// [1] : Enable while HALTed\n\t// [0] : Enable (resets to 0x1)\n\tval MITCTL1 =0x7d7.U(12.W)\n\tval wr_mitctl1_r = io.dec_csr_wen_r_mod & (io.dec_csr_wraddr_r=== MITCTL1)\n\tval mitctl1_ns\t = Mux(wr_mitctl1_r.asBool,io.dec_csr_wrdata_r(3,0), mitctl1(3,0))\n\tval mitctl1_0_b_ns= ~mitctl1_ns(0)\n\tval mitctl1_0_b=withClock(io.csr_wr_clk){RegEnable(mitctl1_0_b_ns,0.U,wr_mitctl1_r)}\n\tmitctl1:=Cat(withClock(io.csr_wr_clk){RegEnable(mitctl1_ns(3,1),0.U,wr_mitctl1_r)},~mitctl1_0_b)\n\n\tio.dec_timer_read_d \t:= io.csr_mitcnt1 | io.csr_mitcnt0 | io.csr_mitb1 | io.csr_mitb0 | io.csr_mitctl0 | io.csr_mitctl1\n\tio.dec_timer_rddata_d \t:=Mux1H(Seq(\n\t\tio.csr_mitcnt0.asBool -> mitcnt0(31,0),\n\t\tio.csr_mitcnt1.asBool \t-> mitcnt1,\n\t\tio.csr_mitb0.asBool\t\t-> mitb0,\n\t\tio.csr_mitb1.asBool\t\t-> mitb1,\n\t\tio.csr_mitctl0.asBool \t-> Cat(Fill(29,0.U(1.W)),mitctl0),\n\t\tio.csr_mitctl1.asBool \t-> Cat(Fill(28,0.U(1.W)),mitctl1)\n\t))\n}\n\n\nclass dec_timer_ctl_IO extends Bundle{\n\tval free_l2clk\t\t\t\t=Input(Clock())\n\tval csr_wr_clk = Input(Clock())\n\tval scan_mode\t\t\t\t=Input(Bool())\n\tval dec_csr_wen_r_mod\t\t=Input(UInt(1.W)) // csr write enable at wb\n\tval dec_csr_wraddr_r\t\t=Input(UInt(12.W)) // write address for csr\n\tval dec_csr_wrdata_r\t\t=Input(UInt(32.W)) // csr write data at wb\n\n\tval csr_mitctl0\t\t\t\t=Input(UInt(1.W))\n\tval csr_mitctl1\t\t\t\t=Input(UInt(1.W))\n\tval csr_mitb0\t\t\t\t=Input(UInt(1.W))\n\tval csr_mitb1\t\t\t\t=Input(UInt(1.W))\n\tval csr_mitcnt0\t\t\t\t=Input(UInt(1.W))\n\tval csr_mitcnt1\t\t\t\t=Input(UInt(1.W))\n\n\n\tval dec_pause_state\t\t\t=Input(UInt(1.W)) \t// Paused\n\tval dec_tlu_pmu_fw_halted\t=Input(UInt(1.W))\t// pmu/fw halted\n\tval internal_dbg_halt_timers=Input(UInt(1.W)) \t// debug halted\n\n\tval dec_timer_rddata_d\t\t=Output(UInt(32.W)) // timer CSR read data\n\tval dec_timer_read_d\t\t=Output(UInt(1.W)) \t// timer CSR address match\n\tval dec_timer_t0_pulse\t\t=Output(UInt(1.W)) \t// timer0 int\n\tval dec_timer_t1_pulse\t\t=Output(UInt(1.W)) \t// timer1 int\n}\nobject tlu extends App {\n\t(new chisel3.stage.ChiselStage).emitVerilog(new dec_tlu_ctl())\n}\n", "groundtruth": "\tdef pattern(y : List[Int]) = (0 until y.size).map(i=> if(y(i)>=0 & y(i)!='z') io.dec_csr_rdaddr_d(y(i)) else if(y(i)<0) !io.dec_csr_rdaddr_d(y(i).abs) else !io.dec_csr_rdaddr_d(0)).reduce(_&_)\n", "crossfile_context": ""}
{"task_id": "Quasar", "path": "Quasar/design/src/main/scala/dma_ctrl.scala", "left_context": "\nimport chisel3._\nimport chisel3.util._\nimport include._\nimport scala.collection._\nimport lib._\n\nclass dma_ctrl extends Module with lib with RequireAsyncReset {\n val io = IO(new Bundle {\n val free_clk = Input(Clock())\n val dma_bus_clk_en = Input(Bool()) // slave bus clock enable\n val clk_override = Input(Bool())\n val scan_mode = Input(Bool())\n val dbg_cmd_size = Input(UInt(2.W))\n\n val dma_dbg_cmd_done = Output(Bool())\n val dma_dbg_cmd_fail = Output(Bool())\n val dma_dbg_rddata = Output(UInt(32.W))\n val iccm_dma_rvalid = Input(Bool())\n val iccm_dma_ecc_error = Input(Bool())\n val iccm_dma_rtag = Input(UInt(3.W))\n val iccm_dma_rdata = Input(UInt(64.W))\n val dma_active = Output(Bool())\n val iccm_ready = Input(Bool())\n\n val dbg_dec_dma = new dec_dbg()\n val dbg_dma = new dbg_dma()\n val dec_dma = Flipped(new dec_dma())\n val lsu_dma = Flipped(new lsu_dma)\n val ifu_dma = Flipped(new ifu_dma)// AXI Write Channel\n val dma_axi = Flipped(new axi_channels(DMA_BUS_TAG))\n\n\n })\n\n val DEPTH = DMA_BUF_DEPTH\n\n val DEPTH_PTR = log2Ceil(DEPTH)\n\n val NACK_COUNT = 7\n\n val dma_dbg_mem_wrdata = WireInit(UInt(32.W), 0.U)\n val bus_cmd_addr = WireInit(UInt(32.W), 0.U)\n val bus_cmd_byteen = WireInit(UInt(8.W), 0.U)\n val bus_cmd_sz = WireInit(UInt(3.W), 0.U)\n val bus_cmd_write = WireInit(Bool(), false.B)\n val bus_cmd_posted_write = WireInit(Bool(), false.B)\n // Clock Gating logic\n val bus_cmd_valid = WireInit(Bool(),0.B)\n val bus_rsp_valid = WireInit(Bool(),0.B)\n val dma_dbg_cmd_done_q = WireInit(Bool(),0.B)\n val fifo_valid = WireInit(UInt(DEPTH.W),0.U)\n val dma_buffer_c1_clken = (bus_cmd_valid & io.dma_bus_clk_en) | io.dbg_dec_dma.dbg_ib.dbg_cmd_valid | io.clk_override\n val dma_free_clken = (bus_cmd_valid | bus_rsp_valid | io.dbg_dec_dma.dbg_ib.dbg_cmd_valid | io.dma_dbg_cmd_done | dma_dbg_cmd_done_q | (fifo_valid.orR) | io.clk_override)\n\n val dma_buffer_c1_clk = rvoclkhdr(clock,dma_buffer_c1_clken,io.scan_mode)\n val dma_free_clk = rvoclkhdr(clock,dma_free_clken,io.scan_mode)\n\n val fifo_addr_in = Mux(io.dbg_dec_dma.dbg_ib.dbg_cmd_valid, io.dbg_dec_dma.dbg_ib.dbg_cmd_addr, bus_cmd_addr)\n val fifo_byteen_in = Fill(8,!io.dbg_dec_dma.dbg_ib.dbg_cmd_valid) & bus_cmd_byteen // Byte enable is used only for bus requests//Mux(io.dbg_cmd_valid, 0.U, bus_cmd_byteen)\n val fifo_sz_in = Mux(io.dbg_dec_dma.dbg_ib.dbg_cmd_valid, Cat(0.U,io.dbg_cmd_size), bus_cmd_sz)\n val fifo_write_in = Mux(io.dbg_dec_dma.dbg_ib.dbg_cmd_valid, io.dbg_dec_dma.dbg_ib.dbg_cmd_write, bus_cmd_write)\n val fifo_posted_write_in = !io.dbg_dec_dma.dbg_ib.dbg_cmd_valid & bus_cmd_posted_write\n val fifo_dbg_in = io.dbg_dec_dma.dbg_ib.dbg_cmd_valid\n val bus_cmd_sent = WireInit(Bool(), false.B)\n val WrPtr = WireInit(UInt(DEPTH_PTR.W), 0.U)\n val RdPtr = WireInit(UInt(DEPTH_PTR.W), 0.U)\n val dma_address_error = WireInit(Bool(), false.B)\n val dma_alignment_error = WireInit(Bool(), false.B)\n\n val fifo_cmd_en = WireInit(UInt(DMA_BUF_DEPTH.W), 0.U)\n\n val fifo_data_en = WireInit(UInt(DMA_BUF_DEPTH.W), 0.U)\n\n val fifo_pend_en = WireInit(UInt(DMA_BUF_DEPTH.W), 0.U)\n\n val fifo_error_bus_en = WireInit(UInt(DMA_BUF_DEPTH.W), 0.U)\n\n val fifo_done_en = WireInit(UInt(DMA_BUF_DEPTH.W), 0.U)\n\n val fifo_done_bus_en = WireInit(UInt(DMA_BUF_DEPTH.W), 0.U)\n\n val fifo_reset = WireInit(UInt(DMA_BUF_DEPTH.W), 0.U)\n\n val fifo_error_en = WireInit(UInt(DMA_BUF_DEPTH.W),0.U)\n val dma_dbg_cmd_error = WireInit(UInt(1.W),0.U)\n val fifo_error_in = Wire(Vec(DMA_BUF_DEPTH, UInt(2.W)))\n val RspPtr = WireInit(UInt((log2Ceil(DMA_BUF_DEPTH)).W), 0.U)\n val bus_posted_write_done = WireInit(UInt(1.W), 0.U)\n val bus_rsp_sent = WireInit(UInt(1.W), 0.U)\n val fifo_error = Wire(Vec(DMA_BUF_DEPTH, UInt(2.W)))\n val fifo_done = WireInit(UInt(DMA_BUF_DEPTH.W), 0.U)\n fifo_cmd_en := (0 until DMA_BUF_DEPTH).map(i => (((bus_cmd_sent.asBool & io.dma_bus_clk_en) | (io.dbg_dec_dma.dbg_ib.dbg_cmd_valid & io.dbg_dec_dma.dbg_ib.dbg_cmd_type(1).asBool)) & (i.U === WrPtr)).asUInt).reverse.reduce(Cat(_,_))\n\n fifo_data_en := (0 until DMA_BUF_DEPTH).map(i => (((bus_cmd_sent & fifo_write_in & io.dma_bus_clk_en) | (io.dbg_dec_dma.dbg_ib.dbg_cmd_valid & io.dbg_dec_dma.dbg_ib.dbg_cmd_type(1) & io.dbg_dec_dma.dbg_ib.dbg_cmd_write)) & (i.U === WrPtr).asUInt()) | ((dma_address_error | dma_alignment_error) & (i.U === RdPtr).asUInt()) | (io.lsu_dma.dma_dccm_ctl.dccm_dma_rvalid & (i.U === io.lsu_dma.dma_dccm_ctl.dccm_dma_rtag).asUInt()) | (io.iccm_dma_rvalid & (i.U === io.iccm_dma_rtag).asUInt())).reverse.reduce(Cat(_,_))\n\n fifo_pend_en := (0 until DMA_BUF_DEPTH).map(i => ((io.lsu_dma.dma_lsc_ctl.dma_dccm_req | io.ifu_dma.dma_mem_ctl.dma_iccm_req) & !io.lsu_dma.dma_lsc_ctl.dma_mem_write & (i.U === RdPtr)).asUInt).reverse.reduce(Cat(_,_))\n\n fifo_error_en := (0 until DMA_BUF_DEPTH).map(i => (((dma_address_error.asBool | dma_alignment_error.asBool | dma_dbg_cmd_error) & (i.U === RdPtr)) | ((io.lsu_dma.dma_dccm_ctl.dccm_dma_rvalid & io.lsu_dma.dma_dccm_ctl.dccm_dma_ecc_error) & (i.U === io.lsu_dma.dma_dccm_ctl.dccm_dma_rtag)) | ((io.iccm_dma_rvalid & io.iccm_dma_ecc_error) & (i.U === io.iccm_dma_rtag))).asUInt).reverse.reduce(Cat(_,_))\n\n fifo_error_bus_en := (0 until DMA_BUF_DEPTH).map(i => ((((fifo_error_in(i)(1,0).orR) & fifo_error_en(i)) | (fifo_error(i).orR)) & io.dma_bus_clk_en).asUInt).reverse.reduce(Cat(_,_))\n\n fifo_done_en := (0 until DMA_BUF_DEPTH).map(i => (((fifo_error(i).orR | fifo_error_en(i) | ((io.lsu_dma.dma_lsc_ctl.dma_dccm_req | io.ifu_dma.dma_mem_ctl.dma_iccm_req) & io.lsu_dma.dma_lsc_ctl.dma_mem_write)) & (i.U === RdPtr)) | (io.lsu_dma.dma_dccm_ctl.dccm_dma_rvalid & (i.U === io.lsu_dma.dma_dccm_ctl.dccm_dma_rtag)) | (io.iccm_dma_rvalid & (i.U === io.iccm_dma_rtag))).asUInt).reverse.reduce(Cat(_,_))\n\n fifo_done_bus_en := (0 until DMA_BUF_DEPTH).map(i => ((fifo_done_en(i) | fifo_done(i)) & io.dma_bus_clk_en).asUInt).reverse.reduce(Cat(_,_))\n\n fifo_reset := (0 until DMA_BUF_DEPTH).map(i => ((((bus_rsp_sent | bus_posted_write_done) & io.dma_bus_clk_en) | io.dma_dbg_cmd_done) & (i.U === RspPtr))).reverse.reduce(Cat(_,_))\n\n (0 until DMA_BUF_DEPTH).map(i => fifo_error_in(i) := (Mux(io.lsu_dma.dma_dccm_ctl.dccm_dma_rvalid & (i.U === io.lsu_dma.dma_dccm_ctl.dccm_dma_rtag), Cat(0.U, io.lsu_dma.dma_dccm_ctl.dccm_dma_ecc_error), Mux(io.iccm_dma_rvalid & (i.U === io.iccm_dma_rtag), (Cat(0.U, io.iccm_dma_ecc_error)), (Cat((dma_address_error | dma_alignment_error | dma_dbg_cmd_error), dma_alignment_error))))))\n\n val fifo_addr = Wire(Vec(DEPTH,UInt(32.W)))\n val bus_cmd_wdata = WireInit(UInt(64.W), 0.U)\n val fifo_data_in = VecInit.tabulate(DMA_BUF_DEPTH)(i =>(Mux(fifo_error_en(i) & (fifo_error_in(i).orR), Cat(Fill(32, 0.U), fifo_addr(i)), Mux(io.lsu_dma.dma_dccm_ctl.dccm_dma_rvalid & (i.U === io.lsu_dma.dma_dccm_ctl.dccm_dma_rtag), io.lsu_dma.dma_dccm_ctl.dccm_dma_rdata, Mux(io.iccm_dma_rvalid & (i.U === io.iccm_dma_rtag), io.iccm_dma_rdata, Mux(io.dbg_dec_dma.dbg_ib.dbg_cmd_valid, Fill(2, dma_dbg_mem_wrdata), bus_cmd_wdata(63,0)))))))\n\n fifo_valid := (0 until DMA_BUF_DEPTH).map(i => withClock(dma_free_clk) {RegNext(Mux(fifo_cmd_en(i), 1.U, fifo_valid(i)) & !fifo_reset(i), 0.U)}).reverse.reduce(Cat(_,_))\n (0 until DMA_BUF_DEPTH).map(i => fifo_error(i) := withClock(dma_free_clk) {RegNext(Mux(fifo_error_en(i).asBool(),fifo_error_in(i) , fifo_error(i)) & Fill(fifo_error_in(i).getWidth , !fifo_reset(i)), 0.U)})\n val fifo_error_bus = WireInit(UInt(DEPTH.W), 0.U)\n val fifo_rpend = WireInit(UInt(DEPTH.W), 0.U)\n", "right_context": " fifo_rpend := (0 until DMA_BUF_DEPTH).map(i => withClock(dma_free_clk) {RegNext(Mux(fifo_pend_en(i), 1.U, fifo_rpend(i)) & !fifo_reset(i), 0.U)}).reverse.reduce(Cat(_,_))\n fifo_done := (0 until DMA_BUF_DEPTH).map(i => withClock(dma_free_clk) {RegNext(Mux(fifo_done_en(i), 1.U, fifo_done(i)) & !fifo_reset(i), 0.U)}).reverse.reduce(Cat(_,_))\n val fifo_done_bus = WireInit(UInt(DEPTH.W), 0.U)\n fifo_done_bus := (0 until DMA_BUF_DEPTH).map(i => withClock(dma_free_clk) {RegNext(Mux(fifo_done_bus_en(i), 1.U, fifo_done_bus(i)) & !fifo_reset(i), 0.U)}).reverse.reduce(Cat(_,_))\n (0 until DMA_BUF_DEPTH).map(i => fifo_addr(i) := rvdffe(fifo_addr_in, fifo_cmd_en(i), clock, io.scan_mode))\n val fifo_sz = VecInit.tabulate(DMA_BUF_DEPTH)(i => withClock(dma_buffer_c1_clk) {RegEnable(fifo_sz_in(2,0), 0.U, fifo_cmd_en(i))})\n val fifo_byteen = VecInit.tabulate(DMA_BUF_DEPTH)(i =>withClock(dma_buffer_c1_clk) {RegEnable(fifo_byteen_in(7,0), 0.U, fifo_cmd_en(i).asBool())})\n val fifo_write = (0 until DMA_BUF_DEPTH).map(i => (withClock(dma_buffer_c1_clk) {RegEnable(fifo_write_in, 0.U, fifo_cmd_en(i))})).reverse.reduce(Cat(_,_))\n val fifo_posted_write = (0 until DMA_BUF_DEPTH).map(i => (withClock(dma_buffer_c1_clk) {RegEnable(fifo_posted_write_in, 0.U, fifo_cmd_en(i))})).reverse.reduce(Cat(_,_))\n val fifo_dbg = (0 until DMA_BUF_DEPTH).map(i => withClock(dma_buffer_c1_clk) {RegEnable(fifo_dbg_in, 0.U, fifo_cmd_en(i))}).reverse.reduce(Cat(_,_))\n\n val fifo_data = Wire(Vec(DMA_BUF_DEPTH,UInt(64.W)))\n (0 until DMA_BUF_DEPTH).map(i => fifo_data(i) := rvdffe(fifo_data_in(i), fifo_data_en(i), clock, io.scan_mode))\n val bus_cmd_tag = WireInit(UInt(DMA_BUS_TAG.W),0.U)\n val bus_cmd_mid = WireInit(UInt(DMA_BUS_ID.W),0.U)\n val bus_cmd_prty = WireInit(UInt(DMA_BUS_PRTY.W),0.U)\n val fifo_tag = VecInit.tabulate(DMA_BUF_DEPTH)(i =>withClock(dma_buffer_c1_clk) {RegEnable(bus_cmd_tag, 0.U, fifo_cmd_en(i))})\n val fifo_mid = VecInit.tabulate(DMA_BUF_DEPTH)(i =>withClock(dma_buffer_c1_clk) {RegEnable(bus_cmd_mid, 0.U, fifo_cmd_en(i))})\n val fifo_prty = VecInit.tabulate(DMA_BUF_DEPTH)(i =>withClock(dma_buffer_c1_clk) {RegEnable(bus_cmd_prty, 0.U, fifo_cmd_en(i))})\n\n // Pointer logic\n\n val NxtWrPtr = Mux((WrPtr === (DEPTH-1).U), 0.U, WrPtr+ 1.U)\n val NxtRdPtr = Mux((RdPtr === (DEPTH-1).U), 0.U, RdPtr+ 1.U)\n val NxtRspPtr = Mux((RspPtr === (DEPTH-1).U), 0.U, RspPtr + 1.U)\n\n val WrPtrEn = fifo_cmd_en.orR\n val RdPtrEn = io.lsu_dma.dma_lsc_ctl.dma_dccm_req | io.ifu_dma.dma_mem_ctl.dma_iccm_req | (dma_address_error | dma_alignment_error | dma_dbg_cmd_error)\n val RspPtrEn = (io.dma_dbg_cmd_done | (bus_rsp_sent | bus_posted_write_done) & io.dma_bus_clk_en)\n\n\n WrPtr := withClock(dma_free_clk) { RegEnable(NxtWrPtr, 0.U, WrPtrEn) }\n RdPtr := withClock(dma_free_clk) { RegEnable(NxtRdPtr, 0.U, RdPtrEn.asBool) }\n RspPtr := withClock(dma_free_clk) { RegEnable(NxtRspPtr, 0.U, RspPtrEn.asBool) }\n // Miscellaneous signals\n val fifo_full_spec_bus = WireInit(Bool(),0.B)\n val fifo_full = fifo_full_spec_bus\n\n val num_fifo_vld = Wire(Vec(DEPTH+1,UInt(4.W)))\n val dbg_dma_bubble_bus = WireInit(Bool(),0.B)\n num_fifo_vld(0) := Cat(0.U(3.W),bus_cmd_sent) - Cat(0.U(3.W),bus_rsp_sent)\n for (i <- 1 to DEPTH) { num_fifo_vld(i):= num_fifo_vld(i-1) + Cat(0.U(3.W),fifo_valid(i-1))}\n val fifo_full_spec = (num_fifo_vld(DEPTH) >= DEPTH.U)\n val dma_fifo_ready = ~(fifo_full | dbg_dma_bubble_bus)\n\n // Error logic\n val dma_mem_addr_in_dccm = WireInit(Bool(),0.B)\n val dma_mem_addr_in_iccm = WireInit(Bool(),0.B)\n val dma_mem_sz_int = WireInit(UInt(3.W),0.U)\n val dma_mem_addr_int = WireInit(UInt(32.W),0.U)\n val dma_mem_byteen = WireInit(UInt(8.W),0.U)\n dma_address_error := fifo_valid(RdPtr) & ~fifo_done(RdPtr) & ~fifo_dbg(RdPtr) & (~(dma_mem_addr_in_dccm | dma_mem_addr_in_iccm)) // request not for ICCM or DCCM\n\n dma_alignment_error := fifo_valid(RdPtr) & !fifo_done(RdPtr) & !fifo_dbg(RdPtr) & !dma_address_error &\n (((dma_mem_sz_int(2,0) === 1.U) & dma_mem_addr_int(0)) | // HW size but unaligned\n ((dma_mem_sz_int(2,0) === 2.U) & (dma_mem_addr_int(1, 0).orR)) | // W size but unaligned\n ((dma_mem_sz_int(2,0) === 3.U) & (dma_mem_addr_int(2, 0).orR)) | // DW size but unaligned\n (dma_mem_addr_in_iccm & ~((dma_mem_sz_int(1, 0) === 2.U) | (dma_mem_sz_int(1, 0) === 3.U)).asUInt ) | // ICCM access not word size\n (dma_mem_addr_in_dccm & io.lsu_dma.dma_lsc_ctl.dma_mem_write & ~((dma_mem_sz_int(1, 0) === 2.U) | (dma_mem_sz_int(1, 0) === 3.U)).asUInt) | // DCCM write not word size\n (io.lsu_dma.dma_lsc_ctl.dma_mem_write & (dma_mem_sz_int(2, 0) === 2.U) & (Mux1H(Seq((dma_mem_addr_int(2,0) === 0.U) -> (dma_mem_byteen(3,0)),\n (dma_mem_addr_int(2,0) === 1.U) -> (dma_mem_byteen(4,1)),\n (dma_mem_addr_int(2,0) === 2.U) -> (dma_mem_byteen(5,2)),\n (dma_mem_addr_int(2,0) === 3.U) -> (dma_mem_byteen(6,3)),\n (dma_mem_addr_int(2,0) === 4.U) -> (dma_mem_byteen(7,4)),\n (dma_mem_addr_int(2,0) === 5.U) -> (dma_mem_byteen(7,5)),\n (dma_mem_addr_int(2,0) === 6.U) -> (dma_mem_byteen(7,6)),\n (dma_mem_addr_int(2,0) === 7.U) -> (dma_mem_byteen(7)))) =/= \"hf\".U)) | // Write byte enables not aligned for word store\n (io.lsu_dma.dma_lsc_ctl.dma_mem_write & (dma_mem_sz_int(2, 0) === 3.U) & !((dma_mem_byteen(7,0) === \"h0f\".U) | (dma_mem_byteen(7,0) === \"hf0\".U) | (dma_mem_byteen(7,0) === \"hff\".U)))) // Write byte enables not aligned for dword store\n // Used to indicate ready to debug\n val fifo_empty = ~(fifo_valid.orR | bus_cmd_sent)\n\n //Dbg outputs\n io.dbg_dma.dma_dbg_ready := fifo_empty & io.dbg_dma.dbg_dma_bubble\n io.dma_dbg_cmd_done := (fifo_valid(RspPtr) & fifo_dbg(RspPtr) & fifo_done(RspPtr))\n io.dma_dbg_cmd_fail := fifo_error(RspPtr).orR\n\n val dma_dbg_sz = fifo_sz(RspPtr)(1,0)\n val dma_dbg_addr = fifo_addr(RspPtr)(1,0)\n val dma_dbg_mem_rddata = Mux(fifo_addr(RspPtr)(2), fifo_data(RspPtr)(63,32) , fifo_data(RspPtr)(31,0))\n io.dma_dbg_rddata := Mux1H(Seq(\n (dma_dbg_sz(1,0) === \"h0\".U(2.W)) -> ((dma_dbg_mem_rddata >> ((8.U)*dma_dbg_addr(1,0))) & \"hff\".U) ,\n (dma_dbg_sz(1,0) === \"h1\".U(2.W)) -> ((dma_dbg_mem_rddata >> ((16.U)*dma_dbg_addr(1))) & \"hffff\".U) ,\n (dma_dbg_sz(1,0) === \"h2\".U(2.W)) -> dma_dbg_mem_rddata))\n\n // PIC memory address check\n\n val dma_mem_addr_in_pic = rvrangecheck_ch(dma_mem_addr_int(31,0),aslong(PIC_BASE_ADDR).U,PIC_SIZE)._1\n val dma_mem_addr_in_pic_region_nc = rvrangecheck_ch(dma_mem_addr_int(31,0),aslong(PIC_BASE_ADDR).U,PIC_SIZE)._2\n\n dma_dbg_cmd_error := fifo_valid(RdPtr) & ~fifo_done(RdPtr) & fifo_dbg(RdPtr) &\n ((~(dma_mem_addr_in_dccm | dma_mem_addr_in_iccm | dma_mem_addr_in_pic)) | // Address outside of ICCM/DCCM/PIC\n ((dma_mem_addr_in_iccm | dma_mem_addr_in_pic) & (dma_mem_sz_int(1,0) =/= 2.U))) // Only word accesses allowed for ICCM/PIC\n\n dma_dbg_mem_wrdata := Mux1H(Seq(\n (io.dbg_cmd_size(1,0) === \"h0\".U(2.W)) -> Fill(4,io.dbg_dec_dma.dbg_dctl.dbg_cmd_wrdata(7,0)) ,\n (io.dbg_cmd_size(1,0) === \"h1\".U(2.W)) -> Fill(2,io.dbg_dec_dma.dbg_dctl.dbg_cmd_wrdata(15,0)),\n (io.dbg_cmd_size(1,0) === \"h2\".U(2.W)) -> io.dbg_dec_dma.dbg_dctl.dbg_cmd_wrdata ))\n\n // Block the decode if fifo full\n val dma_mem_req = WireInit(Bool(),0.B)\n val dma_nack_count = WireInit(UInt(3.W),0.U)\n val dma_nack_count_csr = WireInit(UInt(3.W),0.U)\n val dma_nack_count_d = WireInit(UInt(3.W),0.U)\n io.dec_dma.dctl_dma.dma_dccm_stall_any := dma_mem_req & (dma_mem_addr_in_dccm | dma_mem_addr_in_pic) & (dma_nack_count >= dma_nack_count_csr)\n io.dec_dma.tlu_dma.dma_dccm_stall_any := io.dec_dma.dctl_dma.dma_dccm_stall_any\n io.dec_dma.tlu_dma.dma_iccm_stall_any := dma_mem_req & dma_mem_addr_in_iccm & (dma_nack_count >= dma_nack_count_csr)\n io.ifu_dma.dma_ifc.dma_iccm_stall_any := io.dec_dma.tlu_dma.dma_iccm_stall_any\n // Nack counter, stall the lsu pipe if 7 nacks\n dma_nack_count_csr := io.dec_dma.tlu_dma.dec_tlu_dma_qos_prty\n dma_nack_count_d := Mux((dma_nack_count >= dma_nack_count_csr), (Fill(3,(!(io.lsu_dma.dma_lsc_ctl.dma_dccm_req | io.ifu_dma.dma_mem_ctl.dma_iccm_req))) & dma_nack_count),\n Mux((dma_mem_req & ~(io.lsu_dma.dma_lsc_ctl.dma_dccm_req | io.ifu_dma.dma_mem_ctl.dma_iccm_req)), (dma_nack_count + 1.U), 0.U(3.W)))\n dma_nack_count := withClock(dma_free_clk){RegEnable(dma_nack_count_d,0.U,dma_mem_req)}\n\n\n // Core outputs\n dma_mem_req := fifo_valid(RdPtr) & ~fifo_rpend(RdPtr) & ~fifo_done(RdPtr) & ~(dma_address_error | dma_alignment_error | dma_dbg_cmd_error)\n io.lsu_dma.dma_lsc_ctl.dma_dccm_req := dma_mem_req & (dma_mem_addr_in_dccm | dma_mem_addr_in_pic) & io.lsu_dma.dccm_ready\n io.ifu_dma.dma_mem_ctl.dma_iccm_req := dma_mem_req & dma_mem_addr_in_iccm & io.iccm_ready\n io.lsu_dma.dma_mem_tag := RdPtr\n io.ifu_dma.dma_mem_ctl.dma_mem_tag := io.lsu_dma.dma_mem_tag\n dma_mem_addr_int := fifo_addr(RdPtr)\n dma_mem_sz_int := fifo_sz(RdPtr)\n io.lsu_dma.dma_dccm_ctl.dma_mem_addr := Mux((io.lsu_dma.dma_lsc_ctl.dma_mem_write & ~fifo_dbg(RdPtr) & (dma_mem_byteen === \"hf0\".U(8.W))), Cat(dma_mem_addr_int(31,3),1.U,dma_mem_addr_int(1,0)), dma_mem_addr_int)\n io.lsu_dma.dma_lsc_ctl.dma_mem_addr := io.lsu_dma.dma_dccm_ctl.dma_mem_addr\n io.ifu_dma.dma_mem_ctl.dma_mem_addr := io.lsu_dma.dma_dccm_ctl.dma_mem_addr\n io.lsu_dma.dma_lsc_ctl.dma_mem_sz := Mux(io.lsu_dma.dma_lsc_ctl.dma_mem_write & ~fifo_dbg(RdPtr) & ((dma_mem_byteen === \"h0f\".U(8.W)) | (dma_mem_byteen === \"hf0\".U(8.W))), 2.U(3.W), dma_mem_sz_int)\n io.ifu_dma.dma_mem_ctl.dma_mem_sz := io.lsu_dma.dma_lsc_ctl.dma_mem_sz\n dma_mem_byteen := fifo_byteen(RdPtr)\n io.lsu_dma.dma_lsc_ctl.dma_mem_write := fifo_write(RdPtr)\n io.ifu_dma.dma_mem_ctl.dma_mem_write := io.lsu_dma.dma_lsc_ctl.dma_mem_write\n io.lsu_dma.dma_dccm_ctl.dma_mem_wdata := fifo_data(RdPtr)\n io.lsu_dma.dma_lsc_ctl.dma_mem_wdata := io.lsu_dma.dma_dccm_ctl.dma_mem_wdata\n io.ifu_dma.dma_mem_ctl.dma_mem_wdata := io.lsu_dma.dma_dccm_ctl.dma_mem_wdata\n\n // PMU outputs\n io.dec_dma.tlu_dma.dma_pmu_dccm_read := io.lsu_dma.dma_lsc_ctl.dma_dccm_req & ~io.lsu_dma.dma_lsc_ctl.dma_mem_write\n io.dec_dma.tlu_dma.dma_pmu_dccm_write := io.lsu_dma.dma_lsc_ctl.dma_dccm_req & io.lsu_dma.dma_lsc_ctl.dma_mem_write\n io.dec_dma.tlu_dma.dma_pmu_any_read := (io.lsu_dma.dma_lsc_ctl.dma_dccm_req | io.ifu_dma.dma_mem_ctl.dma_iccm_req) & ~io.lsu_dma.dma_lsc_ctl.dma_mem_write\n io.dec_dma.tlu_dma.dma_pmu_any_write := (io.lsu_dma.dma_lsc_ctl.dma_dccm_req | io.ifu_dma.dma_mem_ctl.dma_iccm_req) & io.lsu_dma.dma_lsc_ctl.dma_mem_write\n\n // Address check dccm\n val dma_mem_addr_in_dccm_region_nc = WireInit(Bool(),0.B)\n if (DCCM_ENABLE){\n dma_mem_addr_in_dccm := rvrangecheck_ch(dma_mem_addr_int(31,0),aslong(DCCM_SADR).U,DCCM_SIZE)._1\n dma_mem_addr_in_dccm_region_nc := rvrangecheck_ch(dma_mem_addr_int(31,0),aslong(DCCM_SADR).U,DCCM_SIZE)._2\n } else{\n dma_mem_addr_in_dccm := 0.U\n dma_mem_addr_in_dccm_region_nc := 0.U\n }\n\n\n // Address check iccm\n val dma_mem_addr_in_iccm_region_nc = WireInit(Bool(),0.B)\n if (ICCM_ENABLE) {\n dma_mem_addr_in_iccm := rvrangecheck_ch(dma_mem_addr_int(31,0),aslong(ICCM_SADR).U,ICCM_SIZE)._1\n dma_mem_addr_in_iccm_region_nc := rvrangecheck_ch(dma_mem_addr_int(31,0),aslong(ICCM_SADR).U,ICCM_SIZE)._2\n\n }else {\n dma_mem_addr_in_iccm := 0.U\n dma_mem_addr_in_iccm_region_nc := 0.U\n }\n\n\n val dma_bus_clk = Wire(Clock())\n if(RV_FPGA_OPTIMIZE) dma_bus_clk := 0.B.asClock()\n else dma_bus_clk := rvclkhdr(clock,io.dma_bus_clk_en,io.scan_mode)// dma_bus_cgc (.en(dma_bus_clk_en), .l1clk(dma_bus_clk), .*)\n\n // Inputs\n fifo_full_spec_bus := rvdff_fpga(fifo_full_spec,dma_bus_clk,io.dma_bus_clk_en,clock)\n dbg_dma_bubble_bus := rvdff_fpga(io.dbg_dma.dbg_dma_bubble,dma_bus_clk,io.dma_bus_clk_en,clock)\n dma_dbg_cmd_done_q := withClock(io.free_clk){ RegNext(io.dma_dbg_cmd_done,0.U)}\n\n // Write channel buffer\n val wrbuf_en = io.dma_axi.aw.valid & io.dma_axi.aw.ready\n val wrbuf_data_en = io.dma_axi.w.valid & io.dma_axi.w.ready\n val wrbuf_cmd_sent = bus_cmd_sent & bus_cmd_write\n val wrbuf_rst = wrbuf_cmd_sent & ~wrbuf_en\n val wrbuf_data_rst = wrbuf_cmd_sent & ~wrbuf_data_en\n\n val wrbuf_vld = rvdffsc_fpga(1.B,wrbuf_en,wrbuf_rst,dma_bus_clk,io.dma_bus_clk_en,clock)\n val wrbuf_data_vld = rvdffsc_fpga(1.B,wrbuf_data_en,wrbuf_data_rst,dma_bus_clk,io.dma_bus_clk_en,clock)\n val wrbuf_tag = rvdffs_fpga(io.dma_axi.aw.bits.id,wrbuf_en,dma_bus_clk,io.dma_bus_clk_en,clock)\n val wrbuf_sz = rvdffs_fpga(io.dma_axi.aw.bits.size,wrbuf_en,dma_bus_clk,io.dma_bus_clk_en,clock)\n val wrbuf_addr = rvdffe(io.dma_axi.aw.bits.addr,wrbuf_en & io.dma_bus_clk_en,clock,io.scan_mode)\n val wrbuf_data = rvdffe(io.dma_axi.w.bits.data,wrbuf_data_en & io.dma_bus_clk_en,clock,io.scan_mode)\n val wrbuf_byteen = rvdffs_fpga(io.dma_axi.w.bits.strb,wrbuf_data_en,dma_bus_clk,io.dma_bus_clk_en,clock)\n\n // Read channel buffer\n val rdbuf_en = io.dma_axi.ar.valid & io.dma_axi.ar.ready\n val rdbuf_cmd_sent = bus_cmd_sent & ~bus_cmd_write\n val rdbuf_rst = rdbuf_cmd_sent & ~rdbuf_en\n\n val rdbuf_vld = rvdffsc_fpga(1.B,rdbuf_en,rdbuf_rst,dma_bus_clk,io.dma_bus_clk_en,clock)\n val rdbuf_tag = rvdffs_fpga(io.dma_axi.ar.bits.id,rdbuf_en,dma_bus_clk,io.dma_bus_clk_en,clock)\n val rdbuf_sz = rvdffs_fpga(io.dma_axi.ar.bits.size,rdbuf_en,dma_bus_clk,io.dma_bus_clk_en,clock)\n val rdbuf_addr = rvdffe(io.dma_axi.ar.bits.addr,rdbuf_en & io.dma_bus_clk_en,clock,io.scan_mode)\n\n io.dma_axi.aw.ready := ~(wrbuf_vld & ~wrbuf_cmd_sent)\n io.dma_axi.w.ready := ~(wrbuf_data_vld & ~wrbuf_cmd_sent)\n io.dma_axi.ar.ready := ~(rdbuf_vld & ~rdbuf_cmd_sent)\n\n //Generate a single request from read/write channel\n val axi_mstr_sel = WireInit(Bool(),0.B)\n bus_cmd_valid := (wrbuf_vld & wrbuf_data_vld) | rdbuf_vld\n bus_cmd_sent := bus_cmd_valid & dma_fifo_ready\n bus_cmd_write := axi_mstr_sel\n bus_cmd_posted_write := 0.U\n bus_cmd_addr := Mux(axi_mstr_sel, wrbuf_addr, rdbuf_addr)\n bus_cmd_sz := Mux(axi_mstr_sel, wrbuf_sz, rdbuf_sz)\n bus_cmd_wdata := wrbuf_data\n bus_cmd_byteen := wrbuf_byteen\n bus_cmd_tag := Mux(axi_mstr_sel, wrbuf_tag, rdbuf_tag)\n bus_cmd_mid := 0.U\n bus_cmd_prty := 0.U\n\n // Sel=1 -> write has higher priority\n val axi_mstr_priority = WireInit(Bool(),0.B)\n axi_mstr_sel := Mux(((wrbuf_vld & wrbuf_data_vld & rdbuf_vld)===1.U).asBool(), axi_mstr_priority, (wrbuf_vld & wrbuf_data_vld) )\n val axi_mstr_prty_in = ~axi_mstr_priority\n val axi_mstr_prty_en = bus_cmd_sent\n axi_mstr_priority := rvdffs_fpga(axi_mstr_prty_in.asUInt(),axi_mstr_prty_en,dma_bus_clk,io.dma_bus_clk_en,clock)\n\n val axi_rsp_valid = fifo_valid(RspPtr) & ~fifo_dbg(RspPtr) & fifo_done_bus(RspPtr)\n val axi_rsp_rdata = fifo_data(RspPtr)\n val axi_rsp_write = fifo_write(RspPtr)\n val axi_rsp_error = Mux(fifo_error(RspPtr)(0), 2.U,Mux(fifo_error(RspPtr)(1), 3.U, 0.U))\n val axi_rsp_tag = fifo_tag(RspPtr)\n\n // AXI response channel signals\n io.dma_axi.b.valid := axi_rsp_valid & axi_rsp_write\n io.dma_axi.b.bits.resp := axi_rsp_error\n io.dma_axi.b.bits.id := axi_rsp_tag\n\n io.dma_axi.r.valid := axi_rsp_valid & ~axi_rsp_write\n io.dma_axi.r.bits.resp := axi_rsp_error\n io.dma_axi.r.bits.data := axi_rsp_rdata\n io.dma_axi.r.bits.last := 1.U\n io.dma_axi.r.bits.id := axi_rsp_tag\n\n bus_posted_write_done := 0.U\n bus_rsp_valid := (io.dma_axi.b.valid | io.dma_axi.r.valid)\n bus_rsp_sent := (io.dma_axi.b.valid & io.dma_axi.b.ready) | (io.dma_axi.r.valid & io.dma_axi.r.ready)\n\n io.dma_active := wrbuf_vld | rdbuf_vld | (fifo_valid.orR)\n\n}\nobject DMA extends App {\n println((new chisel3.stage.ChiselStage).emitVerilog(new dma_ctrl))\n}\n", "groundtruth": " fifo_error_bus := (0 until DMA_BUF_DEPTH).map(i => withClock(dma_free_clk) {RegNext(Mux(fifo_error_bus_en(i), 1.U, fifo_error_bus(i)) & !fifo_reset(i), 0.U)}).reverse.reduce(Cat(_,_))\n", "crossfile_context": ""}
{"task_id": "Quasar", "path": "Quasar/design/src/main/scala/dmi/dmi_wrapper.scala", "left_context": "package dmi\nimport chisel3._\nimport chisel3.util._\nimport lib._\n\nclass dmi_wrapper extends BlackBox with HasBlackBoxResource{\n val io = IO(new Bundle{\n val trst_n = Input(Bool())\n val tck = Input(Clock())\n val tms = Input(UInt(1.W))\n val tdi = Input(UInt(1.W))\n val tdo = Output(UInt(1.W))\n val tdoEnable = Output(UInt(1.W))\n val core_rst_n = Input(AsyncReset())\n val core_clk = Input(Clock())\n val jtag_id = Input(UInt(31.W))\n val rd_data = Input(UInt(32.W))\n val reg_wr_data = Output(UInt(32.W))\n val reg_wr_addr = Output(UInt(7.W))\n val reg_en = Output(UInt(1.W))\n val reg_wr_en = Output(UInt(1.W))\n val dmi_hard_reset = Output(UInt(1.W))\n })\n addResource(\"/vsrc/dmi_wrapper.sv\")\n}\nclass dmi_wrapper_module extends Module{\n val io = IO(new Bundle{\n val trst_n = Input(Bool())\n val tck = Input(Clock())\n val tms = Input(UInt(1.W))\n val tdi = Input(UInt(1.W))\n val tdo = Output(UInt(1.W))\n val tdoEnable = Output(UInt(1.W))\n val core_rst_n = Input(AsyncReset())\n val core_clk = Input(Clock())\n val jtag_id = Input(UInt(32.W))\n val rd_data = Input(UInt(32.W))\n val reg_wr_data = Output(UInt(32.W))\n", "right_context": " //addResource(\"/vsrc/dmi_wrapper.v\")\n val dwrap = Module(new dmi_wrapper)\n dwrap.io <> io\n}\n\n", "groundtruth": " val reg_wr_addr = Output(UInt(7.W))\n val reg_en = Output(UInt(1.W))\n val reg_wr_en = Output(UInt(1.W))\n", "crossfile_context": ""}
{"task_id": "Quasar", "path": "Quasar/design/src/main/scala/exu/exu.scala", "left_context": "package exu\nimport chisel3._\n\nimport scala.collection._\nimport chisel3.util._\nimport include._\nimport lib._\nimport chisel3.experimental.chiselName\n\n@chiselName\nclass exu extends Module with lib with RequireAsyncReset{\n val io=IO(new Bundle{\n\n val\t\tscan_mode\t\t\t\t = Input(Bool()) // Scan control\n val dec_exu = new dec_exu()\n val exu_bp = new exu_bp()\n //ifc-bp-mem-aln-decode\n val exu_flush_final = Output(UInt(1.W)) // Branch flush or flush entire pipeline\n //gpr\n val\t\texu_div_result\t\t\t = Output(UInt(32.W)) // Divide result\n", "right_context": " val \tdec_csr_rddata_d\t\t\t = Input(UInt(32.W))\n val \tlsu_nonblock_load_data\t= Input(UInt(32.W))\n //lsu\n val lsu_exu = Flipped(new lsu_exu())\n //ifu_ifc\n val\t\texu_flush_path_final\t= Output(UInt(31.W)) // Target for the oldest flush source\n })\n\n val PREDPIPESIZE \t\t\t = BTB_ADDR_HI - BTB_ADDR_LO + BHT_GHR_SIZE + BTB_BTAG_SIZE +1\n val ghr_x_ns \t\t\t\t = Wire(UInt(BHT_GHR_SIZE.W))\n val ghr_d_ns \t\t\t\t = Wire(UInt(BHT_GHR_SIZE.W))\n val ghr_d\t \t\t\t\t = Wire(UInt(BHT_GHR_SIZE.W))\n val i0_taken_d\t\t\t\t = Wire(UInt(1.W))\n val mul_valid_x\t\t\t\t = Wire(UInt(1.W))\n val i0_valid_d\t\t\t\t = Wire(UInt(1.W))\n val i0_branch_x = Wire(UInt(1.W))\n val i0_predict_newp_d \t\t = Wire(Valid(new predict_pkt_t()))\n val i0_flush_path_d\t\t\t = Wire(UInt(31.W))\n val i0_predict_p_d\t\t\t = Wire(Valid(new predict_pkt_t()))\n val i0_pp_r\t\t\t\t\t = Wire(Valid(new predict_pkt_t()))\n val i0_predict_p_x\t\t\t = Wire(Valid(new predict_pkt_t()))\n val final_predict_mp\t\t = Wire(Valid(new predict_pkt_t()))\n val pred_correct_npc_r\t\t = Wire(UInt(32.W))\n val i0_pred_correct_upper_d\t = Wire(UInt(1.W))\n val i0_flush_upper_d\t\t = Wire(UInt(1.W))\n io.exu_bp.exu_mp_pkt.bits.prett\t\t\t:=0.U\n io.exu_bp.exu_mp_pkt.bits.br_start_error :=0.U\n io.exu_bp.exu_mp_pkt.bits.br_error := 0.U\n io.exu_bp.exu_mp_pkt.valid\t\t\t := 0.U\n i0_pp_r.bits.toffset := 0.U\n\n val x_data_en = io.dec_exu.decode_exu.dec_data_en(1)\n val x_data_en_q1 = io.dec_exu.decode_exu.dec_data_en(1) & io.dec_exu.dec_alu.dec_csr_ren_d\n val x_data_en_q2 = io.dec_exu.decode_exu.dec_data_en(1) & io.dec_exu.decode_exu.dec_i0_branch_d\n val r_data_en = io.dec_exu.decode_exu.dec_data_en(0)\n val r_data_en_q2 = io.dec_exu.decode_exu.dec_data_en(0) & i0_branch_x\n val x_ctl_en = io.dec_exu.decode_exu.dec_ctl_en(1)\n val r_ctl_en = io.dec_exu.decode_exu.dec_ctl_en(0)\n val predpipe_d = Cat(io.dec_exu.decode_exu.i0_predict_fghr_d, io.dec_exu.decode_exu.i0_predict_index_d, io.dec_exu.decode_exu.i0_predict_btag_d)\n\n val i0_flush_path_x \t =rvdffpcie(i0_flush_path_d,x_data_en.asBool,reset.asAsyncReset,clock,io.scan_mode)\n i0_predict_p_x\t\t\t\t :=rvdffppe(i0_predict_p_d,clock,reset.asAsyncReset,x_data_en.asBool,io.scan_mode,elements= 13,io.exu_bp.exu_mp_pkt.bits.pret)\n val predpipe_x \t\t \t =rvdffe(predpipe_d,x_data_en_q2.asBool,clock,io.scan_mode)\n val predpipe_r\t\t\t \t =rvdffe(predpipe_x ,r_data_en_q2.asBool,clock,io.scan_mode)\n val ghr_x\t\t\t\t\t =rvdffe(ghr_x_ns ,x_ctl_en.asBool,clock,io.scan_mode)\n val i0_pred_correct_upper_x\t=rvdffe(i0_pred_correct_upper_d ,x_ctl_en.asBool,clock,io.scan_mode)\n val i0_flush_upper_x\t =rvdffe(i0_flush_upper_d ,x_ctl_en.asBool,clock,io.scan_mode)\n val i0_taken_x\t\t\t\t =rvdffe(i0_taken_d ,x_ctl_en.asBool,clock,io.scan_mode)\n val i0_valid_x\t\t\t\t =rvdffe(i0_valid_d ,x_ctl_en.asBool,clock,io.scan_mode)\n i0_pp_r :=rvdffppe(i0_predict_p_x,clock,reset.asAsyncReset(),r_ctl_en.asBool,io.scan_mode,elements = 13,io.exu_bp.exu_mp_pkt.bits.pret)\n val pred_temp1\t\t =rvdffpcie(io.dec_exu.decode_exu.pred_correct_npc_x(5,0) ,r_data_en.asBool,reset.asAsyncReset(),clock,io.scan_mode)\n val i0_pred_correct_upper_r\t=rvdffppe_UInt(i0_pred_correct_upper_x ,clock,reset.asAsyncReset(),r_ctl_en.asBool,io.scan_mode,WIDTH=1)\n val i0_flush_path_upper_r\t =rvdffpcie(i0_flush_path_x ,r_data_en.asBool,reset.asAsyncReset(),clock,io.scan_mode)\n val pred_temp2\t\t\t\t =rvdffpcie(io.dec_exu.decode_exu.pred_correct_npc_x(30,6) ,r_data_en.asBool,reset.asAsyncReset(),clock,io.scan_mode)\n pred_correct_npc_r\t\t\t :=Cat(pred_temp2,pred_temp1)\n ghr_d\t\t\t :=rvdffie(ghr_d_ns,clock,reset.asAsyncReset(),io.scan_mode)\n mul_valid_x\t\t :=rvdffie(io.dec_exu.decode_exu.mul_p.valid,clock,reset.asAsyncReset(),io.scan_mode)\n i0_branch_x\t\t :=rvdffie(io.dec_exu.decode_exu.dec_i0_branch_d,clock,reset.asAsyncReset(),io.scan_mode)\n\n val i0_rs1_bypass_en_d = io.dec_exu.decode_exu.dec_i0_rs1_bypass_en_d(0) | io.dec_exu.decode_exu.dec_i0_rs1_bypass_en_d(1) | io.dec_exu.decode_exu.dec_i0_rs1_bypass_en_d(2) | io.dec_exu.decode_exu.dec_i0_rs1_bypass_en_d(3)\n val i0_rs2_bypass_en_d = io.dec_exu.decode_exu.dec_i0_rs2_bypass_en_d(0) | io.dec_exu.decode_exu.dec_i0_rs2_bypass_en_d(1) | io.dec_exu.decode_exu.dec_i0_rs2_bypass_en_d(2) | io.dec_exu.decode_exu.dec_i0_rs2_bypass_en_d(3)\n\n val i0_rs1_bypass_data_d =\tMux1H(Seq(\n io.dec_exu.decode_exu.dec_i0_rs1_bypass_en_d(0).asBool\t\t\t\t\t\t-> io.dec_exu.decode_exu.dec_i0_result_r,\n io.dec_exu.decode_exu.dec_i0_rs1_bypass_en_d(1).asBool \t\t\t\t\t\t-> io.lsu_exu.lsu_result_m,\n io.dec_exu.decode_exu.dec_i0_rs1_bypass_en_d(2).asBool\t\t\t\t\t\t-> io.dec_exu.decode_exu.exu_i0_result_x,\n io.dec_exu.decode_exu.dec_i0_rs1_bypass_en_d(3).asBool \t\t\t\t\t\t-> io.lsu_nonblock_load_data\n ))\n val i0_rs2_bypass_data_d =\tMux1H(Seq(\n io.dec_exu.decode_exu.dec_i0_rs2_bypass_en_d(0).asBool\t\t\t\t\t\t-> io.dec_exu.decode_exu.dec_i0_result_r,\n io.dec_exu.decode_exu.dec_i0_rs2_bypass_en_d(1).asBool \t\t\t\t\t\t-> io.lsu_exu.lsu_result_m,\n io.dec_exu.decode_exu.dec_i0_rs2_bypass_en_d(2).asBool\t\t\t\t\t\t-> io.dec_exu.decode_exu.exu_i0_result_x,\n io.dec_exu.decode_exu.dec_i0_rs2_bypass_en_d(3).asBool \t\t\t\t\t\t-> io.lsu_nonblock_load_data\n ))\n\n val i0_rs1_d = Mux1H(Seq(\n i0_rs1_bypass_en_d.asBool \t\t\t\t\t\t\t\t\t\t\t\t\t\t -> i0_rs1_bypass_data_d,\n (!i0_rs1_bypass_en_d & io.dec_exu.decode_exu.dec_i0_select_pc_d).asBool \t\t-> Cat(io.dec_exu.ib_exu.dec_i0_pc_d,0.U(1.W)),\n (!i0_rs1_bypass_en_d & io.dec_exu.ib_exu.dec_debug_wdata_rs1_d).asBool \t\t-> io.dbg_cmd_wrdata,\n (!i0_rs1_bypass_en_d & !io.dec_exu.ib_exu.dec_debug_wdata_rs1_d & io.dec_exu.decode_exu.dec_i0_rs1_en_d).asBool \t-> io.dec_exu.gpr_exu.gpr_i0_rs1_d\n ))\n io.dec_exu.decode_exu.exu_csr_rs1_x\t\t\t:=rvdffe(i0_rs1_d,x_data_en_q1.asBool,clock,io.scan_mode)\n\n val i0_rs2_d = Mux1H(Seq(\n (!i0_rs2_bypass_en_d & io.dec_exu.decode_exu.dec_i0_rs2_en_d).asBool \t-> io.dec_exu.gpr_exu.gpr_i0_rs2_d,\n (!i0_rs2_bypass_en_d).asBool\t\t\t\t\t\t -> io.dec_exu.decode_exu.dec_i0_immed_d,\n (i0_rs2_bypass_en_d).asBool\t\t\t\t\t\t\t -> i0_rs2_bypass_data_d\n ))\n dontTouch(i0_rs2_d)\n\n io.lsu_exu.exu_lsu_rs1_d:=Mux1H(Seq(\n (!i0_rs1_bypass_en_d & !io.dec_exu.decode_exu.dec_extint_stall & io.dec_exu.decode_exu.dec_i0_rs1_en_d & io.dec_exu.decode_exu.dec_qual_lsu_d).asBool\t \t-> io.dec_exu.gpr_exu.gpr_i0_rs1_d,\n (i0_rs1_bypass_en_d & !io.dec_exu.decode_exu.dec_extint_stall & io.dec_exu.decode_exu.dec_qual_lsu_d).asBool\t\t-> i0_rs1_bypass_data_d,\n (io.dec_exu.decode_exu.dec_extint_stall & io.dec_exu.decode_exu.dec_qual_lsu_d).asBool\t\t\t\t\t\t\t\t\t\t\t\t\t-> Cat(io.dec_exu.tlu_exu.dec_tlu_meihap,0.U(2.W))\n ))\n\n io.lsu_exu.exu_lsu_rs2_d:=Mux1H(Seq(\n (!i0_rs2_bypass_en_d & !io.dec_exu.decode_exu.dec_extint_stall & io.dec_exu.decode_exu.dec_i0_rs2_en_d & io.dec_exu.decode_exu.dec_qual_lsu_d).asBool \t-> io.dec_exu.gpr_exu.gpr_i0_rs2_d,\n (i0_rs2_bypass_en_d & !io.dec_exu.decode_exu.dec_extint_stall & io.dec_exu.decode_exu.dec_qual_lsu_d).asBool\t\t\t\t\t\t\t-> i0_rs2_bypass_data_d\n ))\n\n val muldiv_rs1_d=Mux1H(Seq(\n (!i0_rs1_bypass_en_d & io.dec_exu.decode_exu.dec_i0_rs1_en_d).asBool\t\t-> io.dec_exu.gpr_exu.gpr_i0_rs1_d,\n (i0_rs1_bypass_en_d).asBool\t\t\t\t\t\t\t\t -> i0_rs1_bypass_data_d\n ))\n\n val i_alu=Module(new exu_alu_ctl())\n i_alu.io.dec_alu <> io.dec_exu.dec_alu\n\n i_alu.io.scan_mode\t\t :=io.scan_mode\n i_alu.io.enable\t\t\t :=x_data_en\n i_alu.io.pp_in\t\t\t :=i0_predict_newp_d\n i_alu.io.flush_upper_x\t:=i0_flush_upper_x\n i_alu.io.csr_rddata_in\t:=io.dec_csr_rddata_d\n i_alu.io.dec_tlu_flush_lower_r\t:=io.dec_exu.tlu_exu.dec_tlu_flush_lower_r\n i_alu.io.a_in\t\t\t :=i0_rs1_d.asSInt\n i_alu.io.b_in\t\t\t :=i0_rs2_d\n i_alu.io.dec_i0_pc_d\t\t:=io.dec_exu.ib_exu.dec_i0_pc_d\n i_alu.io.i0_ap\t\t\t\t :=io.dec_exu.decode_exu.i0_ap\n val alu_result_x \t\t =i_alu.io.result_ff\n i0_flush_upper_d \t\t :=i_alu.io.flush_upper_out\n i0_flush_path_d\t\t\t :=i_alu.io.flush_path_out\n io.exu_flush_final := i_alu.io.flush_final_out\n i0_predict_p_d\t\t\t :=i_alu.io.predict_p_out\n i0_pred_correct_upper_d :=i_alu.io.pred_correct_out\n\n val i_mul = Module(new exu_mul_ctl())\n i_mul.io.scan_mode\t:= io.scan_mode\n i_mul.io.mul_p := io.dec_exu.decode_exu.mul_p\n //i_mul.io.mul_p\t:= VecInit.tabulate(io.dec_exu.decode_exu.mul_p.getElements.size-1)(i=>io.dec_exu.decode_exu.mul_p.getElements(i).asUInt & Fill(io.dec_exu.decode_exu.mul_p.getElements.size,io.dec_exu.decode_exu.mul_p.valid)).asTypeOf(io.dec_exu.decode_exu.mul_p) //& io.dec_exu.decode_exu.mul_p.valid\n i_mul.io.rs1_in\t\t\t:= muldiv_rs1_d & Fill(32,io.dec_exu.decode_exu.mul_p.valid)\n i_mul.io.rs2_in\t\t\t:= i0_rs2_d & Fill(32,io.dec_exu.decode_exu.mul_p.valid)\n val mul_result_x\t\t= i_mul.io.result_x\n\n val i_div = Module(new exu_div_ctl())\n i_div.io.dec_div <> io.dec_exu.dec_div\n i_div.io.scan_mode\t:= io.scan_mode\n i_div.io.dividend\t\t:= muldiv_rs1_d\n i_div.io.divisor\t\t:= i0_rs2_d\n io.exu_div_wren\t\t\t:= i_div.io.exu_div_wren\n io.exu_div_result\t\t:= i_div.io.exu_div_result\n\n io.dec_exu.decode_exu.exu_i0_result_x \t\t:= Mux(mul_valid_x.asBool, mul_result_x, alu_result_x)\n i0_predict_newp_d := io.dec_exu.decode_exu.dec_i0_predict_p_d\n i0_predict_newp_d.bits.boffset := io.dec_exu.ib_exu.dec_i0_pc_d(0) // from the start of inst\n\n io.dec_exu.tlu_exu.exu_pmu_i0_br_misp := i0_pp_r.bits.misp\n io.dec_exu.tlu_exu.exu_pmu_i0_br_ataken := i0_pp_r.bits.ataken\n io.dec_exu.tlu_exu.exu_pmu_i0_pc4 := i0_pp_r.bits.pc4\n\n\n i0_valid_d := i0_predict_p_d.valid & io.dec_exu.dec_alu.dec_i0_alu_decode_d & !io.dec_exu.tlu_exu.dec_tlu_flush_lower_r\n i0_taken_d := (i0_predict_p_d.bits.ataken & io.dec_exu.dec_alu.dec_i0_alu_decode_d)\n\n\n if(BTB_ENABLE) {\n // maintain GHR at D\n ghr_d_ns := Mux1H(Seq(\n (!io.dec_exu.tlu_exu.dec_tlu_flush_lower_r & i0_valid_d).asBool -> Cat(ghr_d(BHT_GHR_SIZE - 2, 0), i0_taken_d),\n (!io.dec_exu.tlu_exu.dec_tlu_flush_lower_r & !i0_valid_d).asBool -> ghr_d,\n (io.dec_exu.tlu_exu.dec_tlu_flush_lower_r).asBool -> ghr_x\n ))\n\n // maintain GHR at X\n ghr_x_ns := Mux(i0_valid_x === 1.U, Cat(ghr_x(BHT_GHR_SIZE - 2, 0), i0_taken_x), ghr_x)\n\n io.dec_exu.tlu_exu.exu_i0_br_valid_r := i0_pp_r.valid\n io.dec_exu.tlu_exu.exu_i0_br_mp_r := i0_pp_r.bits.misp\n io.exu_bp.exu_i0_br_way_r := i0_pp_r.bits.way\n io.dec_exu.tlu_exu.exu_i0_br_hist_r := Fill(2, i0_pp_r.valid) & i0_pp_r.bits.hist\n io.dec_exu.tlu_exu.exu_i0_br_error_r := i0_pp_r.bits.br_error\n io.dec_exu.tlu_exu.exu_i0_br_middle_r := i0_pp_r.bits.pc4 ^ i0_pp_r.bits.boffset\n io.dec_exu.tlu_exu.exu_i0_br_start_error_r := i0_pp_r.bits.br_start_error\n io.exu_bp.exu_i0_br_fghr_r := predpipe_r(PREDPIPESIZE - 1, BTB_ADDR_HI + BTB_BTAG_SIZE - BTB_ADDR_LO + 1)\n io.dec_exu.tlu_exu.exu_i0_br_index_r := predpipe_r(BTB_ADDR_HI + BTB_BTAG_SIZE - BTB_ADDR_LO, BTB_BTAG_SIZE)\n io.exu_bp.exu_i0_br_index_r := io.dec_exu.tlu_exu.exu_i0_br_index_r\n final_predict_mp := Mux(i0_flush_upper_x === 1.U, i0_predict_p_x, 0.U.asTypeOf(i0_predict_p_x))\n val final_predpipe_mp = Mux(i0_flush_upper_x === 1.U, predpipe_x, 0.U)\n\n val after_flush_eghr = Mux((i0_flush_upper_x === 1.U & !(io.dec_exu.tlu_exu.dec_tlu_flush_lower_r === 1.U)), ghr_d, ghr_x)\n\n io.exu_bp.exu_mp_pkt.valid := final_predict_mp.valid\n io.exu_bp.exu_mp_pkt.bits.way := final_predict_mp.bits.way\n io.exu_bp.exu_mp_pkt.bits.misp := final_predict_mp.bits.misp\n io.exu_bp.exu_mp_pkt.bits.pcall := final_predict_mp.bits.pcall\n io.exu_bp.exu_mp_pkt.bits.pja := final_predict_mp.bits.pja\n io.exu_bp.exu_mp_pkt.bits.pret := final_predict_mp.bits.pret\n io.exu_bp.exu_mp_pkt.bits.ataken := final_predict_mp.bits.ataken\n io.exu_bp.exu_mp_pkt.bits.boffset := final_predict_mp.bits.boffset\n io.exu_bp.exu_mp_pkt.bits.pc4 := final_predict_mp.bits.pc4\n io.exu_bp.exu_mp_pkt.bits.hist := final_predict_mp.bits.hist(1, 0)\n io.exu_bp.exu_mp_pkt.bits.toffset := final_predict_mp.bits.toffset(11, 0)\n io.exu_bp.exu_mp_fghr := after_flush_eghr\n io.exu_bp.exu_mp_index := final_predpipe_mp(PREDPIPESIZE - BHT_GHR_SIZE - 1, BTB_BTAG_SIZE)\n io.exu_bp.exu_mp_btag := final_predpipe_mp(BTB_BTAG_SIZE - 1, 0)\n io.exu_bp.exu_mp_eghr := final_predpipe_mp(PREDPIPESIZE - 1, BTB_ADDR_HI - BTB_ADDR_LO + BTB_BTAG_SIZE + 1) // mp ghr for bht write\n }\n else {\n\n ghr_d_ns := 0.U\n ghr_x_ns := 0.U\n io.exu_bp.exu_mp_pkt := 0.U\n io.exu_bp.exu_mp_eghr := 0.U\n io.exu_bp.exu_mp_fghr := 0.U\n io.exu_bp.exu_mp_index := 0.U\n io.exu_bp.exu_mp_btag := 0.U\n io.dec_exu.tlu_exu.exu_i0_br_hist_r := 0.U\n io.dec_exu.tlu_exu.exu_i0_br_error_r := 0.U\n io.dec_exu.tlu_exu.exu_i0_br_start_error_r := 0.U\n io.dec_exu.tlu_exu.exu_i0_br_index_r := 0.U\n io.dec_exu.tlu_exu.exu_i0_br_valid_r := 0.U\n io.dec_exu.tlu_exu.exu_i0_br_mp_r := 0.U\n io.dec_exu.tlu_exu.exu_i0_br_middle_r := 0.U\n io.exu_bp.exu_i0_br_fghr_r := 0.U\n io.exu_bp.exu_i0_br_way_r := 0.U\n }\n io.exu_flush_path_final\t:= Mux1H(Seq(\n io.dec_exu.tlu_exu.dec_tlu_flush_lower_r.asBool -> io.dec_exu.tlu_exu.dec_tlu_flush_path_r,\n (~io.dec_exu.tlu_exu.dec_tlu_flush_lower_r & i0_flush_upper_d).asBool -> i0_flush_path_d))\n\n io.dec_exu.tlu_exu.exu_npc_r\t\t\t:= Mux(i0_pred_correct_upper_r===1.U, pred_correct_npc_r, i0_flush_path_upper_r)\n}\nobject exu_main extends App {\n println((new chisel3.stage.ChiselStage).emitVerilog(new exu()))\n}\n", "groundtruth": " val\t\texu_div_wren\t\t\t = Output(UInt(1.W)) // Divide write enable to GPR\n //debug\n", "crossfile_context": ""}
{"task_id": "Quasar", "path": "Quasar/design/src/main/scala/exu/exu_div_ctl.scala", "left_context": "package exu\n\nimport chisel3.{util, _}\nimport chisel3.experimental.chiselName\nimport chisel3.util._\nimport include._\nimport lib._\n\n@chiselName\nclass exu_div_ctl extends Module with RequireAsyncReset with lib {\n val io = IO(new Bundle {\n val scan_mode = Input(Bool())\n val dividend = Input(UInt(32.W))\n val divisor = Input(UInt(32.W))\n val exu_div_result = Output(UInt(32.W))\n val exu_div_wren = Output(UInt(1.W))\n val dec_div = new dec_div()\n })\n\n val out_raw =WireInit(0.U(32.W))\n io.exu_div_result := Fill(32,io.exu_div_wren) & out_raw\nif(!DIV_NEW) {\n val divider_old = Module(new exu_div_existing_1bit_cheapshortq())\n divider_old.io.scan_mode := io.scan_mode\n divider_old.io.cancel := io.dec_div.dec_div_cancel\n divider_old.io.valid_in := io.dec_div.div_p.valid\n divider_old.io.signed_in := ~io.dec_div.div_p.bits.unsign\n divider_old.io.rem_in := io.dec_div.div_p.bits.rem\n divider_old.io.dividend_in := io.dividend\n divider_old.io.divisor_in := io.divisor\n out_raw := divider_old.io.data_out\n io.exu_div_wren := divider_old.io.valid_out\n}\n if(DIV_NEW & DIV_BIT==1) {\n val divider_new1 = Module(new exu_div_new_1bit_fullshortq())\n divider_new1.io.scan_mode := io.scan_mode\n divider_new1.io.cancel := io.dec_div.dec_div_cancel\n divider_new1.io.valid_in := io.dec_div.div_p.valid\n divider_new1.io.signed_in := ~io.dec_div.div_p.bits.unsign\n divider_new1.io.rem_in := io.dec_div.div_p.bits.rem\n divider_new1.io.dividend_in := io.dividend\n divider_new1.io.divisor_in := io.divisor\n out_raw := divider_new1.io.data_out\n io.exu_div_wren := divider_new1.io.valid_out\n }\n if(DIV_NEW & DIV_BIT==2) {\n val divider_new2 = Module(new exu_div_new_2bit_fullshortq())\n divider_new2.io.scan_mode := io.scan_mode\n divider_new2.io.cancel := io.dec_div.dec_div_cancel\n divider_new2.io.valid_in := io.dec_div.div_p.valid\n divider_new2.io.signed_in := ~io.dec_div.div_p.bits.unsign\n divider_new2.io.rem_in := io.dec_div.div_p.bits.rem\n divider_new2.io.dividend_in := io.dividend\n divider_new2.io.divisor_in := io.divisor\n out_raw := divider_new2.io.data_out\n io.exu_div_wren := divider_new2.io.valid_out\n }\n if(DIV_NEW & DIV_BIT==3) {\n val divider_new3 = Module(new exu_div_new_3bit_fullshortq())\n divider_new3.io.scan_mode := io.scan_mode\n divider_new3.io.cancel := io.dec_div.dec_div_cancel\n divider_new3.io.valid_in := io.dec_div.div_p.valid\n divider_new3.io.signed_in := ~io.dec_div.div_p.bits.unsign\n divider_new3.io.rem_in := io.dec_div.div_p.bits.rem\n divider_new3.io.dividend_in := io.dividend\n divider_new3.io.divisor_in := io.divisor\n out_raw := divider_new3.io.data_out\n io.exu_div_wren := divider_new3.io.valid_out\n }\n if(DIV_NEW & DIV_BIT==4) {\n val divider_new4 = Module(new exu_div_new_4bit_fullshortq())\n divider_new4.io.scan_mode := io.scan_mode\n divider_new4.io.cancel := io.dec_div.dec_div_cancel\n divider_new4.io.valid_in := io.dec_div.div_p.valid\n divider_new4.io.signed_in := ~io.dec_div.div_p.bits.unsign\n divider_new4.io.rem_in := io.dec_div.div_p.bits.rem\n divider_new4.io.dividend_in := io.dividend\n divider_new4.io.divisor_in := io.divisor\n out_raw := divider_new4.io.data_out\n io.exu_div_wren := divider_new4.io.valid_out\n }\n}\nobject div_main extends App {\n println((new chisel3.stage.ChiselStage).emitVerilog(new exu_div_ctl()))\n}\n////////////////////////////////////////// OLD DIVIDER /////////////////////////////////////\nclass exu_div_existing_1bit_cheapshortq extends Module with RequireAsyncReset with lib {\n val io = IO(new Bundle{\n val scan_mode = Input(Bool())\n val cancel = Input(Bool())\n val valid_in = Input(Bool())\n val signed_in = Input(Bool())\n val rem_in = Input(Bool())\n val dividend_in = Input(UInt(32.W))\n val divisor_in = Input(UInt(32.W))\n val data_out = Output(UInt(32.W))\n val valid_out = Output(UInt(1.W))\n })\n val run_state = WireInit(0.U(1.W))\n val count = WireInit(0.U(6.W))\n val m_ff = WireInit(0.U(33.W))\n val q_in = WireInit(0.U(33.W))\n val q_ff = WireInit(0.U(33.W))\n val a_in = WireInit(0.U(33.W))\n val a_ff = WireInit(0.U(33.W))\n val m_eff = WireInit(0.U(33.W))\n val dividend_neg_ff = WireInit(0.U(1.W))\n val divisor_neg_ff = WireInit(0.U(1.W))\n val dividend_comp = WireInit(0.U(32.W))\n val q_ff_comp = WireInit(0.U(32.W))\n val a_ff_comp = WireInit(0.U(32.W))\n val sign_ff = WireInit(0.U(1.W))\n val rem_ff = WireInit(0.U(1.W))\n val add = WireInit(0.U(1.W))\n val a_eff = WireInit(0.U(33.W))\n val a_eff_shift = WireInit(0.U(65.W))\n val rem_correct = WireInit(0.U(1.W))\n val valid_ff_x = WireInit(0.U(1.W))\n val finish_ff = WireInit(0.U(1.W))\n val smallnum_case_ff = WireInit(0.U(1.W))\n val smallnum_ff = WireInit(0.U(4.W))\n val smallnum_case = WireInit(0.U(1.W))\n val count_in = WireInit(0.U(6.W))\n val dividend_eff = WireInit(0.U(32.W))\n val a_shift = WireInit(0.U(33.W))\n val shortq = WireInit(0.U(6.W))\n val valid_x = valid_ff_x & !io.cancel\n\n // START - short circuit logic for small numbers {{\n // small number divides - any 4b / 4b is done in 1 cycle (divisor != 0)\n // smallnum case does not cover divide by 0\n\n smallnum_case := ((q_ff(31,4) === 0.U) & (m_ff(31,4) === 0.U) & (m_ff(31,0) =/= 0.U) & !rem_ff & valid_x) |\n ((q_ff(31,0) === 0.U) & (m_ff(31,0) =/= 0.U) & !rem_ff & valid_x)\n\n def pat(x : List[Int], y : List[Int]) = {\n val pat_a = (0 until x.size).map(i=> if(x(i)>=0) q_ff(x(i)) else !q_ff(x(i).abs)).reduce(_&_)\n", "right_context": " pat_a & pat_b\n }\n\n val smallnum = Cat(\n pat(List(3),List(-3, -2, -1)),\n\n pat(List(3),List(-3, -2))& !m_ff(0) | pat(List(2),List(-3, -2, -1)) | pat(List(3, 2),List(-3, -2)),\n\n pat(List(2),List(-3, -2))& !m_ff(0) | pat(List(1),List(-3, -2, -1)) | pat(List(3),List(-3, -1))& !m_ff(0) |\n pat(List(3, -2),List(-3, -2, 1, 0)) | pat(List(-3, 2, 1),List(-3, -2)) | pat(List(3, 2),List(-3))& !m_ff(0) |\n pat(List(3, 2),List(-3, 2, -1)) | pat(List(3, 1),List(-3,-1)) | pat(List(3, 2, 1),List(-3, 2)),\n\n pat(List(2, 1, 0),List(-3, -1)) | pat(List(3, -2, 0),List(-3, 1, 0)) | pat(List(2),List(-3, -1))& !m_ff(0) |\n pat(List(1),List(-3, -2))& !m_ff(0) | pat(List(0),List(-3, -2, -1)) | pat(List(-3, 2, -1),List(-3, -2, 1, 0)) |\n pat(List(-3, 2, 1),List(-3))& !m_ff(0) | pat(List(3),List(-2, -1)) & !m_ff(0) | pat(List(3, -2),List(-3, 2, 1)) |\n pat(List(-3, 2, 1),List(-3, 2, -1)) | pat(List(-3, 2, 0),List(-3, -1)) | pat(List(3, -2, -1),List(-3, 2, 0)) |\n pat(List(-2, 1, 0),List(-3, -2)) | pat(List(3, 2),List(-1)) & !m_ff(0) | pat(List(-3, 2, 1, 0),List(-3, 2)) |\n pat(List(3, 2),List(3, -2)) | pat(List(3, 1),List(3,-2,-1)) | pat(List(3, 0),List(-2, -1)) |\n pat(List(3, -1),List(-3, 2, 1, 0)) | pat(List(3, 2, 1),List(3)) & !m_ff(0) | pat(List(3, 2, 1),List(3, -1)) |\n pat(List(3, 2, 0),List(3, -1)) | pat(List(3, -2, 1),List(-3, 1)) | pat(List(3, 1, 0),List(-2)) |\n pat(List(3, 2, 1, 0),List(3)) |pat(List(3, 1),List(-2)) & !m_ff(0)\n )\n // END - short circuit logic for small numbers }}\n\n // *** Start Short Q *** {{\n val shortq_enable_ff = WireInit(0.U(1.W))\n val short_dividend = WireInit(0.U(33.W))\n val shortq_shift_xx = WireInit(0.U(4.W))\n\n short_dividend := Cat (sign_ff & q_ff(31),q_ff(31,0))\n\n\n val a_cls = Cat(0.U(2.W),\n Mux1H(Seq (\n !short_dividend(32).asBool -> (short_dividend(31,24) =/= Fill(8,0.U)),\n short_dividend(32).asBool -> (short_dividend(31,23) =/= Fill(9,1.U))\n )),\n Mux1H(Seq (\n !short_dividend(32).asBool -> (short_dividend(23,16) =/= Fill(8,0.U)),\n short_dividend(32).asBool -> (short_dividend(22,15) =/= Fill(8,1.U))\n )),\n Mux1H(Seq (\n !short_dividend(32).asBool -> (short_dividend(15,8) =/= Fill(8,0.U)),\n short_dividend(32).asBool -> (short_dividend(14,7) =/= Fill(8,1.U))\n ))\n )\n val b_cls = Cat(0.U(2.W),\n Mux1H(Seq (\n !m_ff(32).asBool -> (m_ff(31,24) =/= Fill(8,0.U)),\n m_ff(32).asBool -> (m_ff(31,24) =/= Fill(8,1.U))\n )),\n Mux1H(Seq (\n !m_ff(32).asBool -> (m_ff(23,16) =/= Fill(8,0.U)),\n m_ff(32).asBool -> (m_ff(23,16) =/= Fill(8,1.U))\n )),\n Mux1H(Seq (\n !m_ff(32).asBool -> (m_ff(15,8) =/= Fill(8,0.U)),\n m_ff(32).asBool -> (m_ff(15,8) =/= Fill(8,1.U))\n ))\n )\n val shortq_raw = Cat(\n ( (a_cls(2,1) === \"b01\".U ) & (b_cls(2) === \"b1\".U ) ) | // Shift by 32\n ( (a_cls(2,0) === \"b001\".U ) & (b_cls(2) === \"b1\".U ) ) |\n ( (a_cls(2,0) === \"b000\".U ) & (b_cls(2) === \"b1\".U ) ) |\n ( (a_cls(2,0) === \"b001\".U ) & (b_cls(2,1) === \"b01\".U ) ) |\n ( (a_cls(2,0) === \"b000\".U ) & (b_cls(2,1) === \"b01\".U ) ) |\n ( (a_cls(2,0) === \"b000\".U ) & (b_cls(2,0) === \"b001\".U ) ) ,\n\n ( (a_cls(2) === \"b1\".U ) & (b_cls(2) === \"b1\".U ) ) | // Shift by 24\n ( (a_cls(2,1) === \"b01\".U ) & (b_cls(2,1) === \"b01\".U ) ) |\n ( (a_cls(2,0) === \"b001\".U ) & (b_cls(2,0) === \"b001\".U ) ) |\n ( (a_cls(2,0) === \"b000\".U ) & (b_cls(2,0) === \"b000\".U ) ) ,\n\n ( (a_cls(2) === \"b1\".U ) & (b_cls(2,1) === \"b01\".U ) ) | // Shift by 16\n ( (a_cls(2,1) === \"b01\".U ) & (b_cls(2,0) === \"b001\".U ) ) |\n ( (a_cls(2,0) === \"b001\".U ) & (b_cls(2,0) === \"b000\".U ) ) ,\n\n ( (a_cls(2) === \"b1\".U ) & (b_cls(2,0) === \"b001\".U ) ) | // Shift by 8\n ( (a_cls(2,1) === \"b01\".U ) & (b_cls(2,0) === \"b000\".U ) )\n\n )\n val shortq_enable = valid_ff_x & (m_ff(31,0) =/= 0.U(32.W)) & (shortq_raw =/= 0.U(4.W))\n val shortq_shift = Cat(0.U(2.W),Fill(4,shortq_enable) & shortq_raw)\n val shortq_shift_ff = Cat(0.U(1.W),Mux1H(Seq (\n shortq_shift_xx(3).asBool -> \"b11111\".U,\n shortq_shift_xx(2).asBool -> \"b11000\".U,\n shortq_shift_xx(1).asBool -> \"b10000\".U,\n shortq_shift_xx(0).asBool -> \"b01000\".U\n )))\n // *** End Short *** }}\n\n val finish = smallnum_case | Mux(!rem_ff ,count === 32.U(6.W) ,count === 33.U(6.W))\n val div_clken = io.valid_in | run_state | finish | finish_ff\n val run_in = (io.valid_in | run_state) & !finish & !io.cancel\n count_in := Fill(6,(run_state & !finish & !io.cancel & !shortq_enable)) & (count + Cat(0.U,shortq_shift_ff(4,0)) + (1.U)(6.W))\n io.valid_out := finish_ff & !io.cancel\n val sign_eff = io.signed_in & (io.divisor_in =/= 0.U(32.W))\n\n q_in := Mux1H(Seq(\n (!run_state).asBool -> Cat(0.U(1.W),io.dividend_in) ,\n (run_state & (valid_ff_x | shortq_enable_ff)).asBool -> (Cat(dividend_eff(31,0),!a_in(32)) << shortq_shift_ff(4,0)) ,\n (run_state & !(valid_ff_x | shortq_enable_ff)).asBool -> Cat(q_ff(31,0),!a_in(32))\n ))\n val qff_enable = io.valid_in | (run_state & !shortq_enable)\n dividend_eff := Mux((sign_ff & dividend_neg_ff).asBool, rvtwoscomp(q_ff(31,0)),q_ff(31,0))\n m_eff := Mux(add.asBool , m_ff, ~m_ff )\n a_eff_shift := Cat(0.U(33.W), dividend_eff) << shortq_shift_ff(4,0)\n a_eff := Mux1H(Seq(\n rem_correct.asBool -> a_ff ,\n (!rem_correct & !shortq_enable_ff).asBool -> Cat(a_ff(31,0), q_ff(32)) ,\n (!rem_correct & shortq_enable_ff).asBool -> a_eff_shift(64,32)\n ))\n val aff_enable = io.valid_in | (run_state & !shortq_enable & (count =/= 33.U(6.W))) | rem_correct\n a_shift := Fill(33,run_state) & a_eff\n a_in := Fill(33,run_state) & (a_shift + m_eff + Cat(0.U(32.W),!add))\n val m_already_comp = divisor_neg_ff & sign_ff\n // if m already complemented, then invert operation add->sub, sub->add\n add := (a_ff(32) | rem_correct) ^ m_already_comp\n rem_correct := (count === 33.U(6.W)) & rem_ff & a_ff(32)\n val q_ff_eff = Mux((sign_ff & (dividend_neg_ff ^ divisor_neg_ff)).asBool,rvtwoscomp(q_ff(31,0)), q_ff(31,0))\n val a_ff_eff = Mux((sign_ff & dividend_neg_ff ).asBool, rvtwoscomp(a_ff(31,0)), a_ff(31,0))\n\n io.data_out := Mux1H(Seq(\n smallnum_case_ff.asBool -> Cat(0.U(28.W), smallnum_ff),\n rem_ff.asBool -> a_ff_eff ,\n (!smallnum_case_ff & !rem_ff).asBool -> q_ff_eff\n ))\n valid_ff_x := rvdffe(io.valid_in & !io.cancel, div_clken,clock,io.scan_mode)\n finish_ff := rvdffe(finish & !io.cancel, div_clken,clock,io.scan_mode)\n run_state := rvdffe(run_in,div_clken,clock,io.scan_mode)\n count := rvdffe(count_in, div_clken,clock,io.scan_mode)\n dividend_neg_ff := rvdffe((io.valid_in & io.dividend_in(31)) | (!io.valid_in & dividend_neg_ff), div_clken,clock,io.scan_mode)\n divisor_neg_ff := rvdffe((io.valid_in & io.divisor_in(31)) | (!io.valid_in & divisor_neg_ff), div_clken,clock,io.scan_mode)\n sign_ff := rvdffe((io.valid_in & sign_eff) | (!io.valid_in & sign_ff), div_clken,clock,io.scan_mode)\n rem_ff := rvdffe((io.valid_in & io.rem_in) | (!io.valid_in & rem_ff), div_clken,clock,io.scan_mode)\n smallnum_case_ff := rvdffe(smallnum_case, div_clken,clock,io.scan_mode)\n smallnum_ff := rvdffe(smallnum, div_clken,clock,io.scan_mode)\n shortq_enable_ff := rvdffe(shortq_enable, div_clken,clock,io.scan_mode)\n shortq_shift_xx := rvdffe(shortq_shift, div_clken,clock,io.scan_mode)\n q_ff := rvdffe(q_in, qff_enable,clock,io.scan_mode)\n a_ff := rvdffe(a_in, aff_enable,clock,io.scan_mode)\n m_ff := rvdffe(Cat(io.signed_in & io.divisor_in(31), io.divisor_in(31,0)), io.valid_in,clock,io.scan_mode)\n\n}\n/////////////////////////////////////////////// 1 BIT FULL DIVIDER//////////////////////////////////\nclass exu_div_new_1bit_fullshortq extends Module with RequireAsyncReset with lib {\n val io = IO(new Bundle{\n val scan_mode = Input(Bool())\n val cancel = Input(Bool())\n val valid_in = Input(Bool())\n val signed_in = Input(Bool())\n val rem_in = Input(Bool())\n val dividend_in = Input(UInt(32.W))\n val divisor_in = Input(UInt(32.W))\n val data_out = Output(UInt(32.W))\n val valid_out = Output(UInt(1.W))\n })\n val valid_ff = WireInit(Bool(),init=false.B)\n val finish_ff = WireInit(Bool(),init=false.B)\n val control_ff = WireInit(0.U(3.W))\n val count_ff = WireInit(0.U(7.W))\n val smallnum = WireInit(0.U(4.W))\n val a_ff = WireInit(0.U(32.W))\n val b_ff = WireInit(0.U(33.W))\n val q_ff = WireInit(0.U(32.W))\n val r_ff = WireInit(0.U(32.W))\n val quotient_set = WireInit(Bool(),init=false.B)\n val shortq_enable = WireInit(Bool(),init=false.B)\n val shortq_enable_ff = WireInit(Bool(),init=false.B)\n val by_zero_case_ff = WireInit(Bool(),init=false.B)\n val adder_out = WireInit(0.U(33.W))\n val ar_shifted = WireInit(0.U(64.W))\n val shortq_shift_ff = WireInit(0.U(5.W))\n val dividend_sign_ff = control_ff(2)\n val divisor_sign_ff = control_ff(1)\n val rem_ff = control_ff(0)\n val by_zero_case = valid_ff & (b_ff(31,0) === 0.U)\n val smallnum_case = ((a_ff(31,4) === 0.U) & (b_ff(31,4) === 0.U) & !by_zero_case & !rem_ff & valid_ff & !io.cancel) |\n ((a_ff(31,0) === 0.U) & !by_zero_case & !rem_ff & valid_ff & !io.cancel)\n val valid_ff_in = io.valid_in & !io.cancel\n val control_in = Cat((!io.valid_in & control_ff(2)) | (io.valid_in & io.signed_in & io.dividend_in(31)), (!io.valid_in & control_ff(1)) | (io.valid_in & io.signed_in & io.divisor_in(31)), (!io.valid_in & control_ff(0)) | (io.valid_in & io.rem_in))\n val running_state = count_ff.orR() | shortq_enable_ff\n val misc_enable = io.valid_in | valid_ff | io.cancel | running_state | finish_ff\n val finish_raw = smallnum_case | by_zero_case | (count_ff === 32.U)\n val finish = finish_raw & !io.cancel\n val count_enable = (valid_ff | running_state) & !finish & !finish_ff & !io.cancel & !shortq_enable\n val count_in = Fill(7,count_enable) & (count_ff + Cat(0.U(6.W),1.U) + Cat(0.U(2.W),shortq_shift_ff))\n val a_enable = io.valid_in | running_state\n val a_shift = running_state & !shortq_enable_ff\n ar_shifted := Cat (Fill(32,dividend_sign_ff),a_ff) << shortq_shift_ff\n val b_twos_comp = valid_ff & !(dividend_sign_ff ^ divisor_sign_ff)\n val twos_comp_b_sel = valid_ff & !(dividend_sign_ff ^ divisor_sign_ff)\n val twos_comp_q_sel = !valid_ff & !rem_ff & (dividend_sign_ff ^ divisor_sign_ff) & !by_zero_case_ff\n val b_enable = io.valid_in | b_twos_comp\n val rq_enable = io.valid_in | valid_ff | running_state\n val r_sign_sel = valid_ff & dividend_sign_ff & !by_zero_case\n val r_restore_sel = running_state & !quotient_set & !shortq_enable_ff\n val r_adder_sel = running_state & quotient_set & !shortq_enable_ff\n val twos_comp_in = Mux1H(Seq (\n twos_comp_q_sel -> q_ff,\n twos_comp_b_sel -> b_ff(31,0)\n ))\n val twos_comp_out = rvtwoscomp(twos_comp_in)\n\n val a_in = Mux1H(Seq (\n (!a_shift & !shortq_enable_ff).asBool -> io.dividend_in,\n a_shift -> Cat(a_ff(30,0),0.U),\n shortq_enable_ff -> ar_shifted(31,0)\n ))\n val b_in = Mux1H(Seq (\n !b_twos_comp -> Cat(io.signed_in & io.divisor_in(31),io.divisor_in(31,0)),\n b_twos_comp -> Cat(!divisor_sign_ff,twos_comp_out(31,0))\n ))\n val r_in = Mux1H (Seq(\n r_sign_sel -> \"hffffffff\".U(32.W),\n r_restore_sel -> Cat(r_ff(30,0),a_ff(31)),\n r_adder_sel -> adder_out(31,0),\n shortq_enable_ff -> ar_shifted(63,32),\n by_zero_case -> a_ff\n ))\n val q_in = Mux1H (Seq(\n !valid_ff -> Cat(q_ff(30,0),quotient_set),\n smallnum_case -> Cat(0.U(28.W),smallnum),\n by_zero_case -> Fill(32,1.U)\n))\n adder_out := Cat(r_ff,a_ff(31)) + b_ff\n quotient_set := (!adder_out(32) ^ dividend_sign_ff) | ((a_ff(30,0) === 0.U) & (adder_out === 0.U))\n io.valid_out := finish_ff & !io.cancel\n io.data_out := Mux1H(Seq(\n (!rem_ff & !twos_comp_q_sel).asBool() -> q_ff,\n rem_ff -> r_ff,\n twos_comp_q_sel -> twos_comp_out\n ))\n def pat1(x : List[Int], y : List[Int]) = {\n val pat_a = (0 until x.size).map(i=> if(x(i)>=0) a_ff(x(i)) else !a_ff(x(i).abs)).reduce(_&_)\n val pat_b = (0 until y.size).map(i=> if(y(i)>=0) b_ff(y(i)) else !b_ff(y(i).abs)).reduce(_&_)\n pat_a & pat_b\n }\n\n smallnum := Cat(\n pat1(List(3),List(-3, -2, -1)),\n\n pat1(List(3),List(-3, -2))& !b_ff(0) | pat1(List(2),List(-3, -2, -1)) | pat1(List(3, 2),List(-3, -2)),\n\n pat1(List(2),List(-3, -2))& !b_ff(0) | pat1(List(1),List(-3, -2, -1)) | pat1(List(3),List(-3, -1))& !b_ff(0) |\n pat1(List(3, -2),List(-3, -2, 1, 0)) | pat1(List(-3, 2, 1),List(-3, -2)) | pat1(List(3, 2),List(-3))& !b_ff(0) |\n pat1(List(3, 2),List(-3, 2, -1)) | pat1(List(3, 1),List(-3,-1)) | pat1(List(3, 2, 1),List(-3, 2)),\n\n pat1(List(2, 1, 0),List(-3, -1)) | pat1(List(3, -2, 0),List(-3, 1, 0)) | pat1(List(2),List(-3, -1))& !b_ff(0) |\n pat1(List(1),List(-3, -2))& !b_ff(0) | pat1(List(0),List(-3, -2, -1)) | pat1(List(-3, 2, -1),List(-3, -2, 1, 0)) |\n pat1(List(-3, 2, 1),List(-3))& !b_ff(0) | pat1(List(3),List(-2, -1)) & !b_ff(0) | pat1(List(3, -2),List(-3, 2, 1)) |\n pat1(List(-3, 2, 1),List(-3, 2, -1)) | pat1(List(-3, 2, 0),List(-3, -1)) | pat1(List(3, -2, -1),List(-3, 2, 0)) |\n pat1(List(-2, 1, 0),List(-3, -2)) | pat1(List(3, 2),List(-1)) & !b_ff(0) | pat1(List(-3, 2, 1, 0),List(-3, 2)) |\n pat1(List(3, 2),List(3, -2)) | pat1(List(3, 1),List(3,-2,-1)) | pat1(List(3, 0),List(-2, -1)) |\n pat1(List(3, -1),List(-3, 2, 1, 0)) | pat1(List(3, 2, 1),List(3)) & !b_ff(0) | pat1(List(3, 2, 1),List(3, -1)) |\n pat1(List(3, 2, 0),List(3, -1)) | pat1(List(3, -2, 1),List(-3, 1)) | pat1(List(3, 1, 0),List(-2)) |\n pat1(List(3, 2, 1, 0),List(3)) |pat1(List(3, 1),List(-2)) & !b_ff(0))\n\nval shortq_dividend = Cat(dividend_sign_ff,a_ff)\n val a_enc = Module(new exu_div_cls)\n a_enc.io.operand := shortq_dividend\n val dw_a_enc1 = a_enc.io.cls\n val b_enc = Module(new exu_div_cls)\n b_enc.io.operand := b_ff\n val dw_b_enc1 = b_enc.io.cls\n val dw_a_enc = Cat (0.U, dw_a_enc1)\n val dw_b_enc = Cat (0.U, dw_b_enc1)\n val dw_shortq_raw = Cat(0.U,dw_b_enc) - Cat(0.U,dw_a_enc) + 1.U(7.W)\n val shortq = Mux(dw_shortq_raw(6).asBool(),0.U,dw_shortq_raw(5,0))\n shortq_enable := valid_ff & !shortq(5) & !(shortq(4,1) === \"b1111\".U) & !io.cancel\n val shortq_shift = Mux(!shortq_enable,0.U,(\"b11111\".U - shortq(4,0)))\n valid_ff := rvdffe(valid_ff_in, misc_enable,clock,io.scan_mode)\n control_ff := rvdffe(control_in, misc_enable,clock,io.scan_mode)\n by_zero_case_ff := rvdffe(by_zero_case,misc_enable,clock,io.scan_mode)\n shortq_enable_ff := rvdffe(shortq_enable, misc_enable,clock,io.scan_mode)\n shortq_shift_ff := rvdffe(shortq_shift, misc_enable,clock,io.scan_mode)\n finish_ff := rvdffe(finish, misc_enable,clock,io.scan_mode)\n count_ff := rvdffe(count_in, misc_enable,clock,io.scan_mode)\n\n a_ff := rvdffe(a_in, a_enable,clock,io.scan_mode)\n b_ff := rvdffe(b_in, b_enable,clock,io.scan_mode)\n r_ff := rvdffe(r_in, rq_enable,clock,io.scan_mode)\n q_ff := rvdffe(q_in, rq_enable,clock,io.scan_mode)\n}\n/////////////////////////////////////////////// 2 BIT FULL DIVIDER//////////////////////////////////\nclass exu_div_new_2bit_fullshortq extends Module with RequireAsyncReset with lib {\n val io = IO(new Bundle{\n val scan_mode = Input(Bool())\n val cancel = Input(Bool())\n val valid_in = Input(Bool())\n val signed_in = Input(Bool())\n val rem_in = Input(Bool())\n val dividend_in = Input(UInt(32.W))\n val divisor_in = Input(UInt(32.W))\n val data_out = Output(UInt(32.W))\n val valid_out = Output(UInt(1.W))\n })\n val valid_ff = WireInit(Bool(),init=false.B)\n val finish_ff = WireInit(Bool(),init=false.B)\n val control_ff = WireInit(0.U(3.W))\n val count_ff = WireInit(0.U(7.W))\n val smallnum = WireInit(0.U(4.W))\n val a_ff = WireInit(0.U(32.W))\n val b_ff1 = WireInit(0.U(33.W))\n val b_ff = WireInit(0.U(35.W))\n val q_ff = WireInit(0.U(32.W))\n val r_ff = WireInit(0.U(32.W))\n val quotient_raw = WireInit(0.U(4.W))\n val quotient_new = WireInit(0.U(2.W))\n val shortq_enable = WireInit(Bool(),init=false.B)\n val shortq_enable_ff = WireInit(Bool(),init=false.B)\n val by_zero_case_ff = WireInit(Bool(),init=false.B)\n val ar_shifted = WireInit(0.U(64.W))\n val shortq_shift_ff = WireInit(0.U(5.W))\n val valid_ff_in = io.valid_in & !io.cancel\n val control_in = Cat((!io.valid_in & control_ff(2)) | (io.valid_in & io.signed_in & io.dividend_in(31)), (!io.valid_in & control_ff(1)) | (io.valid_in & io.signed_in & io.divisor_in(31)), (!io.valid_in & control_ff(0)) | (io.valid_in & io.rem_in))\n val dividend_sign_ff = control_ff(2)\n val divisor_sign_ff = control_ff(1)\n val rem_ff = control_ff(0)\n val by_zero_case = valid_ff & (b_ff(31,0) === 0.U)\n val smallnum_case = ((a_ff(31,4) === 0.U) & (b_ff(31,4) === 0.U) & !by_zero_case & !rem_ff & valid_ff & !io.cancel) |\n ((a_ff(31,0) === 0.U) & !by_zero_case & !rem_ff & valid_ff & !io.cancel)\n val running_state = count_ff.orR() | shortq_enable_ff\n val misc_enable = io.valid_in | valid_ff | io.cancel | running_state | finish_ff\n val finish_raw = smallnum_case | by_zero_case | (count_ff === 32.U)\n val finish = finish_raw & !io.cancel\n val count_enable = (valid_ff | running_state) & !finish & !finish_ff & !io.cancel & !shortq_enable\n val count_in = Fill(7,count_enable) & (count_ff + Cat(0.U(5.W),2.U) + Cat(0.U(2.W),shortq_shift_ff(4,1),0.U))\n val a_enable = io.valid_in | running_state\n val a_shift = running_state & !shortq_enable_ff\n ar_shifted := Cat (Fill(32,dividend_sign_ff),a_ff) << Cat(shortq_shift_ff(4,1),0.U)\n val b_twos_comp = valid_ff & !(dividend_sign_ff ^ divisor_sign_ff)\n val twos_comp_b_sel = valid_ff & !(dividend_sign_ff ^ divisor_sign_ff)\n val twos_comp_q_sel = !valid_ff & !rem_ff & (dividend_sign_ff ^ divisor_sign_ff) & !by_zero_case_ff\n val b_enable = io.valid_in | b_twos_comp\n val rq_enable = io.valid_in | valid_ff | running_state\n val r_sign_sel = valid_ff & dividend_sign_ff & !by_zero_case\n val r_restore_sel = running_state & (quotient_new === 0.U) & !shortq_enable_ff\n val r_adder1_sel = running_state & (quotient_new === 1.U) & !shortq_enable_ff\n val r_adder2_sel = running_state & (quotient_new === 2.U) & !shortq_enable_ff\n val r_adder3_sel = running_state & (quotient_new === 3.U) & !shortq_enable_ff\n val adder1_out = Cat(r_ff(30,0),a_ff(31,30)) + b_ff(32,0)\n val adder2_out = Cat(r_ff(31,0),a_ff(31,30)) + Cat(b_ff(32,0),0.U)\n val adder3_out = Cat(r_ff(31),r_ff(31,0),a_ff(31,30)) + Cat(b_ff(33,0),0.U) + b_ff\n quotient_raw := Cat((!adder3_out(34) ^ dividend_sign_ff) | ((a_ff(29,0) === 0.U) & (adder3_out === 0.U)),\n (!adder2_out(33) ^ dividend_sign_ff) | ((a_ff(29,0) === 0.U) & (adder2_out === 0.U)),\n (!adder1_out(32) ^ dividend_sign_ff) | ((a_ff(29,0) === 0.U) & (adder1_out === 0.U)),0.U)\n quotient_new := Cat ((quotient_raw(3) | quotient_raw(2)) , (quotient_raw(3) |(!quotient_raw(2) & quotient_raw(1))))\n val twos_comp_in = Mux1H(Seq (\n twos_comp_q_sel -> q_ff,\n twos_comp_b_sel -> b_ff(31,0)\n ))\n val twos_comp_out = rvtwoscomp(twos_comp_in)\n\n val a_in = Mux1H(Seq (\n (!a_shift & !shortq_enable_ff).asBool -> io.dividend_in,\n a_shift -> Cat(a_ff(29,0),0.U(2.W)),\n shortq_enable_ff -> ar_shifted(31,0)\n ))\n\n val b_in = Mux1H(Seq (\n !b_twos_comp -> Cat(io.signed_in & io.divisor_in(31),io.divisor_in(31,0)),\n b_twos_comp -> Cat(!divisor_sign_ff,twos_comp_out(31,0))\n ))\n val r_in = Mux1H (Seq(\n r_sign_sel -> \"hffffffff\".U(32.W),\n r_restore_sel -> Cat(r_ff(29,0),a_ff(31,30)),\n r_adder1_sel -> adder1_out(31,0),\n r_adder2_sel -> adder2_out(31,0),\n r_adder3_sel -> adder3_out(31,0),\n shortq_enable_ff -> ar_shifted(63,32),\n by_zero_case -> a_ff\n ))\n val q_in = Mux1H (Seq(\n !valid_ff -> Cat(q_ff(29,0),quotient_new),\n smallnum_case -> Cat(0.U(28.W),smallnum),\n by_zero_case -> Fill(32,1.U)\n ))\n io.valid_out := finish_ff & !io.cancel\n io.data_out := Mux1H(Seq(\n (!rem_ff & !twos_comp_q_sel).asBool() -> q_ff,\n rem_ff -> r_ff,\n twos_comp_q_sel -> twos_comp_out\n ))\n def pat1(x : List[Int], y : List[Int]) = {\n val pat_a = (0 until x.size).map(i=> if(x(i)>=0) a_ff(x(i)) else !a_ff(x(i).abs)).reduce(_&_)\n val pat_b = (0 until y.size).map(i=> if(y(i)>=0) b_ff(y(i)) else !b_ff(y(i).abs)).reduce(_&_)\n pat_a & pat_b\n }\n smallnum := Cat(\n pat1(List(3),List(-3, -2, -1)),\n\n pat1(List(3),List(-3, -2))& !b_ff(0) | pat1(List(2),List(-3, -2, -1)) | pat1(List(3, 2),List(-3, -2)),\n\n pat1(List(2),List(-3, -2))& !b_ff(0) | pat1(List(1),List(-3, -2, -1)) | pat1(List(3),List(-3, -1))& !b_ff(0) |\n pat1(List(3, -2),List(-3, -2, 1, 0)) | pat1(List(-3, 2, 1),List(-3, -2)) | pat1(List(3, 2),List(-3))& !b_ff(0) |\n pat1(List(3, 2),List(-3, 2, -1)) | pat1(List(3, 1),List(-3,-1)) | pat1(List(3, 2, 1),List(-3, 2)),\n\n pat1(List(2, 1, 0),List(-3, -1)) | pat1(List(3, -2, 0),List(-3, 1, 0)) | pat1(List(2),List(-3, -1))& !b_ff(0) |\n pat1(List(1),List(-3, -2))& !b_ff(0) | pat1(List(0),List(-3, -2, -1)) | pat1(List(-3, 2, -1),List(-3, -2, 1, 0)) |\n pat1(List(-3, 2, 1),List(-3))& !b_ff(0) | pat1(List(3),List(-2, -1)) & !b_ff(0) | pat1(List(3, -2),List(-3, 2, 1)) |\n pat1(List(-3, 2, 1),List(-3, 2, -1)) | pat1(List(-3, 2, 0),List(-3, -1)) | pat1(List(3, -2, -1),List(-3, 2, 0)) |\n pat1(List(-2, 1, 0),List(-3, -2)) | pat1(List(3, 2),List(-1)) & !b_ff(0) | pat1(List(-3, 2, 1, 0),List(-3, 2)) |\n pat1(List(3, 2),List(3, -2)) | pat1(List(3, 1),List(3,-2,-1)) | pat1(List(3, 0),List(-2, -1)) |\n pat1(List(3, -1),List(-3, 2, 1, 0)) | pat1(List(3, 2, 1),List(3)) & !b_ff(0) | pat1(List(3, 2, 1),List(3, -1)) |\n pat1(List(3, 2, 0),List(3, -1)) | pat1(List(3, -2, 1),List(-3, 1)) | pat1(List(3, 1, 0),List(-2)) |\n pat1(List(3, 2, 1, 0),List(3)) |pat1(List(3, 1),List(-2)) & !b_ff(0))\n\n val shortq_dividend = Cat(dividend_sign_ff,a_ff)\n val a_enc = Module(new exu_div_cls)\n a_enc.io.operand := shortq_dividend\n val dw_a_enc1 = a_enc.io.cls\n val b_enc = Module(new exu_div_cls)\n b_enc.io.operand := b_ff(32,0)\n val dw_b_enc1 = b_enc.io.cls\n val dw_a_enc = Cat (0.U, dw_a_enc1)\n val dw_b_enc = Cat (0.U, dw_b_enc1)\n val dw_shortq_raw = Cat(0.U,dw_b_enc) - Cat(0.U,dw_a_enc) + 1.U(7.W)\n val shortq = Mux(dw_shortq_raw(6).asBool(),0.U,dw_shortq_raw(5,0))\n shortq_enable := valid_ff & !shortq(5) & !(shortq(4,1) === \"b1111\".U) & !io.cancel\n val shortq_shift = Mux(!shortq_enable,0.U,(\"b11111\".U - shortq(4,0)))\n b_ff := Cat(b_ff1(32),b_ff1(32),b_ff1)\n valid_ff := rvdffe(valid_ff_in, misc_enable,clock,io.scan_mode)\n control_ff := rvdffe(control_in, misc_enable,clock,io.scan_mode)\n by_zero_case_ff := rvdffe(by_zero_case,misc_enable,clock,io.scan_mode)\n shortq_enable_ff := rvdffe(shortq_enable, misc_enable,clock,io.scan_mode)\n shortq_shift_ff := Cat(rvdffe(shortq_shift(4,1), misc_enable,clock,io.scan_mode),0.U)\n finish_ff := rvdffe(finish, misc_enable,clock,io.scan_mode)\n count_ff := rvdffe(count_in, misc_enable,clock,io.scan_mode)\n\n a_ff := rvdffe(a_in, a_enable,clock,io.scan_mode)\n b_ff1 := rvdffe(b_in(32,0), b_enable,clock,io.scan_mode)\n r_ff := rvdffe(r_in, rq_enable,clock,io.scan_mode)\n q_ff := rvdffe(q_in, rq_enable,clock,io.scan_mode)\n\n}\n/////////////////////////////////////////////// 3 BIT FULL DIVIDER//////////////////////////////////\nclass exu_div_new_3bit_fullshortq extends Module with RequireAsyncReset with lib {\n val io = IO(new Bundle{\n val scan_mode = Input(Bool())\n val cancel = Input(Bool())\n val valid_in = Input(Bool())\n val signed_in = Input(Bool())\n val rem_in = Input(Bool())\n val dividend_in = Input(UInt(32.W))\n val divisor_in = Input(UInt(32.W))\n val data_out = Output(UInt(32.W))\n val valid_out = Output(UInt(1.W))\n })\n val valid_ff = WireInit(Bool(),init=false.B)\n val finish_ff = WireInit(Bool(),init=false.B)\n val control_ff = WireInit(0.U(3.W))\n val count_ff = WireInit(0.U(7.W))\n val smallnum = WireInit(0.U(4.W))\n val a_ff = WireInit(0.U(33.W))\n val b_ff1 = WireInit(0.U(33.W))\n val b_ff = WireInit(0.U(37.W))\n val q_ff = WireInit(0.U(32.W))\n val r_ff = WireInit(0.U(33.W))\n val quotient_raw = WireInit(0.U(8.W))\n val quotient_new = WireInit(0.U(3.W))\n val shortq_enable = WireInit(Bool(),init=false.B)\n val shortq_enable_ff = WireInit(Bool(),init=false.B)\n val by_zero_case_ff = WireInit(Bool(),init=false.B)\n val ar_shifted = WireInit(0.U(66.W))\n val shortq_shift = WireInit(0.U(5.W))\n val shortq_decode = WireInit(0.U(5.W))\n val shortq_shift_ff = WireInit(0.U(5.W))\n val valid_ff_in = io.valid_in & !io.cancel\n val control_in = Cat((!io.valid_in & control_ff(2)) | (io.valid_in & io.signed_in & io.dividend_in(31)), (!io.valid_in & control_ff(1)) | (io.valid_in & io.signed_in & io.divisor_in(31)), (!io.valid_in & control_ff(0)) | (io.valid_in & io.rem_in))\n val dividend_sign_ff = control_ff(2)\n val divisor_sign_ff = control_ff(1)\n val rem_ff = control_ff(0)\n val by_zero_case = valid_ff & (b_ff(31,0) === 0.U)\n\n val smallnum_case = ((a_ff(31,4) === 0.U) & (b_ff(31,4) === 0.U) & !by_zero_case & !rem_ff & valid_ff & !io.cancel) |\n ((a_ff(31,0) === 0.U) & !by_zero_case & !rem_ff & valid_ff & !io.cancel)\n val running_state = count_ff.orR() | shortq_enable_ff\n val misc_enable = io.valid_in | valid_ff | io.cancel | running_state | finish_ff\n val finish_raw = smallnum_case | by_zero_case | (count_ff === 33.U)\n val finish = finish_raw & !io.cancel\n val count_enable = (valid_ff | running_state) & !finish & !finish_ff & !io.cancel & !shortq_enable\n val count_in = Fill(7,count_enable) & (count_ff + Cat(0.U(5.W),3.U(2.W)) + Cat(0.U(2.W),shortq_shift_ff))\n val a_enable = io.valid_in | running_state\n val a_shift = running_state & !shortq_enable_ff\n ar_shifted := Cat (Fill(33,dividend_sign_ff),a_ff) << shortq_shift_ff(4,0)\n val b_twos_comp = valid_ff & !(dividend_sign_ff ^ divisor_sign_ff)\n val twos_comp_b_sel = valid_ff & !(dividend_sign_ff ^ divisor_sign_ff)\n val twos_comp_q_sel = !valid_ff & !rem_ff & (dividend_sign_ff ^ divisor_sign_ff) & !by_zero_case_ff\n val b_enable = io.valid_in | b_twos_comp\n val rq_enable = io.valid_in | valid_ff | running_state\n val r_sign_sel = valid_ff & dividend_sign_ff & !by_zero_case\n\n val r_adder_sel = (0 to 7 ).map(i=> (running_state & (quotient_new === i.asUInt) & !shortq_enable_ff))\n val adder1_out = Cat(r_ff(30,0),a_ff(32,30)) + b_ff(33,0)\n val adder2_out = Cat(r_ff(31,0),a_ff(32,30)) + Cat(b_ff(33,0),0.U)\n val adder3_out = Cat(r_ff(32,0),a_ff(32,30)) + Cat(b_ff(34,0),0.U) + b_ff(35,0)\n val adder4_out = Cat(r_ff(32),r_ff(32,0),a_ff(32,30)) + Cat(b_ff(34,0),0.U(2.W))\n val adder5_out = Cat(r_ff(32),r_ff(32,0),a_ff(32,30)) + Cat(b_ff(34,0),0.U(2.W)) + b_ff\n val adder6_out = Cat(r_ff(32),r_ff(32,0),a_ff(32,30)) + Cat(b_ff(34,0),0.U(2.W)) + Cat(b_ff(35,0),0.U)\n val adder7_out = Cat(r_ff(32),r_ff(32,0),a_ff(32,30)) + Cat(b_ff(34,0),0.U(2.W)) + Cat(b_ff(35,0),0.U) + b_ff\n quotient_raw := Cat((!adder7_out(36) ^ dividend_sign_ff) | ((a_ff(29,0) === 0.U) & (adder7_out === 0.U)),\n (!adder6_out(36) ^ dividend_sign_ff) | ((a_ff(29,0) === 0.U) & (adder6_out === 0.U)),\n (!adder5_out(36) ^ dividend_sign_ff) | ((a_ff(29,0) === 0.U) & (adder5_out === 0.U)),\n (!adder4_out(36) ^ dividend_sign_ff) | ((a_ff(29,0) === 0.U) & (adder4_out === 0.U)),\n (!adder3_out(35) ^ dividend_sign_ff) | ((a_ff(29,0) === 0.U) & (adder3_out === 0.U)),\n (!adder2_out(34) ^ dividend_sign_ff) | ((a_ff(29,0) === 0.U) & (adder2_out === 0.U)),\n (!adder1_out(33) ^ dividend_sign_ff) | ((a_ff(29,0) === 0.U) & (adder1_out === 0.U)), 0.U)\n quotient_new := Cat ((quotient_raw(7) | quotient_raw(6) | quotient_raw(5) | quotient_raw(4)),\n (quotient_raw(7) | quotient_raw(6) |(!quotient_raw(4) & quotient_raw(3)) |(!quotient_raw(3) & quotient_raw(2))),\n (quotient_raw(7) | (!quotient_raw(6) & quotient_raw(5)) | (!quotient_raw(4) & quotient_raw(3)) |(!quotient_raw(2) & quotient_raw(1))))\n val twos_comp_in = Mux1H(Seq (\n twos_comp_q_sel -> q_ff,\n twos_comp_b_sel -> b_ff(31,0)\n ))\n val twos_comp_out = rvtwoscomp(twos_comp_in)\n val a_in = Mux1H(Seq (\n (!a_shift & !shortq_enable_ff).asBool -> Cat(io.signed_in & io.dividend_in(31),io.dividend_in(31,0)),\n a_shift -> Cat(a_ff(29,0),0.U(3.W)),\n shortq_enable_ff -> ar_shifted(32,0)\n ))\n val b_in = Mux1H(Seq (\n !b_twos_comp -> Cat(io.signed_in & io.divisor_in(31),io.divisor_in(31,0)),\n b_twos_comp -> Cat(!divisor_sign_ff,twos_comp_out(31,0))\n ))\n val r_in = Mux1H (Seq(\n r_sign_sel -> Fill(33,1.U),\n r_adder_sel(0) -> Cat(r_ff(29,0),a_ff(32,30)),\n r_adder_sel(1) -> adder1_out(32,0),\n r_adder_sel(2) -> adder2_out(32,0),\n r_adder_sel(3) -> adder3_out(32,0),\n r_adder_sel(4) -> adder4_out(32,0),\n r_adder_sel(5) -> adder5_out(32,0),\n r_adder_sel(6) -> adder6_out(32,0),\n r_adder_sel(7) -> adder7_out(32,0),\n shortq_enable_ff -> ar_shifted(65,33),\n by_zero_case -> Cat(0.U,a_ff(31,0))\n))\n val q_in = Mux1H (Seq(\n !valid_ff -> Cat(q_ff(28,0),quotient_new),\n smallnum_case -> Cat(0.U(28.W),smallnum),\n by_zero_case -> Fill(32,1.U)\n ))\n io.valid_out := finish_ff & !io.cancel\n io.data_out := Mux1H(Seq(\n (!rem_ff & !twos_comp_q_sel).asBool() -> q_ff,\n rem_ff -> r_ff(31,0),\n twos_comp_q_sel -> twos_comp_out\n ))\n def pat1(x : List[Int], y : List[Int]) = {\n val pat_a = (0 until x.size).map(i=> if(x(i)>=0) a_ff(x(i)) else !a_ff(x(i).abs)).reduce(_&_)\n val pat_b = (0 until y.size).map(i=> if(y(i)>=0) b_ff(y(i)) else !b_ff(y(i).abs)).reduce(_&_)\n pat_a & pat_b\n }\n smallnum := Cat(\n pat1(List(3),List(-3, -2, -1)),\n\n pat1(List(3),List(-3, -2))& !b_ff(0) | pat1(List(2),List(-3, -2, -1)) | pat1(List(3, 2),List(-3, -2)),\n\n pat1(List(2),List(-3, -2))& !b_ff(0) | pat1(List(1),List(-3, -2, -1)) | pat1(List(3),List(-3, -1))& !b_ff(0) |\n pat1(List(3, -2),List(-3, -2, 1, 0)) | pat1(List(-3, 2, 1),List(-3, -2)) | pat1(List(3, 2),List(-3))& !b_ff(0) |\n pat1(List(3, 2),List(-3, 2, -1)) | pat1(List(3, 1),List(-3,-1)) | pat1(List(3, 2, 1),List(-3, 2)),\n\n pat1(List(2, 1, 0),List(-3, -1)) | pat1(List(3, -2, 0),List(-3, 1, 0)) | pat1(List(2),List(-3, -1))& !b_ff(0) |\n pat1(List(1),List(-3, -2))& !b_ff(0) | pat1(List(0),List(-3, -2, -1)) | pat1(List(-3, 2, -1),List(-3, -2, 1, 0)) |\n pat1(List(-3, 2, 1),List(-3))& !b_ff(0) | pat1(List(3),List(-2, -1)) & !b_ff(0) | pat1(List(3, -2),List(-3, 2, 1)) |\n pat1(List(-3, 2, 1),List(-3, 2, -1)) | pat1(List(-3, 2, 0),List(-3, -1)) | pat1(List(3, -2, -1),List(-3, 2, 0)) |\n pat1(List(-2, 1, 0),List(-3, -2)) | pat1(List(3, 2),List(-1)) & !b_ff(0) | pat1(List(-3, 2, 1, 0),List(-3, 2)) |\n pat1(List(3, 2),List(3, -2)) | pat1(List(3, 1),List(3,-2,-1)) | pat1(List(3, 0),List(-2, -1)) |\n pat1(List(3, -1),List(-3, 2, 1, 0)) | pat1(List(3, 2, 1),List(3)) & !b_ff(0) | pat1(List(3, 2, 1),List(3, -1)) |\n pat1(List(3, 2, 0),List(3, -1)) | pat1(List(3, -2, 1),List(-3, 1)) | pat1(List(3, 1, 0),List(-2)) |\n pat1(List(3, 2, 1, 0),List(3)) |pat1(List(3, 1),List(-2)) & !b_ff(0))\n\n val shortq_dividend = Cat(dividend_sign_ff,a_ff(31,0))\n val a_enc = Module(new exu_div_cls)\n a_enc.io.operand := shortq_dividend\n val dw_a_enc1 = a_enc.io.cls\n val b_enc = Module(new exu_div_cls)\n b_enc.io.operand := b_ff(32,0)\n val dw_b_enc1 = b_enc.io.cls\n val dw_a_enc = Cat (0.U, dw_a_enc1)\n val dw_b_enc = Cat (0.U, dw_b_enc1)\n\n val dw_shortq_raw = Cat(0.U,dw_b_enc) - Cat(0.U,dw_a_enc) + 1.U(7.W)\n val shortq = Mux(dw_shortq_raw(6).asBool(),0.U,dw_shortq_raw(5,0))\n shortq_enable := valid_ff & !shortq(5) & !(shortq(4,2) === \"b111\".U) & !io.cancel\n val list = Array(27,27,27,27,27,27,24,24,24,21,21,21,18,18,18,15,15,15,12,12,12,9,9,9,6,6,6,3,0,0,0,0)\n shortq_decode := Mux1H((31 to 0 by -1).map(i=> (shortq === i.U) -> list(i).U))\n shortq_shift := Mux(!shortq_enable,0.U,shortq_decode)\n b_ff := Cat(b_ff1(32),b_ff1(32),b_ff1(32),b_ff1(32),b_ff1)\n valid_ff := rvdffe(valid_ff_in, misc_enable,clock,io.scan_mode)\n control_ff := rvdffe(control_in, misc_enable,clock,io.scan_mode)\n by_zero_case_ff := rvdffe(by_zero_case,misc_enable,clock,io.scan_mode)\n shortq_enable_ff := rvdffe(shortq_enable, misc_enable,clock,io.scan_mode)\n shortq_shift_ff := rvdffe(shortq_shift, misc_enable,clock,io.scan_mode)\n finish_ff := rvdffe(finish, misc_enable,clock,io.scan_mode)\n count_ff := rvdffe(count_in, misc_enable,clock,io.scan_mode)\n\n a_ff := rvdffe(a_in, a_enable,clock,io.scan_mode)\n b_ff1 := rvdffe(b_in(32,0), b_enable,clock,io.scan_mode)\n r_ff := rvdffe(r_in, rq_enable,clock,io.scan_mode)\n q_ff := rvdffe(q_in, rq_enable,clock,io.scan_mode)\n\n}\n/////////////////////////////////////////////// 4 BIT FULL DIVIDER//////////////////////////////////\nclass exu_div_new_4bit_fullshortq extends Module with RequireAsyncReset with lib {\n val io = IO(new Bundle {\n val scan_mode = Input(Bool())\n val cancel = Input(Bool())\n val valid_in = Input(Bool())\n val signed_in = Input(Bool())\n val rem_in = Input(Bool())\n val dividend_in = Input(UInt(32.W))\n val divisor_in = Input(UInt(32.W))\n val data_out = Output(UInt(32.W))\n val valid_out = Output(UInt(1.W))\n })\n\n val valid_ff = WireInit(Bool(),init=false.B)\n val finish_ff = WireInit(Bool(),init=false.B)\n val control_ff = WireInit(0.U(3.W))\n val count_ff = WireInit(0.U(7.W))\n val smallnum = WireInit(0.U(4.W))\n val a_ff = WireInit(0.U(32.W))\n val b_ff1 = WireInit(0.U(33.W))\n val b_ff = WireInit(0.U(38.W))\n val q_ff = WireInit(0.U(32.W))\n val r_ff = WireInit(0.U(33.W))\n val quotient_raw = WireInit(0.U(16.W))\n val quotient_new = WireInit(0.U(4.W))\n val shortq_enable = WireInit(Bool(),init=false.B)\n val shortq_enable_ff = WireInit(Bool(),init=false.B)\n val by_zero_case_ff = WireInit(Bool(),init=false.B)\n val ar_shifted = WireInit(0.U(65.W))\n val shortq_shift = WireInit(0.U(5.W))\n val shortq_decode = WireInit(0.U(5.W))\n val shortq_shift_ff = WireInit(0.U(5.W))\n val valid_ff_in = io.valid_in & !io.cancel\n val control_in = Cat((!io.valid_in & control_ff(2)) | (io.valid_in & io.signed_in & io.dividend_in(31)), (!io.valid_in & control_ff(1)) | (io.valid_in & io.signed_in & io.divisor_in(31)), (!io.valid_in & control_ff(0)) | (io.valid_in & io.rem_in))\n val dividend_sign_ff = control_ff(2)\n val divisor_sign_ff = control_ff(1)\n val rem_ff = control_ff(0)\n val by_zero_case = valid_ff & (b_ff(31,0) === 0.U)\n\n val smallnum_case = ((a_ff(31,4) === 0.U) & (b_ff(31,4) === 0.U) & !by_zero_case & !rem_ff & valid_ff & !io.cancel) |\n ((a_ff(31,0) === 0.U) & !by_zero_case & !rem_ff & valid_ff & !io.cancel)\n val running_state = count_ff.orR() | shortq_enable_ff\n val misc_enable = io.valid_in | valid_ff | io.cancel | running_state | finish_ff\n val finish_raw = smallnum_case | by_zero_case | (count_ff === 32.U)\n val finish = finish_raw & !io.cancel\n val count_enable = (valid_ff | running_state) & !finish & !finish_ff & !io.cancel & !shortq_enable\n val count_in = Fill(7,count_enable) & (count_ff + 4.U(7.W) + Cat(0.U(2.W),shortq_shift_ff))\n val a_enable = io.valid_in | running_state\n val a_shift = running_state & !shortq_enable_ff\n ar_shifted := Cat (Fill(33,dividend_sign_ff),a_ff(31,0)) << shortq_shift_ff\n val b_twos_comp = valid_ff & !(dividend_sign_ff ^ divisor_sign_ff)\n val twos_comp_b_sel = valid_ff & !(dividend_sign_ff ^ divisor_sign_ff)\n val twos_comp_q_sel = !valid_ff & !rem_ff & (dividend_sign_ff ^ divisor_sign_ff) & !by_zero_case_ff\n val b_enable = io.valid_in | b_twos_comp\n val rq_enable = io.valid_in | valid_ff | running_state\n val r_sign_sel = valid_ff & dividend_sign_ff & !by_zero_case\n val r_adder_sel = (0 to 15 ).map(i=> (running_state & (quotient_new === i.asUInt) & !shortq_enable_ff))\n val adder1_out = Cat(r_ff(30,0),a_ff(31,28)) + b_ff(34,0)\n val adder2_out = Cat(r_ff(31,0),a_ff(31,28)) + Cat(b_ff(34,0),0.U)\n val adder3_out = Cat(r_ff(32,0),a_ff(31,28)) + Cat(b_ff(35,0),0.U) + b_ff(36,0)\n val adder4_out = Cat(r_ff(32),r_ff(32,0),a_ff(31,28)) + Cat(b_ff(35,0),0.U(2.W))\n val adder5_out = Cat(r_ff(32),r_ff(32,0),a_ff(31,28)) + Cat(b_ff(35,0),0.U(2.W)) + b_ff\n val adder6_out = Cat(r_ff(32),r_ff(32,0),a_ff(31,28)) + Cat(b_ff(35,0),0.U(2.W)) + Cat(b_ff(36,0),0.U)\n val adder7_out = Cat(r_ff(32),r_ff(32,0),a_ff(31,28)) + Cat(b_ff(35,0),0.U(2.W)) + Cat(b_ff(36,0),0.U) + b_ff\n val adder8_out = Cat(r_ff(32),r_ff(32,0),a_ff(31,28)) + Cat(b_ff(34,0),0.U(3.W))\n val adder9_out = Cat(r_ff(32),r_ff(32,0),a_ff(31,28)) + Cat(b_ff(34,0),0.U(3.W)) + b_ff\n val adder10_out = Cat(r_ff(32),r_ff(32,0),a_ff(31,28)) + Cat(b_ff(34,0),0.U(3.W)) + Cat(b_ff(36,0),0.U)\n val adder11_out = Cat(r_ff(32),r_ff(32,0),a_ff(31,28)) + Cat(b_ff(34,0),0.U(3.W)) + Cat(b_ff(36,0),0.U) + b_ff\n val adder12_out = Cat(r_ff(32),r_ff(32,0),a_ff(31,28)) + Cat(b_ff(34,0),0.U(3.W)) + Cat(b_ff(35,0),0.U(2.W))\n val adder13_out = Cat(r_ff(32),r_ff(32,0),a_ff(31,28)) + Cat(b_ff(34,0),0.U(3.W)) + Cat(b_ff(35,0),0.U(2.W)) + b_ff\n val adder14_out = Cat(r_ff(32),r_ff(32,0),a_ff(31,28)) + Cat(b_ff(34,0),0.U(3.W)) + Cat(b_ff(35,0),0.U(2.W)) + Cat(b_ff(36,0),0.U)\n val adder15_out = Cat(r_ff(32),r_ff(32,0),a_ff(31,28)) + Cat(b_ff(34,0),0.U(3.W)) + Cat(b_ff(35,0),0.U(2.W)) + Cat(b_ff(36,0),0.U) + b_ff\n\n quotient_raw := Cat(\n (!adder15_out(37) ^ dividend_sign_ff) | ((a_ff(27,0) === 0.U) & (adder15_out === 0.U)),\n (!adder14_out(37) ^ dividend_sign_ff) | ((a_ff(27,0) === 0.U) & (adder14_out === 0.U)),\n (!adder13_out(37) ^ dividend_sign_ff) | ((a_ff(27,0) === 0.U) & (adder13_out === 0.U)),\n (!adder12_out(37) ^ dividend_sign_ff) | ((a_ff(27,0) === 0.U) & (adder12_out === 0.U)),\n (!adder11_out(37) ^ dividend_sign_ff) | ((a_ff(27,0) === 0.U) & (adder11_out === 0.U)),\n (!adder10_out(37) ^ dividend_sign_ff) | ((a_ff(27,0) === 0.U) & (adder10_out === 0.U)),\n (!adder9_out(37) ^ dividend_sign_ff) | ((a_ff(27,0) === 0.U) & (adder9_out === 0.U)),\n (!adder8_out(37) ^ dividend_sign_ff) | ((a_ff(27,0) === 0.U) & (adder8_out === 0.U)),\n (!adder7_out(37) ^ dividend_sign_ff) | ((a_ff(27,0) === 0.U) & (adder7_out === 0.U)),\n (!adder6_out(37) ^ dividend_sign_ff) | ((a_ff(27,0) === 0.U) & (adder6_out === 0.U)),\n (!adder5_out(37) ^ dividend_sign_ff) | ((a_ff(27,0) === 0.U) & (adder5_out === 0.U)),\n (!adder4_out(37) ^ dividend_sign_ff) | ((a_ff(27,0) === 0.U) & (adder4_out === 0.U)),\n (!adder3_out(36) ^ dividend_sign_ff) | ((a_ff(27,0) === 0.U) & (adder3_out === 0.U)),\n (!adder2_out(35) ^ dividend_sign_ff) | ((a_ff(27,0) === 0.U) & (adder2_out === 0.U)),\n (!adder1_out(34) ^ dividend_sign_ff) | ((a_ff(27,0) === 0.U) & (adder1_out === 0.U)), 0.U)\n\n quotient_new := Cat(\n (Mux1H((8 to 14).map(i=> (quotient_raw(15,i)=== Cat(Fill(15-i,0.U),1.U)).asBool -> 1.U)) | (quotient_raw(15)===1.U)),\n Mux1H (Seq(( quotient_raw(15,4) === \"b000000000001\".U(12.W)) -> 1.U, ( quotient_raw(15,5) === \"b00000000001\".U(11.W)) -> 1.U, ( quotient_raw(15,6) === \"b0000000001\".U(10.W)) -> 1.U, ( quotient_raw(15,7) === \"b000000001\".U(9.W)) -> 1.U,\n ( quotient_raw(15,12)=== \"b0001\".U(4.W)) -> 1.U, ( quotient_raw(15,13)=== \"b001\".U(3.W)) -> 1.U, ( quotient_raw(15,14)=== \"b01\".U(2.W)) -> 1.U, ( quotient_raw(15) === \"b1\".U) -> 1.U)),\n Mux1H(Seq(( quotient_raw(15,2) === \"b00000000000001\".U(14.W)) -> 1.U, ( quotient_raw(15,3) === \"b0000000000001\".U(13.W)) -> 1.U, ( quotient_raw(15,6) === \"b0000000001\".U(10.W)) -> 1.U, ( quotient_raw(15,7) === \"b000000001\".U(9.W)) -> 1.U,\n ( quotient_raw(15,10)=== \"b000001\".U(6.W)) -> 1.U, ( quotient_raw(15,11)=== \"b00001\".U(5.W)) -> 1.U, ( quotient_raw(15,14)=== \"b01\".U(2.W)) -> 1.U, ( quotient_raw(15) === \"b1\".U) -> 1.U)),\n (Mux1H((1 to 13 by 2).map(i=> (quotient_raw(15,i)=== Cat(Fill(15-i,0.U),1.U)).asBool -> 1.U)) | (quotient_raw(15)===1.U) ))\n val twos_comp_in = Mux1H(Seq (\n twos_comp_q_sel -> q_ff,\n twos_comp_b_sel -> b_ff(31,0)\n ))\n val twos_comp_out = rvtwoscomp(twos_comp_in)\n val a_in = Mux1H(Seq (\n (!a_shift & !shortq_enable_ff).asBool -> io.dividend_in(31,0),\n a_shift -> Cat(a_ff(27,0),0.U(4.W)),\n shortq_enable_ff -> ar_shifted(31,0)\n ))\n val b_in = Mux1H(Seq (\n !b_twos_comp -> Cat(io.signed_in & io.divisor_in(31),io.divisor_in(31,0)),\n b_twos_comp -> Cat(!divisor_sign_ff,twos_comp_out(31,0))\n ))\n val r_in = Mux1H (Seq(\n r_sign_sel -> Fill(33,1.U),\n r_adder_sel(0) -> Cat(r_ff(28,0),a_ff(31,28)),\n r_adder_sel(1) -> adder1_out(32,0),\n r_adder_sel(2) -> adder2_out(32,0),\n r_adder_sel(3) -> adder3_out(32,0),\n r_adder_sel(4) -> adder4_out(32,0),\n r_adder_sel(5) -> adder5_out(32,0),\n r_adder_sel(6) -> adder6_out(32,0),\n r_adder_sel(7) -> adder7_out(32,0),\n r_adder_sel(8) -> adder8_out(32,0),\n r_adder_sel(9) -> adder9_out(32,0),\n r_adder_sel(10) -> adder10_out(32,0),\n r_adder_sel(11) -> adder11_out(32,0),\n r_adder_sel(12) -> adder12_out(32,0),\n r_adder_sel(13) -> adder13_out(32,0),\n r_adder_sel(14) -> adder14_out(32,0),\n r_adder_sel(15) -> adder15_out(32,0),\n shortq_enable_ff -> ar_shifted(64,32),\n by_zero_case -> Cat(0.U,a_ff(31,0))\n ))\n val q_in = Mux1H (Seq(\n !valid_ff -> Cat(q_ff(27,0),quotient_new),\n smallnum_case -> Cat(0.U(28.W),smallnum),\n by_zero_case -> Fill(32,1.U)\n ))\n io.valid_out := finish_ff & !io.cancel\n io.data_out := Mux1H(Seq(\n (!rem_ff & !twos_comp_q_sel).asBool() -> q_ff,\n rem_ff -> r_ff(31,0),\n twos_comp_q_sel -> twos_comp_out\n ))\n def pat1(x : List[Int], y : List[Int]) = {\n val pat_a = (0 until x.size).map(i=> if(x(i)>=0) a_ff(x(i)) else !a_ff(x(i).abs)).reduce(_&_)\n val pat_b = (0 until y.size).map(i=> if(y(i)>=0) b_ff(y(i)) else !b_ff(y(i).abs)).reduce(_&_)\n pat_a & pat_b\n }\n smallnum := Cat(\n pat1(List(3),List(-3, -2, -1)),\n\n pat1(List(3),List(-3, -2))& !b_ff(0) | pat1(List(2),List(-3, -2, -1)) | pat1(List(3, 2),List(-3, -2)),\n\n pat1(List(2),List(-3, -2))& !b_ff(0) | pat1(List(1),List(-3, -2, -1)) | pat1(List(3),List(-3, -1))& !b_ff(0) |\n pat1(List(3, -2),List(-3, -2, 1, 0)) | pat1(List(-3, 2, 1),List(-3, -2)) | pat1(List(3, 2),List(-3))& !b_ff(0) |\n pat1(List(3, 2),List(-3, 2, -1)) | pat1(List(3, 1),List(-3,-1)) | pat1(List(3, 2, 1),List(-3, 2)),\n\n pat1(List(2, 1, 0),List(-3, -1)) | pat1(List(3, -2, 0),List(-3, 1, 0)) | pat1(List(2),List(-3, -1))& !b_ff(0) |\n pat1(List(1),List(-3, -2))& !b_ff(0) | pat1(List(0),List(-3, -2, -1)) | pat1(List(-3, 2, -1),List(-3, -2, 1, 0)) |\n pat1(List(-3, 2, 1),List(-3))& !b_ff(0) | pat1(List(3),List(-2, -1)) & !b_ff(0) | pat1(List(3, -2),List(-3, 2, 1)) |\n pat1(List(-3, 2, 1),List(-3, 2, -1)) | pat1(List(-3, 2, 0),List(-3, -1)) | pat1(List(3, -2, -1),List(-3, 2, 0)) |\n pat1(List(-2, 1, 0),List(-3, -2)) | pat1(List(3, 2),List(-1)) & !b_ff(0) | pat1(List(-3, 2, 1, 0),List(-3, 2)) |\n pat1(List(3, 2),List(3, -2)) | pat1(List(3, 1),List(3,-2,-1)) | pat1(List(3, 0),List(-2, -1)) |\n pat1(List(3, -1),List(-3, 2, 1, 0)) | pat1(List(3, 2, 1),List(3)) & !b_ff(0) | pat1(List(3, 2, 1),List(3, -1)) |\n pat1(List(3, 2, 0),List(3, -1)) | pat1(List(3, -2, 1),List(-3, 1)) | pat1(List(3, 1, 0),List(-2)) |\n pat1(List(3, 2, 1, 0),List(3)) |pat1(List(3, 1),List(-2)) & !b_ff(0))\n\n\n val shortq_dividend = Cat(dividend_sign_ff,a_ff(31,0))\n val a_enc = Module(new exu_div_cls)\n a_enc.io.operand := shortq_dividend\n val dw_a_enc1 = a_enc.io.cls\n val b_enc = Module(new exu_div_cls)\n b_enc.io.operand := b_ff(32,0)\n val dw_b_enc1 = b_enc.io.cls\n val dw_a_enc = Cat (0.U, dw_a_enc1)\n val dw_b_enc = Cat (0.U, dw_b_enc1)\n val dw_shortq_raw = Cat(0.U,dw_b_enc) - Cat(0.U,dw_a_enc) + 1.U(7.W)\n val shortq = Mux(dw_shortq_raw(6).asBool(),0.U,dw_shortq_raw(5,0))\n shortq_enable := valid_ff & !shortq(5) & !(shortq(4,2) === \"b111\".U) & !io.cancel\n val list = Array(28,28,28,28,24,24,24,24,20,20,20,20,16,16,16,16,12,12,12,12,8,8,8,8,4,4,4,4,0,0,0,0)\n shortq_decode := Mux1H((31 to 0 by -1).map(i=> (shortq === i.U) -> list(i).U))\n shortq_shift := Mux(!shortq_enable,0.U,shortq_decode)\n b_ff := Cat(b_ff1(32),b_ff1(32),b_ff1(32),b_ff1(32),b_ff1(32),b_ff1)\n valid_ff := rvdffe(valid_ff_in, misc_enable,clock,io.scan_mode)\n control_ff := rvdffe(control_in, misc_enable,clock,io.scan_mode)\n by_zero_case_ff := rvdffe(by_zero_case,misc_enable,clock,io.scan_mode)\n shortq_enable_ff := rvdffe(shortq_enable, misc_enable,clock,io.scan_mode)\n shortq_shift_ff := rvdffe(shortq_shift, misc_enable,clock,io.scan_mode)\n finish_ff := rvdffe(finish, misc_enable,clock,io.scan_mode)\n count_ff := rvdffe(count_in, misc_enable,clock,io.scan_mode)\n\n a_ff := rvdffe(a_in, a_enable,clock,io.scan_mode)\n b_ff1 := rvdffe(b_in(32,0), b_enable,clock,io.scan_mode)\n r_ff := rvdffe(r_in, rq_enable,clock,io.scan_mode)\n q_ff := rvdffe(q_in, rq_enable,clock,io.scan_mode)\n\n}\nclass exu_div_cls extends Module{\n val io= IO(new Bundle{\n val operand = Input(UInt(33.W))\n val cls = Output(UInt(5.W))\n })\n val cls_zeros = WireInit(0.U(5.W))\n val cls_ones = WireInit(0.U(5.W))\n\n cls_zeros := Mux1H((0 until 32).map(i=> (io.operand(31,31-i)===1.U)->i.U))\n\n when(io.operand(31,0) === \"hffffffff\".U) { cls_ones := 31.U}\n .otherwise{cls_ones := Mux1H((1 until 32).map(i=> (io.operand(31,31-i) === Cat(Fill(i,1.U),0.U)).asBool -> (i-1).U ))}\n io.cls := Mux(io.operand(32),cls_ones,cls_zeros)\n} ", "groundtruth": " val pat_b = (0 until y.size).map(i=> if(y(i)>=0) m_ff(y(i)) else !m_ff(y(i).abs)).reduce(_&_)\n", "crossfile_context": ""}
{"task_id": "Quasar", "path": "Quasar/design/src/main/scala/exu/exu_mul_ctl.scala", "left_context": "package exu\n\nimport chisel3._\nimport chisel3.util._\nimport include._\nimport lib._\nimport chisel3.stage.ChiselStage\n\nclass exu_mul_ctl extends Module with RequireAsyncReset with lib {\n val io = IO(new Bundle{\n val scan_mode = Input(Bool())\n val mul_p = Flipped(Valid(new mul_pkt_t ))\n val rs1_in = Input(UInt(32.W))\n val rs2_in = Input(UInt(32.W))\n val result_x = Output(UInt(32.W))\n })\n\n val rs1_ext_in = WireInit(SInt(33.W), 0.S)\n val rs2_ext_in = WireInit(SInt(33.W), 0.S)\n val rs1_x = WireInit(SInt(33.W), 0.S)\n val rs2_x = WireInit(SInt(33.W), 0.S)\n val prod_x = WireInit(SInt(66.W), 0.S)\n val low_x = WireInit(0.U(1.W))\n\n // *** Start - BitManip ***\n // ZBE\n val ap_bext = WireInit(Bool(),0.B)\n val ap_bdep = WireInit(Bool(),0.B)\n\n // ZBC\n val ap_clmul = WireInit(Bool(),0.B)\n val ap_clmulh = WireInit(Bool(),0.B)\n val ap_clmulr = WireInit(Bool(),0.B)\n\n // ZBP\n val ap_grev = WireInit(Bool(),0.B)\n val ap_gorc = WireInit(Bool(),0.B)\n val ap_shfl = WireInit(Bool(),0.B)\n val ap_unshfl = WireInit(Bool(),0.B)\n\n // ZBR\n val ap_crc32_b = WireInit(Bool(),0.B)\n val ap_crc32_h = WireInit(Bool(),0.B)\n val ap_crc32_w = WireInit(Bool(),0.B)\n val ap_crc32c_b = WireInit(Bool(),0.B)\n val ap_crc32c_h = WireInit(Bool(),0.B)\n val ap_crc32c_w = WireInit(Bool(),0.B)\n\n // ZBF\n val ap_bfp = WireInit(Bool(),0.B)\n\n\n if (BITMANIP_ZBE == 1) {\n ap_bext := io.mul_p.bits.bext\n ap_bdep := io.mul_p.bits.bdep\n\n }\n else{\n ap_bext := 0.U\n ap_bdep := 0.U\n }\n\n if (BITMANIP_ZBC == 1) {\n ap_clmul := io.mul_p.bits.clmul\n ap_clmulh := io.mul_p.bits.clmulh\n ap_clmulr := io.mul_p.bits.clmulr\n }\n else{\n ap_clmul := 0.U\n ap_clmulh := 0.U\n ap_clmulr := 0.U\n }\n\n if (BITMANIP_ZBP == 1) {\n ap_grev := io.mul_p.bits.grev\n ap_gorc := io.mul_p.bits.gorc\n ap_shfl := io.mul_p.bits.shfl\n ap_unshfl := io.mul_p.bits.unshfl\n }\n else{\n ap_grev := 0.U\n ap_gorc := 0.U\n ap_shfl := 0.U\n ap_unshfl := 0.U\n }\n\n if (BITMANIP_ZBR == 1) {\n ap_crc32_b := io.mul_p.bits.crc32_b\n ap_crc32_h := io.mul_p.bits.crc32_h\n ap_crc32_w := io.mul_p.bits.crc32_w\n ap_crc32c_b := io.mul_p.bits.crc32c_b\n ap_crc32c_h := io.mul_p.bits.crc32c_h\n ap_crc32c_w := io.mul_p.bits.crc32c_w\n }\n else{\n ap_crc32_b := 0.U\n ap_crc32_h := 0.U\n ap_crc32_w := 0.U\n ap_crc32c_b := 0.U\n ap_crc32c_h := 0.U\n ap_crc32c_w := 0.U\n }\n\n if (BITMANIP_ZBF == 1) {\n ap_bfp := io.mul_p.bits.bfp\n }\n else{\n ap_bfp := 0.U\n }\n\n // *** End - BitManip ***\n\n val mul_x_enable = io.mul_p.valid\n val bit_x_enable = io.mul_p.valid\n rs1_ext_in := Cat(io.mul_p.bits.rs1_sign & io.rs1_in(31),io.rs1_in).asSInt\n rs2_ext_in := Cat(io.mul_p.bits.rs2_sign & io.rs2_in(31),io.rs2_in).asSInt\n\n low_x := rvdffe (io.mul_p.bits.low, mul_x_enable.asBool,clock,io.scan_mode)\n rs1_x := rvdffe(rs1_ext_in, mul_x_enable.asBool,clock,io.scan_mode)\n rs2_x := rvdffe (rs2_ext_in, mul_x_enable.asBool,clock,io.scan_mode)\n\n prod_x := rs1_x * rs2_x\n\n // * * * * * * * * * * * * * * * * * * BitManip : BEXT, BDEP * * * * * * * * * * * * * * * * * *\n\n\n // *** BEXT == \"gather\" ***\n\n def one_cal (ind:Int) : UInt = if (ind == 0) io.rs2_in(ind) else (0 to ind).map(io.rs2_in(_).asUInt).reduce(_+&_)\n val bext_d = (0 until 32).map(i=> MuxCase(false.B, (0 until 32).map(j=> (one_cal(j) === (i+1).U).asBool -> io.rs1_in(j).asUInt))).reverse.reduce(Cat(_,_))\n\n // *** BDEP == \"scatter\" ***\n val bdep_d =(0 until 32).map(j => Mux((io.rs2_in(j) === 1.U), io.rs1_in(one_cal(j)-1.U),0.U)).reverse.reduce(Cat(_,_))\n // * * * * * * * * * * * * * * * * * * BitManip : CLMUL, CLMULH, CLMULR * * * * * * * * * * * * *\n\n val clmul_raw_d = WireInit(UInt(63.W),0.U)\n clmul_raw_d := (1 until 31).map(i => Fill(63,io.rs2_in(i)) & Cat(Fill(31-i,0.U),io.rs1_in(31,0),Fill(i,0.U))).reduce(_^_) ^ ( Fill(63,io.rs2_in(0)) & Cat(Fill(31,0.U),io.rs1_in) ) ^ ( Fill(63,io.rs2_in(31)) & Cat(io.rs1_in,Fill(31,0.U)) )\n\n\n // * * * * * * * * * * * * * * * * * * BitManip : GREV * * * * * * * * * * * * * * * * * *\n\n // uint32_t grev32(uint32_t rs1, uint32_t rs2)\n // {\n // uint32_t x = rs1;\n // int shamt = rs2 & 31;\n //\n // if (shamt & 1) x = ( (x & 0x55555555) << 1) | ( (x & 0xAAAAAAAA) >> 1);\n // if (shamt & 2) x = ( (x & 0x33333333) << 2) | ( (x & 0xCCCCCCCC) >> 2);\n // if (shamt & 4) x = ( (x & 0x0F0F0F0F) << 4) | ( (x & 0xF0F0F0F0) >> 4);\n // if (shamt & 8) x = ( (x & 0x00FF00FF) << 8) | ( (x & 0xFF00FF00) >> 8);\n // if (shamt & 16) x = ( (x & 0x0000FFFF) << 16) | ( (x & 0xFFFF0000) >> 16);\n //\n // return x;\n // }\n\n\n val grev1_d = Mux(io.rs2_in(0), Range(0, 31, 2).map(i=> Cat(io.rs1_in(i),io.rs1_in(i+1))).reverse.reduce(Cat(_,_)), io.rs1_in)\n\n val grev2_d = Mux(io.rs2_in(1), Range(0, 31, 4).map(i=> Cat(grev1_d(i+1,i),grev1_d(i+1+2,i+2))).reverse.reduce(Cat(_,_)) , grev1_d(31,0))\n\n val grev4_d = Mux(io.rs2_in(2), Range(0, 31, 8).map(i=> Cat(grev2_d(i+3,i),grev2_d(i+3+4,i+4))).reverse.reduce(Cat(_,_)) , grev2_d(31,0))\n\n val grev8_d = Mux(io.rs2_in(3), Range(0, 31, 16).map(i=> Cat(grev4_d(i+7,i),grev4_d(i+7+8,i+8))).reverse.reduce(Cat(_,_)), grev4_d(31,0))\n\n val grev_d = Mux(io.rs2_in(4), Cat(grev8_d(15,0),grev8_d(31,16)), grev8_d(31,0) )\n\n // * * * * * * * * * * * * * * * * * * BitManip : GORC * * * * * * * * * * * * * * * * * *\n\n // uint32_t gorc32(uint32_t rs1, uint32_t rs2)\n // {\n // uint32_t x = rs1;\n // int shamt = rs2 & 31;\n //\n // if (shamt & 1) x |= ( (x & 0x55555555) << 1) | ( (x & 0xAAAAAAAA) >> 1);\n // if (shamt & 2) x |= ( (x & 0x33333333) << 2) | ( (x & 0xCCCCCCCC) >> 2);\n // if (shamt & 4) x |= ( (x & 0x0F0F0F0F) << 4) | ( (x & 0xF0F0F0F0) >> 4);\n // if (shamt & 8) x |= ( (x & 0x00FF00FF) << 8) | ( (x & 0xFF00FF00) >> 8);\n // if (shamt & 16) x |= ( (x & 0x0000FFFF) << 16) | ( (x & 0xFFFF0000) >> 16);\n //\n // return x;\n // }\n\n val gorc1_d = ( Fill(32,io.rs2_in(0)) & Range(0, 31, 2).map(i=> Cat(io.rs1_in(i),io.rs1_in(i+1))).reverse.reduce(Cat(_,_)) ) | io.rs1_in\n\n val gorc2_d = ( Fill(32,io.rs2_in(1)) & Range(0, 31, 4).map(i=> Cat(gorc1_d(i+1,i),gorc1_d(i+1+2,i+2))).reverse.reduce(Cat(_,_)) ) | gorc1_d\n\n val gorc4_d = ( Fill(32,io.rs2_in(2)) & Range(0, 31, 8).map(i=> Cat(gorc2_d(i+3,i),gorc2_d(i+3+4,i+4))).reverse.reduce(Cat(_,_)) ) | gorc2_d\n\n val gorc8_d = ( Fill(32,io.rs2_in(3)) & Range(0, 31, 16).map(i=> Cat(gorc4_d(i+7,i),gorc4_d(i+7+8,i+8))).reverse.reduce(Cat(_,_)) ) | gorc4_d\n\n val gorc_d = ( Fill(32,io.rs2_in(4)) & Cat(gorc8_d(15,0),gorc8_d(31,16)) ) | gorc8_d\n\n\n // * * * * * * * * * * * * * * * * * * BitManip : SHFL, UNSHLF * * * * * * * * * * * * * * * * * *\n\n // uint32_t shuffle32_stage (uint32_t src, uint32_t maskL, uint32_t maskR, int N)\n // {\n // uint32_t x = src & ~(maskL | maskR);\n // x |= ((src << N) & maskL) | ((src >> N) & maskR);\n // return x;\n // }\n //\n //\n //\n // uint32_t shfl32(uint32_t rs1, uint32_t rs2)\n // {\n // uint32_t x = rs1;\n // int shamt = rs2 & 15\n //\n // if (shamt & 8) x = shuffle32_stage(x, 0x00ff0000, 0x0000ff00, 8);\n // if (shamt & 4) x = shuffle32_stage(x, 0x0f000f00, 0x00f000f0, 4);\n // if (shamt & 2) x = shuffle32_stage(x, 0x30303030, 0xc0c0c0c0, 2);\n // if (shamt & 1) x = shuffle32_stage(x, 0x44444444, 0x22222222, 1);\n //\n // return x;\n // }\n\n\n\n val shfl8_d = Mux(io.rs2_in(3),Range(0, 9,8).map(i=> Cat(io.rs1_in(i+7+16,i+16),io.rs1_in(i+7,i))).reverse.reduce(Cat(_,_)) ,io.rs1_in)\n\n val shfl4_d = Mux(io.rs2_in(2),Range(0, 13,4).map(i=> if(i<8) Cat(shfl8_d(i+3+8,i+8),shfl8_d(i+3,i))else Cat(shfl8_d(i+3+8+8,i+8+8),shfl8_d(i+3+8,i+8))).reverse.reduce(Cat(_,_)), shfl8_d)\n\n", "right_context": "\n val shfl_d = Mux(io.rs2_in(0), Range(0, 16,1).map(i=> if(i<2) Cat(shfl2_d(i+2),shfl2_d(i))else if(i<4) Cat(shfl2_d(i+4),shfl2_d(i+2))else if(i<6) Cat(shfl2_d(i+6),shfl2_d(i+4))else if(i<8) Cat(shfl2_d(i+8),shfl2_d(i+6))else if(i<10) Cat(shfl2_d(i+10),shfl2_d(i+8))else if(i<12) Cat(shfl2_d(i+12),shfl2_d(i+10))else if(i<14) Cat(shfl2_d(i+14),shfl2_d(i+12))else Cat(shfl2_d(i+16),shfl2_d(i+14))).reverse.reduce(Cat(_,_)), shfl2_d)\n\n\n\n\n // // uint32_t unshfl32(uint32_t rs1, uint32_t rs2)\n // // {\n // // uint32_t x = rs1;\n // // int shamt = rs2 & 15\n // //\n // // if (shamt & 1) x = shuffle32_stage(x, 0x44444444, 0x22222222, 1);\n // // if (shamt & 2) x = shuffle32_stage(x, 0x30303030, 0xc0c0c0c0, 2);\n // // if (shamt & 4) x = shuffle32_stage(x, 0x0f000f00, 0x00f000f0, 4);\n // // if (shamt & 8) x = shuffle32_stage(x, 0x00ff0000, 0x0000ff00, 8);\n // //\n // // return x;\n // // }\n //\n //\n val unshfl1_d = Mux(io.rs2_in(0) , Range(0, 16,1).map(i=> if(i<2) Cat(io.rs1_in(i+2),io.rs1_in(i))else if(i<4) Cat(io.rs1_in(i+4),io.rs1_in(i+2))else if(i<6) Cat(io.rs1_in(i+6),io.rs1_in(i+4))else if(i<8) Cat(io.rs1_in(i+8),io.rs1_in(i+6))else if(i<10) Cat(io.rs1_in(i+10),io.rs1_in(i+8))else if(i<12) Cat(io.rs1_in(i+12),io.rs1_in(i+10))else if(i<14) Cat(io.rs1_in(i+14),io.rs1_in(i+12))else Cat(io.rs1_in(i+16),io.rs1_in(i+14))).reverse.reduce(Cat(_,_)) , io.rs1_in)\n\n val unshfl2_d =Mux(io.rs2_in(1) , Range(0, 15,2).map(i=> if(i<4)Cat(unshfl1_d(i+1+4,i+4),unshfl1_d(i+1,i))else if(i<8)Cat(unshfl1_d(i+9,i+8),unshfl1_d(i+5,i+4))else if(i<12)Cat(unshfl1_d(i+13,i+12),unshfl1_d(i+9,i+8))else Cat(unshfl1_d(i+17,i+16),unshfl1_d(i+13,i+12))).reverse.reduce(Cat(_,_)) , unshfl1_d)\n\n val unshfl4_d = Mux(io.rs2_in(2) , Range(0, 13,4).map(i=> if(i<8) Cat(unshfl2_d(i+3+8,i+8),unshfl2_d(i+3,i))else Cat(unshfl2_d(i+3+8+8,i+8+8),unshfl2_d(i+3+8,i+8))).reverse.reduce(Cat(_,_)) , unshfl2_d)\n\n val unshfl_d = Mux(io.rs2_in(3) , Range(0, 9,8).map(i=> Cat(unshfl4_d(i+7+16,i+16),unshfl4_d(i+7,i))).reverse.reduce(Cat(_,_)) , unshfl4_d)\n\n // * * * * * * * * * * * * * * * * * * BitManip : BFP * * * * * * * * * * * * * * * * * *\n\n\n\n val bfp_len = Cat(io.rs2_in(27,24) === 0.U,io.rs2_in(27,24)) // If LEN field is zero, then LEN=16\n val bfp_off = io.rs2_in(20,16)\n\n val bfp_len_mask_ = \"hffff_ffff\".U(32.W) << bfp_len\n val bfp_preshift_data = io.rs2_in(15,0) & ~bfp_len_mask_(15,0)\n\n val bfp_shift_data = Cat(Fill(16,0.U),bfp_preshift_data(15,0), Fill(16,0.U),bfp_preshift_data(15,0)) << bfp_off\n val bfp_shift_mask = Cat(bfp_len_mask_(31,0), bfp_len_mask_(31,0)) << bfp_off\n\n val bfp_result_d = bfp_shift_data(63,32) | (io.rs1_in & bfp_shift_mask(63,32))\n\n // * * * * * * * * * * * * * * * * * * BitManip : CRC32, CRC32c * * * * * * * * * * * * * * * * *\n\n // *** computed from https: //crccalc.com ***\n //\n // \"a\" is 8'h61 = 8'b0110_0001 (8'h61 ^ 8'hff = 8'h9e)\n //\n // Input must first be XORed with 32'hffff_ffff\n //\n //\n // CRC32\n //\n // Input Output Input Output\n // ----- -------- -------- --------\n // \"a\" e8b7be43 ffffff9e 174841bc\n // \"aa\" 078a19d7 ffff9e9e f875e628\n // \"aaaa\" ad98e545 9e9e9e9e 5267a1ba\n //\n //\n //\n // CRC32c\n //\n // Input Output Input Output\n // ----- -------- -------- --------\n // \"a\" c1d04330 ffffff9e 3e2fbccf\n // \"aa\" f1f2dac2 ffff9e9e 0e0d253d\n // \"aaaa\" 6a52eeb0 9e9e9e9e 95ad114f\n\n\n val crc32_all = ap_crc32_b | ap_crc32_h | ap_crc32_w | ap_crc32c_b | ap_crc32c_h | ap_crc32c_w\n\n val crc32_poly_rev = \"hEDB88320\".U(32.W) // bit reverse of 32'h04C11DB7\n val crc32c_poly_rev = \"h82F63B78\".U(32.W) // bit reverse of 32'h1EDC6F41\n\n\n val crc32_bd = Wire(Vec(9,UInt(32.W)))\n crc32_bd(0) := io.rs1_in\n for(i <- 1 to 8) {\n crc32_bd(i) := (crc32_bd(i-1) >> 1) ^ (crc32_poly_rev & Fill(32,crc32_bd(i-1)(0)))//io.rs1_in\n }\n\n val crc32_hd = Wire(Vec(17,UInt(32.W)))\n crc32_hd(0) := io.rs1_in\n for(i <- 1 to 16) {\n crc32_hd(i) := (crc32_hd(i-1) >> 1) ^ (crc32_poly_rev & Fill(32,crc32_hd(i-1)(0)))//io.rs1_in\n }\n\n val crc32_wd = Wire(Vec(33,UInt(32.W)))\n crc32_wd(0) := io.rs1_in\n for(i <- 1 to 32) {\n crc32_wd(i) := (crc32_wd(i-1) >> 1) ^ (crc32_poly_rev & Fill(32,crc32_wd(i-1)(0)))//io.rs1_in\n }\n /////////////////////////////////////////////////////////////////////////////////////////\n\n val crc32c_bd = Wire(Vec(9,UInt(32.W)))\n crc32c_bd(0) := io.rs1_in\n for(i <- 1 to 8) {\n crc32c_bd(i) := (crc32c_bd(i-1) >> 1) ^ (crc32c_poly_rev & Fill(32,crc32c_bd(i-1)(0)))//io.rs1_in\n }\n\n\n val crc32c_hd = Wire(Vec(17,UInt(32.W)))\n crc32c_hd(0) := io.rs1_in\n for(i <- 1 to 16) {\n crc32c_hd(i) := (crc32c_hd(i-1) >> 1) ^ (crc32c_poly_rev & Fill(32,crc32c_hd(i-1)(0)))//io.rs1_in\n }\n\n\n val crc32c_wd = Wire(Vec(33,UInt(32.W)))\n crc32c_wd(0) := io.rs1_in\n for(i <- 1 to 32) {\n crc32c_wd(i) := (crc32c_wd(i-1) >> 1) ^ (crc32c_poly_rev & Fill(32,crc32c_wd(i-1)(0)))//io.rs1_in\n }\n\n\n // * * * * * * * * * * * * * * * * * * BitManip : Common logic * * * * * * * * * * * * * * * * * *\n\n\n val bitmanip_sel_d = ap_bext | ap_bdep | ap_clmul | ap_clmulh | ap_clmulr | ap_grev | ap_gorc | ap_shfl | ap_unshfl | crc32_all | ap_bfp\n\n val bitmanip_d = Mux1H(Seq(\n ap_bext -> bext_d(31,0) ,\n ap_bdep -> bdep_d(31,0) ,\n ap_clmul -> clmul_raw_d(31,0) ,\n ap_clmulh -> Cat(0.U(1.W),clmul_raw_d(62,32)) ,\n ap_clmulr -> clmul_raw_d(62,31) ,\n ap_grev -> grev_d(31,0) ,\n ap_gorc -> gorc_d(31,0) ,\n ap_shfl -> shfl_d(31,0) ,\n ap_unshfl -> unshfl_d(31,0) ,\n ap_crc32_b -> crc32_bd(8)(31,0) ,\n ap_crc32_h -> crc32_hd(16)(31,0) ,\n ap_crc32_w -> crc32_wd(32)(31,0) ,\n ap_crc32c_b -> crc32c_bd(8)(31,0) ,\n ap_crc32c_h -> crc32c_hd(16)(31,0) ,\n ap_crc32c_w -> crc32c_wd(32)(31,0) ,\n ap_bfp -> bfp_result_d(31,0) ))\n\n val bitmanip_sel_x = rvdffe(bitmanip_sel_d,bit_x_enable,clock,io.scan_mode)\n val bitmanip_x = rvdffe(bitmanip_d,bit_x_enable,clock,io.scan_mode)\n\n\n io.result_x := (Fill(32,~bitmanip_sel_x & ~low_x) & prod_x(63,32) ) |\n (Fill(32,~bitmanip_sel_x & low_x) & prod_x(31,0) ) |\n bitmanip_x\n\n}\nobject mul extends App {\n println((new ChiselStage).emitVerilog(new exu_mul_ctl))}\n\n\n", "groundtruth": " val shfl2_d = Mux(io.rs2_in(1), Range(0, 15,2).map(i=> if(i<4)Cat(shfl4_d(i+1+4,i+4),shfl4_d(i+1,i))else if(i<8)Cat(shfl4_d(i+9,i+8),shfl4_d(i+5,i+4))else if(i<12)Cat(shfl4_d(i+13,i+12),shfl4_d(i+9,i+8))else Cat(shfl4_d(i+17,i+16),shfl4_d(i+13,i+12))).reverse.reduce(Cat(_,_)), shfl4_d)\n", "crossfile_context": ""}
{"task_id": "Quasar", "path": "Quasar/design/src/main/scala/lib/axi4_to_ahb.scala", "left_context": "package lib\n\nimport chisel3._\nimport chisel3.util._\nimport include._\n\nclass axi4_to_ahb_IO(val TAG : Int) extends Bundle {\n\n val free_clk = Input(Clock())\n val scan_mode = Input(Bool())\n val bus_clk_en = Input(Bool())\n val clk_override = Input(Bool())\n val dec_tlu_force_halt = Input(Bool())\n // AXI-4 signals\n val axi = Flipped(new axi_channels(TAG))\n // AHB-Lite signals\n val ahb = new ahb_channel()\n}\n\nclass axi4_to_ahb(val TAG : Int = 3) extends Module with lib with RequireAsyncReset {\n val io = IO(new axi4_to_ahb_IO(TAG))\n // Create bus synchronized version of force halt\n val dec_tlu_force_halt_bus_q = WireInit(Bool(), init = false.B)\n val dec_tlu_force_halt_bus = io.dec_tlu_force_halt | dec_tlu_force_halt_bus_q\n val dec_tlu_force_halt_bus_ns = !io.bus_clk_en & dec_tlu_force_halt_bus\n", "right_context": " val buf_rst = WireInit(0.U(1.W))\n buf_rst := dec_tlu_force_halt_bus\n io.ahb.out.htrans := 0.U\n val buf_state_en = WireInit(Bool(), init = false.B)\n val bus_clk = Wire(Clock())\n val ahbm_data_clk = Wire(Clock())\n val idle :: cmd_rd :: cmd_wr :: data_rd :: data_wr :: done :: stream_rd :: stream_err_rd :: Nil = Enum(8)\n val buf_state = WireInit(0.U(3.W))\n val buf_nxtstate = WireInit(0.U(3.W))\n buf_state := rvdffsc_fpga(buf_nxtstate, buf_state_en.asBool(), buf_rst, bus_clk, io.bus_clk_en, clock)\n //logic signals\n val slave_valid = WireInit(Bool(), init = false.B)\n val slave_ready = WireInit(Bool(), init = false.B)\n val slave_tag = WireInit(0.U(TAG.W)) // [TAG-1:0]\n val slave_rdata = WireInit(0.U(64.W)) // [63:0]\n val slave_opc = WireInit(0.U(4.W)) // [3:0]\n val wrbuf_en = WireInit(Bool(), init = false.B)\n val wrbuf_data_en = WireInit(Bool(), init = false.B)\n val wrbuf_cmd_sent = WireInit(Bool(), init = false.B)\n val wrbuf_rst = WireInit(Bool(), init = false.B)\n val wrbuf_vld = WireInit(Bool(), init = false.B)\n val wrbuf_data_vld = WireInit(Bool(), init = false.B)\n val wrbuf_tag = WireInit(0.U(TAG.W)) // [TAG-1:0]\n val wrbuf_size = WireInit(0.U(3.W)) // [2:0]\n val wrbuf_addr = WireInit(0.U(32.W)) // [31:0]\n val wrbuf_data = WireInit(0.U(64.W)) // [63:0]\n val wrbuf_byteen = WireInit(0.U(8.W)) // [7:0]\n\n val master_valid = WireInit(Bool(), init = false.B)\n val master_ready = WireInit(0.U(1.W))\n val master_tag = WireInit(0.U(TAG.W)) // [TAG-1:0]\n val master_addr = WireInit(0.U(32.W)) // [31:0]\n val master_wdata = WireInit(0.U(64.W)) // [63:0]\n val master_size = WireInit(0.U(3.W)) // [2:0]\n val master_opc = WireInit(0.U(3.W)) // [2:0]\n val master_byteen = WireInit(0.U(8.W)) // [7:0]\n // Buffer signals (one entry buffer)\n val buf_addr = WireInit(0.U(32.W)) // [31:0]\n val buf_size = WireInit(0.U(2.W)) // [1:0]\n val buf_write = WireInit(Bool(), init = false.B)\n val buf_byteen = WireInit(0.U(8.W)) // [7:0]\n val buf_aligned = WireInit(Bool(), init = false.B)\n val buf_data = WireInit(0.U(64.W)) // [63:0]\n val buf_tag = WireInit(0.U(TAG.W)) // [TAG-1:0]\n //Miscellaneous signals\n // val buf_rst = WireInit(Bool(), init = false.B)\n val buf_tag_in = WireInit(0.U(TAG.W)) // [TAG-1:0]\n val buf_addr_in = WireInit(0.U(32.W)) // [31:0]\n val buf_byteen_in = WireInit(0.U(8.W)) // [7:0]\n val buf_data_in = WireInit(0.U(64.W)) // [63:0]\n val buf_write_in = WireInit(Bool(), init = false.B)\n val buf_aligned_in = WireInit(Bool(), init = false.B)\n val buf_size_in = WireInit(0.U(3.W)) // [2:0]\n\n // val buf_state_en = WireInit(Bool(), init = false.B)\n val buf_wr_en = WireInit(Bool(), init = false.B)\n val buf_data_wr_en = WireInit(Bool(), init = false.B)\n val slvbuf_error_en = WireInit(Bool(), init = false.B)\n val wr_cmd_vld = WireInit(Bool(), init = false.B)\n\n val cmd_done_rst = WireInit(Bool(), init = false.B)\n val cmd_done = WireInit(Bool(), init = false.B)\n val cmd_doneQ = WireInit(Bool(), init = false.B)\n val trxn_done = WireInit(Bool(), init = false.B)\n val buf_cmd_byte_ptr = WireInit(0.U(3.W)) // [2:0]\n val buf_cmd_byte_ptrQ = WireInit(0.U(3.W)) // [2:0]\n val buf_cmd_nxtbyte_ptr = WireInit(0.U(3.W)) // [2:0]\n val buf_cmd_byte_ptr_en = WireInit(Bool(), init = false.B)\n val found = WireInit(Bool(), init = false.B)\n\n val slave_valid_pre = WireInit(Bool(), init = false.B)\n val ahb_hready_q = WireInit(Bool(), init = false.B)\n val ahb_hresp_q = WireInit(Bool(), init = false.B)\n val ahb_htrans_q = WireInit(0.U(2.W)) // [1:0]\n val ahb_hwrite_q = WireInit(Bool(), init = false.B)\n val ahb_hrdata_q = WireInit(0.U(64.W)) // [63:0]\n\n val slvbuf_write = WireInit(Bool(), init = false.B)\n val slvbuf_error = WireInit(Bool(), init = false.B)\n val slvbuf_tag = WireInit(0.U(TAG.W)) // [TAG-1:0]\n\n val slvbuf_error_in = WireInit(Bool(), init = false.B)\n val slvbuf_wr_en = WireInit(Bool(), init = false.B)\n val bypass_en = WireInit(Bool(), init = false.B)\n val rd_bypass_idle = WireInit(Bool(), init = false.B)\n\n val last_addr_en = WireInit(Bool(), init = false.B)\n val last_bus_addr = WireInit(0.U(32.W)) // [31:0]\n // Clocks\n val buf_clken = WireInit(Bool(), init = false.B)\n val ahbm_data_clken = WireInit(Bool(), init = false.B)\n val buf_clk = Wire(Clock())\n def get_write_size(byteen: UInt) = {\n val size = (\"b11\".U & Fill(2, (byteen(7, 0) === \"hff\".U))) |\n (\"b10\".U & (Fill(2, ((byteen(7, 0) === \"hf0\".U) | (byteen(7, 0) === \"h0f\".U(8.W)))))) |\n (\"b01\".U(2.W) & (Fill(2, ((byteen(7, 0) === \"hc0\".U) | (byteen(7, 0) === \"h30\".U) | (byteen(7, 0) === \"h0c\".U(8.W)) | (byteen(7, 0) === \"h03\".U(8.W))))))\n size\n }\n\n def get_write_addr(byteen_e: UInt) = {\n val addr = (\"h0\".U(3.W) & (Fill(3, ((byteen_e(7, 0) === \"hff\".U) | (byteen_e(7, 0) === \"h0f\".U(8.W)) | (byteen_e(7, 0) === \"h03\".U(8.W)))))) |\n (\"h2\".U & (Fill(3, (byteen_e(7, 0) === \"h0c\".U(8.W))))) |\n (\"h4\".U & (Fill(3, ((byteen_e(7, 0) === \"hf0\".U) | (byteen_e(7, 0) === \"h03\".U(8.W)))))) |\n (\"h6\".U & (Fill(3, (byteen_e(7, 0) === \"hc0\".U))))\n (\"h6\".U & (Fill(3, (byteen_e(7, 0) === \"hc0\".U))))\n addr\n }\n\n def get_nxtbyte_ptr(current_byte_ptr: UInt, byteen: UInt, get_next: Bool): UInt = {\n val start_ptr = Mux(get_next, current_byte_ptr + 1.U, current_byte_ptr)\n val temp = (0 until 8).map(j => (byteen(j) & (j.asUInt() >= start_ptr)) -> j.U)\n MuxCase(7.U, temp)\n }\n wr_cmd_vld := wrbuf_vld & wrbuf_data_vld\n master_valid := wr_cmd_vld | io.axi.ar.valid\n master_tag := Mux(wr_cmd_vld.asBool(), wrbuf_tag(TAG - 1, 0), io.axi.ar.bits.id(TAG - 1, 0))\n master_opc := Mux(wr_cmd_vld.asBool(), \"b011\".U, \"b0\".U)\n master_addr := Mux(wr_cmd_vld.asBool(), wrbuf_addr(31, 0), io.axi.ar.bits.addr(31, 0))\n master_size := Mux(wr_cmd_vld.asBool(), wrbuf_size(2, 0), io.axi.ar.bits.size(2, 0))\n master_byteen := wrbuf_byteen(7, 0)\n master_wdata := wrbuf_data(63, 0)\n\n // AXI response channel signals\n io.axi.b.valid := slave_valid & slave_ready & slave_opc(3)\n io.axi.b.bits.resp := Mux(slave_opc(0), \"b10\".U, Mux(slave_opc(1), \"b11\".U, \"b0\".U))\n io.axi.b.bits.id := slave_tag(TAG - 1, 0)\n\n io.axi.r.valid := slave_valid & slave_ready & (slave_opc(3, 2) === \"b0\".U)\n io.axi.r.bits.resp := Mux(slave_opc(0), \"b10\".U, Mux(slave_opc(1), \"b11\".U, \"b0\".U))\n io.axi.r.bits.id := slave_tag(TAG - 1, 0)\n io.axi.r.bits.data := slave_rdata(63, 0)\n slave_ready := io.axi.b.ready & io.axi.r.ready\n\n switch(buf_state) {\n is(idle) {\n master_ready := 1.U\n buf_write_in := (master_opc(2, 1) === \"b01\".U)\n buf_nxtstate := Mux(buf_write_in.asBool(), cmd_wr, cmd_rd)\n buf_state_en := master_valid & 1.U\n buf_wr_en := buf_state_en\n buf_data_wr_en := buf_state_en & (buf_nxtstate === cmd_wr)\n buf_cmd_byte_ptr_en := buf_state_en\n buf_cmd_byte_ptr := Mux(buf_write_in.asBool(), (get_nxtbyte_ptr(0.U(3.W), buf_byteen_in(7, 0), false.B)), master_addr(2, 0))\n bypass_en := buf_state_en\n rd_bypass_idle := bypass_en & (buf_nxtstate === cmd_rd)\n io.ahb.out.htrans := (Fill(2, bypass_en)) & \"b10\".U\n }\n\n is(cmd_rd) {\n buf_nxtstate := Mux((master_valid & (master_opc(2, 0) === \"b000\".U)).asBool(), stream_rd, data_rd)\n buf_state_en := ahb_hready_q & (ahb_htrans_q(1, 0) =/= \"b0\".U) & !ahb_hwrite_q\n cmd_done := buf_state_en & !master_valid\n slvbuf_wr_en := buf_state_en\n master_ready := (ahb_hready_q & (ahb_htrans_q(1, 0) =/= \"b0\".U) & !ahb_hwrite_q) & (Mux((master_valid & (master_opc(2, 0) === \"b000\".U)).asBool(), stream_rd, data_rd) === stream_rd) ////////////TBD////////\n buf_wr_en := master_ready\n bypass_en := master_ready & master_valid\n buf_cmd_byte_ptr := Mux(bypass_en.asBool(), master_addr(2, 0), buf_addr(2, 0))\n io.ahb.out.htrans := \"b10\".U & (Fill(2, (!buf_state_en | bypass_en)))\n }\n\n is(stream_rd) {\n master_ready := (ahb_hready_q & !ahb_hresp_q) & ~(master_valid & master_opc(2, 1) === \"b01\".U)\n buf_wr_en := (master_valid & master_ready & (master_opc(2, 0) === \"b000\".U)) // update the fifo if we are streaming the read commands\n buf_nxtstate := Mux(ahb_hresp_q.asBool(), stream_err_rd, Mux((master_valid & master_ready & (master_opc(2, 0) === \"b000\".U)).asBool(), stream_rd, data_rd)) // assuming that the master accpets the slave response right away.\n buf_state_en := (ahb_hready_q | ahb_hresp_q)\n buf_data_wr_en := buf_state_en\n slvbuf_error_in := ahb_hresp_q\n slvbuf_error_en := buf_state_en\n slave_valid_pre := buf_state_en & !ahb_hresp_q // send a response right away if we are not going through an error response.\n cmd_done := buf_state_en & !master_valid // last one of the stream should not send a htrans\n bypass_en := master_ready & master_valid & (buf_nxtstate === stream_rd) & buf_state_en\n buf_cmd_byte_ptr := Mux(bypass_en.asBool(), master_addr(2, 0), buf_addr(2, 0))\n io.ahb.out.htrans := \"b10\".U & Fill(2, (!((buf_nxtstate =/= stream_rd) & buf_state_en)))\n slvbuf_wr_en := buf_wr_en // shifting the contents from the buf to slv_buf for streaming cases\n }\n\n is(stream_err_rd) {\n buf_nxtstate := data_rd\n buf_state_en := ahb_hready_q & (ahb_htrans_q(1, 0) =/= \"b0\".U) & !ahb_hwrite_q\n slave_valid_pre := buf_state_en\n slvbuf_wr_en := buf_state_en // Overwrite slvbuf with buffer\n buf_cmd_byte_ptr := buf_addr(2, 0)\n io.ahb.out.htrans := \"b10\".U(2.W) & Fill(2, !buf_state_en)\n }\n\n is(data_rd) {\n buf_nxtstate := done\n buf_state_en := (ahb_hready_q | ahb_hresp_q)\n buf_data_wr_en := buf_state_en\n slvbuf_error_in := ahb_hresp_q\n slvbuf_error_en := buf_state_en\n slvbuf_wr_en := buf_state_en\n }\n\n is(cmd_wr) {\n buf_nxtstate := data_wr\n trxn_done := ahb_hready_q & ahb_hwrite_q & (ahb_htrans_q(1, 0) =/= \"b0\".U)\n buf_state_en := trxn_done\n buf_cmd_byte_ptr_en := buf_state_en\n slvbuf_wr_en := buf_state_en\n buf_cmd_byte_ptr := Mux(trxn_done.asBool(), (get_nxtbyte_ptr(buf_cmd_byte_ptrQ(2, 0), buf_byteen(7, 0), true.B)), buf_cmd_byte_ptrQ)\n cmd_done := trxn_done & (buf_aligned | (buf_cmd_byte_ptrQ === \"b111\".U) | (buf_byteen((get_nxtbyte_ptr(buf_cmd_byte_ptrQ(2, 0), buf_byteen(7, 0), true.B))) === \"b0\".U))\n io.ahb.out.htrans := Fill(2, !(cmd_done | cmd_doneQ)) & \"b10\".U\n }\n\n is(data_wr) {\n buf_state_en := (cmd_doneQ & ahb_hready_q) | ahb_hresp_q\n master_ready := buf_state_en & !ahb_hresp_q & slave_ready\n buf_nxtstate := Mux((ahb_hresp_q | !slave_ready), done, Mux((master_valid & master_valid), Mux((master_opc(2, 1) === 1.U).asBool(), cmd_wr, cmd_rd), idle))\n slvbuf_error_in := ahb_hresp_q\n slvbuf_error_en := buf_state_en\n buf_write_in := master_opc(2, 1) === 1.U\n buf_wr_en := buf_state_en & ((buf_nxtstate === cmd_wr) | (buf_nxtstate === cmd_rd))\n buf_data_wr_en := buf_wr_en\n cmd_done := (ahb_hresp_q | (ahb_hready_q & (ahb_htrans_q(1, 0) =/= 0.U) &\n ((buf_cmd_byte_ptrQ === 7.U) | (buf_byteen(get_nxtbyte_ptr(buf_cmd_byte_ptrQ(2, 0), buf_byteen(7, 0), true.B)) === 0.U))))\n bypass_en := buf_state_en & buf_write_in & (buf_nxtstate === cmd_wr)\n io.ahb.out.htrans := Fill(2, (!(cmd_done | cmd_doneQ) | bypass_en)) & 2.U\n slave_valid_pre := buf_state_en & (buf_nxtstate =/= done)\n trxn_done := ahb_hready_q & ahb_hwrite_q & (ahb_htrans_q(1, 0) =/= 0.U)\n buf_cmd_byte_ptr_en := trxn_done | bypass_en\n buf_cmd_byte_ptr := Mux(bypass_en, get_nxtbyte_ptr(0.U(3.W), buf_byteen_in(7, 0), false.B), Mux(trxn_done, get_nxtbyte_ptr(buf_cmd_byte_ptrQ(2, 0), buf_byteen(7, 0), true.B), buf_cmd_byte_ptrQ))\n }\n is(done) {\n buf_nxtstate := idle\n buf_state_en := slave_ready\n slvbuf_error_en := true.B\n slave_valid_pre := true.B\n }\n }\n // buf_rst := 0.U\n cmd_done_rst := slave_valid_pre\n buf_addr_in := Cat(master_addr(31, 3), Mux((buf_aligned_in & (master_opc(2, 1) === \"b01\".U)).asBool(), get_write_addr(master_byteen(7, 0)), master_addr(2, 0)))\n buf_tag_in := master_tag(TAG - 1, 0)\n buf_byteen_in := wrbuf_byteen(7, 0)\n buf_data_in := Mux((buf_state === data_rd), ahb_hrdata_q(63, 0), master_wdata(63, 0))\n buf_size_in := Mux((buf_aligned_in & (master_size(1, 0) === \"b11\".U) & (master_opc(2, 1) === \"b01\".U)).asBool(), get_write_size(master_byteen(7, 0)), master_size(1, 0))\n buf_aligned_in := (master_opc(2, 0) === 0.U) | // reads are always aligned since they are either DW or sideeffects\n (master_size(1, 0) === 0.U) | (master_size(1, 0) === \"b01\".U(2.W)) | (master_size(1, 0) === \"b10\".U) | // Always aligned for Byte/HW/Word since they can be only for non-idempotent. IFU/SB are always aligned\n ((master_size(1, 0) === \"b11\".U) & ((master_byteen(7, 0) === \"h3\".U) | (master_byteen(7, 0) === \"hc\".U) | (master_byteen(7, 0) === \"h30\".U) | (master_byteen(7, 0) === \"hc0\".U) |\n (master_byteen(7, 0) === \"hf\".U) | (master_byteen(7, 0) === \"hf0\".U) | (master_byteen(7, 0) === \"hff\".U)))\n // Generate the ahb signals\n io.ahb.out.haddr := Cat(Mux(bypass_en.asBool(), master_addr(31, 3), buf_addr(31, 3)), Fill(3, io.ahb.out.htrans === 2.U) & buf_cmd_byte_ptr)\n io.ahb.out.hsize := Mux(bypass_en.asBool(), Cat(0.U, (Fill(2, buf_aligned_in) & buf_size_in(1, 0))), Cat(\"b0\".U, (Fill(2, buf_aligned) & buf_size(1, 0))))\n\n io.ahb.out.hburst := \"b0\".U\n io.ahb.out.hmastlock := \"b0\".U\n io.ahb.out.hprot := Cat(\"b001\".U, !io.axi.ar.bits.prot(2))\n io.ahb.out.hwrite := Mux(bypass_en.asBool(), (master_opc(2, 1) === \"b01\".U), buf_write)\n io.ahb.out.hwdata := buf_data(63, 0)\n\n slave_valid := slave_valid_pre\n slave_opc := Cat(Mux(slvbuf_write.asBool(), \"b11\".U, \"b00\".U), Fill(2, slvbuf_error) & \"b10\".U)\n slave_rdata := Mux(slvbuf_error.asBool(), Fill(2, last_bus_addr(31, 0)), Mux((buf_state === done), buf_data(63, 0), ahb_hrdata_q(63, 0)))\n slave_tag := slvbuf_tag(TAG - 1, 0)\n\n last_addr_en := (io.ahb.out.htrans(1, 0) =/= \"b0\".U) & io.ahb.in.hready & io.ahb.out.hwrite\n // Write buffer\n wrbuf_en := io.axi.aw.valid & io.axi.aw.ready & master_ready\n wrbuf_data_en := io.axi.w.valid & io.axi.w.ready & master_ready\n wrbuf_cmd_sent := master_valid & master_ready & (master_opc(2, 1) === \"b01\".U)\n wrbuf_rst := (wrbuf_cmd_sent & !wrbuf_en) | dec_tlu_force_halt_bus\n\n io.axi.aw.ready := !(wrbuf_vld & !wrbuf_cmd_sent) & master_ready\n io.axi.w.ready := !(wrbuf_data_vld & !wrbuf_cmd_sent) & master_ready\n io.axi.ar.ready := !(wrbuf_vld & wrbuf_data_vld) & master_ready\n io.axi.r.bits.last := true.B\n\n wrbuf_vld := rvdffsc_fpga(1.U, wrbuf_en.asBool(), wrbuf_rst, bus_clk, io.bus_clk_en, clock)\n wrbuf_data_vld := rvdffsc_fpga(1.U, wrbuf_data_en.asBool(), wrbuf_rst, bus_clk, io.bus_clk_en, clock)\n wrbuf_tag := rvdffs_fpga(io.axi.aw.bits.id(TAG - 1, 0), wrbuf_en.asBool(), bus_clk, io.bus_clk_en, clock)\n wrbuf_size := rvdffs_fpga(io.axi.aw.bits.size(2, 0), wrbuf_en.asBool(), bus_clk, io.bus_clk_en, clock)\n wrbuf_addr := rvdffe(io.axi.aw.bits.addr, wrbuf_en.asBool & io.bus_clk_en, clock, io.scan_mode)\n wrbuf_data := rvdffe(io.axi.w.bits.data, wrbuf_data_en.asBool & io.bus_clk_en, clock, io.scan_mode)\n wrbuf_byteen := rvdffs_fpga(io.axi.w.bits.strb(7, 0), wrbuf_data_en.asBool(), bus_clk, io.bus_clk_en, clock)\n last_bus_addr := rvdffs_fpga(io.ahb.out.haddr(31, 0), last_addr_en.asBool(), bus_clk, io.bus_clk_en, clock)\n buf_write := rvdffs_fpga(buf_write_in, buf_wr_en.asBool(), buf_clk, buf_clken, clock)\n buf_tag := rvdffs_fpga(buf_tag_in(TAG - 1, 0), buf_wr_en.asBool(), buf_clk, buf_clken, clock)\n buf_addr := rvdffe(buf_addr_in(31, 0), (buf_wr_en & io.bus_clk_en).asBool, clock, io.scan_mode)\n buf_size := rvdffs_fpga(buf_size_in(1,0), buf_wr_en.asBool(), buf_clk, buf_clken, clock)\n buf_aligned := rvdffs_fpga(buf_aligned_in, buf_wr_en.asBool(), buf_clk, buf_clken, clock)\n buf_byteen := rvdffs_fpga(buf_byteen_in(7, 0), buf_wr_en.asBool(), buf_clk, buf_clken, clock)\n buf_data := rvdffe(buf_data_in(63, 0), (buf_data_wr_en & io.bus_clk_en).asBool(), clock, io.scan_mode)\n slvbuf_write := rvdffs_fpga(buf_write, slvbuf_wr_en.asBool(), buf_clk, buf_clken, clock)\n slvbuf_tag := rvdffs_fpga(buf_tag(TAG - 1, 0), slvbuf_wr_en.asBool(), buf_clk, buf_clken, clock)\n slvbuf_error := rvdffs_fpga(slvbuf_error_in, slvbuf_error_en.asBool(), bus_clk, io.bus_clk_en, clock)\n cmd_doneQ := rvdffsc_fpga(1.U, cmd_done.asBool(), cmd_done_rst, bus_clk, io.bus_clk_en, clock)\n buf_cmd_byte_ptrQ := rvdffs_fpga(buf_cmd_byte_ptr(2, 0), buf_cmd_byte_ptr_en.asBool(), bus_clk, io.bus_clk_en, clock)\n ahb_hready_q := rvdff_fpga(io.ahb.in.hready, bus_clk, io.bus_clk_en, clock)\n ahb_htrans_q := rvdff_fpga(io.ahb.out.htrans(1, 0), bus_clk,io.bus_clk_en, clock)\n ahb_hwrite_q := rvdff_fpga(io.ahb.out.hwrite,bus_clk, io.bus_clk_en, clock)\n ahb_hresp_q := rvdff_fpga(io.ahb.in.hresp,bus_clk, io.bus_clk_en, clock)\n ahb_hrdata_q := rvdff_fpga(io.ahb.in.hrdata(63, 0), ahbm_data_clk, ahbm_data_clken, clock)\n buf_clken := io.bus_clk_en & (buf_wr_en | slvbuf_wr_en | io.clk_override)\n ahbm_data_clken := io.bus_clk_en & ((buf_state =/= idle) | io.clk_override)\n if (RV_FPGA_OPTIMIZE) {\n bus_clk := 0.B.asClock()\n buf_clk := 0.B.asClock()\n ahbm_data_clk := 0.B.asClock()\n }\n else {\n buf_clk := rvclkhdr(clock, buf_clken, io.scan_mode)\n bus_clk := rvclkhdr(clock, io.bus_clk_en, io.scan_mode)\n ahbm_data_clk := rvclkhdr(clock, ahbm_data_clken, io.scan_mode)\n }\n}\n\nobject axi4_to_ahb extends App {\n println((new chisel3.stage.ChiselStage).emitVerilog(new axi4_to_ahb(1)))\n}", "groundtruth": " dec_tlu_force_halt_bus_q := withClock(io.free_clk) {RegNext(dec_tlu_force_halt_bus_ns, 0.U)}\n", "crossfile_context": ""}
{"task_id": "Quasar", "path": "Quasar/design/src/main/scala/lsu/lsu_stbuf.scala", "left_context": "package lsu\nimport lib._\nimport chisel3._\nimport chisel3.experimental.chiselName\nimport chisel3.util._\nimport include._\n\n@chiselName\nclass lsu_stbuf extends Module with lib with RequireAsyncReset {\n val io = IO (new Bundle {\n val lsu_stbuf_c1_clk \t = Input(Clock())\n val lsu_free_c2_clk \t = Input(Clock())\n val lsu_pkt_m \t = Flipped(Valid(new lsu_pkt_t))\n val lsu_pkt_r \t = Flipped(Valid(new lsu_pkt_t))\n val store_stbuf_reqvld_r\t = Input(Bool())\n val lsu_commit_r = Input(Bool())\n val dec_lsu_valid_raw_d = Input(Bool())\n val store_data_hi_r\t \t \t = Input(UInt(DCCM_DATA_WIDTH.W))\n val store_data_lo_r\t \t \t = Input(UInt(DCCM_DATA_WIDTH.W))\n val store_datafn_hi_r = Input(UInt(DCCM_DATA_WIDTH.W))\n val store_datafn_lo_r\t \t = Input(UInt(DCCM_DATA_WIDTH.W))\n val lsu_stbuf_commit_any\t \t= Input(Bool())\n val lsu_addr_d\t \t \t\t = Input(UInt(LSU_SB_BITS.W))\n val lsu_addr_m\t \t \t\t = Input(UInt(32.W))\n val lsu_addr_r\t \t \t\t = Input(UInt(32.W))\n val end_addr_d\t \t \t\t = Input(UInt(LSU_SB_BITS.W))\n val end_addr_m\t \t \t\t = Input(UInt(32.W))\n val end_addr_r\t \t \t\t = Input(UInt(32.W))\n val ldst_dual_d = Input(Bool())\n val ldst_dual_m = Input(Bool())\n val ldst_dual_r = Input(Bool())\n val addr_in_dccm_m = Input(Bool())\n val addr_in_dccm_r \t \t = Input(Bool())\n val lsu_cmpen_m \t = Input(Bool())\n val scan_mode = Input(Bool())\n\n //Outputs\n val stbuf_reqvld_any \t \t = Output(Bool())\n val stbuf_reqvld_flushed_any = Output(Bool())\n val stbuf_addr_any \t \t = Output(UInt(LSU_SB_BITS.W))\n val stbuf_data_any \t \t = Output(UInt(DCCM_DATA_WIDTH.W))\n val lsu_stbuf_full_any \t = Output(Bool())\n val lsu_stbuf_empty_any \t = Output(Bool())\n val ldst_stbuf_reqvld_r \t = Output(Bool())\n val stbuf_fwddata_hi_m \t = Output(UInt(DCCM_DATA_WIDTH.W))\n val stbuf_fwddata_lo_m \t = Output(UInt(DCCM_DATA_WIDTH.W))\n val stbuf_fwdbyteen_hi_m \t = Output(UInt(DCCM_BYTE_WIDTH.W))\n val stbuf_fwdbyteen_lo_m \t = Output(UInt(DCCM_BYTE_WIDTH.W))\n })\n\n io.stbuf_reqvld_any \t\t\t := 0.U\n io.stbuf_reqvld_flushed_any := 0.U\n io.stbuf_addr_any \t := 0.U\n io.stbuf_data_any \t := 0.U\n io.lsu_stbuf_full_any \t \t := 0.U\n io.lsu_stbuf_empty_any \t \t := 0.U\n io.ldst_stbuf_reqvld_r \t \t := 0.U\n io.stbuf_fwddata_hi_m \t \t := 0.U\n io.stbuf_fwddata_lo_m \t \t := 0.U\n io.stbuf_fwdbyteen_hi_m \t := 0.U\n io.stbuf_fwdbyteen_lo_m \t := 0.U\n\n\n val stbuf_vld = WireInit(UInt(LSU_STBUF_DEPTH.W), init = 0.U)\n val stbuf_wr_en = WireInit(UInt(LSU_STBUF_DEPTH.W), init = 0.U)\n val stbuf_dma_kill_en = WireInit(UInt(LSU_STBUF_DEPTH.W), init = 0.U)\n val stbuf_dma_kill = WireInit(UInt(LSU_STBUF_DEPTH.W), init = 0.U)\n val stbuf_reset = WireInit(UInt(LSU_STBUF_DEPTH.W), init = 0.U)\n val store_byteen_ext_r = WireInit(UInt(8.W), init= 0.U)\n val stbuf_addr = Wire(Vec(LSU_STBUF_DEPTH,UInt(LSU_SB_BITS.W)))\n stbuf_addr := (0 until LSU_STBUF_DEPTH).map(i => 0.U)\n val stbuf_byteen = Wire(Vec(LSU_STBUF_DEPTH,UInt(DCCM_BYTE_WIDTH.W)))\n stbuf_byteen := (0 until LSU_STBUF_DEPTH).map(i => 0.U)\n val stbuf_data = Wire(Vec(LSU_STBUF_DEPTH,UInt(DCCM_DATA_WIDTH.W)))\n stbuf_data := (0 until LSU_STBUF_DEPTH).map(i => 0.U)\n val stbuf_addrin = Wire(Vec(LSU_STBUF_DEPTH,UInt(LSU_SB_BITS.W)))\n stbuf_addrin := (0 until LSU_STBUF_DEPTH).map(i => 0.U)\n val stbuf_datain = Wire(Vec(LSU_STBUF_DEPTH,UInt(DCCM_DATA_WIDTH.W)))\n stbuf_datain := (0 until LSU_STBUF_DEPTH).map(i => 0.U)\n val stbuf_byteenin = Wire(Vec(LSU_STBUF_DEPTH,UInt(DCCM_BYTE_WIDTH.W)))\n stbuf_byteenin := (0 until LSU_STBUF_DEPTH).map(i => 0.U)\n val WrPtr = WireInit(UInt(log2Ceil(LSU_STBUF_DEPTH).W),init = 0.U)\n val RdPtr = WireInit(UInt(log2Ceil(LSU_STBUF_DEPTH).W),init = 0.U)\n val cmpaddr_hi_m = WireInit(0.U(16.W))\n val stbuf_specvld_m = WireInit(0.U(2.W))\n val stbuf_specvld_r = WireInit(0.U(2.W))\n val cmpaddr_lo_m = WireInit(0.U(16.W))\n val stbuf_fwdata_hi_pre_m\t= WireInit(UInt(DCCM_DATA_WIDTH.W),init = 0.U)\n val stbuf_fwdata_lo_pre_m\t= WireInit(UInt(DCCM_DATA_WIDTH.W),init = 0.U)\n val ld_byte_rhit_lo_lo\t \t= WireInit(UInt(DCCM_BYTE_WIDTH.W),init = 0.U)\n val ld_byte_rhit_hi_lo\t \t= WireInit(UInt(DCCM_BYTE_WIDTH.W),init = 0.U)\n val ld_byte_rhit_lo_hi\t \t= WireInit(UInt(DCCM_BYTE_WIDTH.W),init = 0.U)\n val ld_byte_rhit_hi_hi\t \t= WireInit(UInt(DCCM_BYTE_WIDTH.W),init = 0.U)\n val ld_byte_hit_lo\t = WireInit(UInt(DCCM_BYTE_WIDTH.W),init = 0.U)\n val ld_byte_rhit_lo\t = WireInit(UInt(DCCM_BYTE_WIDTH.W),init = 0.U)\n val ld_byte_hit_hi\t = WireInit(UInt(DCCM_BYTE_WIDTH.W),init = 0.U)\n val ld_byte_rhit_hi\t = WireInit(UInt(DCCM_BYTE_WIDTH.W),init = 0.U)\n val ldst_byteen_ext_r\t \t= WireInit(UInt(8.W),init = 0.U)\n val ld_fwddata_rpipe_lo\t \t= WireInit(UInt(32.W),init = 0.U)\n val ld_fwddata_rpipe_hi\t \t= WireInit(UInt(32.W),init = 0.U)\n\n //\n val datain1 = Wire(Vec(LSU_STBUF_DEPTH,UInt(8.W)))\n val datain2 = Wire(Vec(LSU_STBUF_DEPTH,UInt(8.W)))\n val datain3 = Wire(Vec(LSU_STBUF_DEPTH,UInt(8.W)))\n val datain4 = Wire(Vec(LSU_STBUF_DEPTH,UInt(8.W)))\n\n //////////////////////////////////////Code Start here///////////////////////////////\n val ldst_byteen_r = Mux1H(Seq(\n io.lsu_pkt_r.bits.by.asBool -> \"b00000001\".U,\n io.lsu_pkt_r.bits.half.asBool ->\"b00000011\".U,\n io.lsu_pkt_r.bits.word.asBool -> \"b00001111\".U,\n io.lsu_pkt_r.bits.dword.asBool -> \"b11111111\".U\n ))\n val dual_stbuf_write_r = io.ldst_dual_r & io.store_stbuf_reqvld_r\n\n store_byteen_ext_r := ldst_byteen_r << io.lsu_addr_r(1,0)\n val store_byteen_hi_r = store_byteen_ext_r (7,4) & Fill(4, io.lsu_pkt_r.bits.store)\n val store_byteen_lo_r = store_byteen_ext_r (3,0) & Fill(4, io.lsu_pkt_r.bits.store)\n\n val RdPtrPlus1 = RdPtr + \"b01\".U\n val WrPtrPlus1 = WrPtr + \"b01\".U\n val WrPtrPlus2 = WrPtr + \"b10\".U\n\n io.ldst_stbuf_reqvld_r := (io.lsu_commit_r | io.lsu_pkt_r.bits.dma) & io.store_stbuf_reqvld_r\n\n val store_matchvec_lo_r = (0 until LSU_STBUF_DEPTH).map(i=> (stbuf_addr(i)(LSU_SB_BITS-1,log2Ceil(DCCM_BYTE_WIDTH)) === io.lsu_addr_r(LSU_SB_BITS-1,log2Ceil(DCCM_BYTE_WIDTH)) & stbuf_vld(i) & !stbuf_dma_kill(i) & !stbuf_reset(i)).asUInt).reverse.reduce(Cat(_,_))\n val store_matchvec_hi_r = (0 until LSU_STBUF_DEPTH).map(i=> (stbuf_addr(i)(LSU_SB_BITS-1,log2Ceil(DCCM_BYTE_WIDTH)) === io.end_addr_r(LSU_SB_BITS-1,log2Ceil(DCCM_BYTE_WIDTH)) & stbuf_vld(i) & !stbuf_dma_kill(i) & dual_stbuf_write_r & !stbuf_reset(i)).asUInt).reverse.reduce(Cat(_,_))\n\n val store_coalesce_lo_r = store_matchvec_lo_r.orR\n val store_coalesce_hi_r = store_matchvec_hi_r.orR\n if (DCCM_ENABLE == 1) {\n stbuf_wr_en := (0 until LSU_STBUF_DEPTH).map(i => (io.ldst_stbuf_reqvld_r & (\n ((i.asUInt === WrPtr) & !store_coalesce_lo_r) |\n ((i.asUInt === WrPtr) & dual_stbuf_write_r & !store_coalesce_hi_r) |\n ((i.asUInt === WrPtrPlus1) & dual_stbuf_write_r & !(store_coalesce_lo_r | store_coalesce_hi_r)) |\n store_matchvec_lo_r(i) | store_matchvec_hi_r(i))).asUInt).reverse.reduce(Cat(_, _))\n stbuf_reset := (0 until LSU_STBUF_DEPTH).map(i => ((io.lsu_stbuf_commit_any | io.stbuf_reqvld_flushed_any) & (i.asUInt === RdPtr).asBool).asUInt).reverse.reduce(Cat(_, _))\n val sel_lo = (0 until LSU_STBUF_DEPTH).map(i => (((!io.ldst_dual_r | io.store_stbuf_reqvld_r) & (i.asUInt === WrPtr).asBool & !store_coalesce_lo_r) | store_matchvec_lo_r(i)).asUInt).reverse.reduce(Cat(_, _))\n\n stbuf_addrin := (0 until LSU_STBUF_DEPTH).map(i => Mux(sel_lo(i), io.lsu_addr_r(LSU_SB_BITS - 1, 0), io.end_addr_r(LSU_SB_BITS - 1, 0)))\n stbuf_byteenin := (0 until LSU_STBUF_DEPTH).map(i => Mux(sel_lo(i), stbuf_byteen(i) | store_byteen_lo_r, stbuf_byteen(i) | store_byteen_hi_r).asUInt)\n\n datain1 := (0 until LSU_STBUF_DEPTH).map(i => Mux(sel_lo(i), Mux(!stbuf_byteen(i)(0) | store_byteen_lo_r(0), io.store_datafn_lo_r(7, 0), stbuf_data(i)(7, 0)),\n Mux(!stbuf_byteen(i)(0) | store_byteen_hi_r(0), io.store_datafn_hi_r(7, 0), stbuf_data(i)(7, 0))).asUInt)\n\n datain2 := (0 until LSU_STBUF_DEPTH).map(i => Mux(sel_lo(i), Mux(!stbuf_byteen(i)(1) | store_byteen_lo_r(1), io.store_datafn_lo_r(15, 8), stbuf_data(i)(15, 8)),\n Mux(!stbuf_byteen(i)(1) | store_byteen_hi_r(1), io.store_datafn_hi_r(15, 8), stbuf_data(i)(15, 8))).asUInt)\n\n datain3 := (0 until LSU_STBUF_DEPTH).map(i => Mux(sel_lo(i), Mux(!stbuf_byteen(i)(2) | store_byteen_lo_r(2), io.store_datafn_lo_r(23, 16), stbuf_data(i)(23, 16)),\n Mux(!stbuf_byteen(i)(2) | store_byteen_hi_r(2), io.store_datafn_hi_r(23, 16), stbuf_data(i)(23, 16))).asUInt)\n\n datain4 := (0 until LSU_STBUF_DEPTH).map(i => Mux(sel_lo(i), Mux(!stbuf_byteen(i)(3) | store_byteen_lo_r(3), io.store_datafn_lo_r(31, 24), stbuf_data(i)(31, 24)),\n Mux(!stbuf_byteen(i)(3) | store_byteen_hi_r(3), io.store_datafn_hi_r(31, 24), stbuf_data(i)(31, 24))).asUInt)\n\n stbuf_datain := (0 until LSU_STBUF_DEPTH).map(i => Cat(datain4(i), datain3(i), datain2(i), datain1(i)))\n\n\n stbuf_vld := (0 until LSU_STBUF_DEPTH).map(i => withClock(io.lsu_free_c2_clk) {\n RegNext(Mux(stbuf_wr_en(i).asBool(), 1.U, stbuf_vld(i)) & !stbuf_reset(i), 0.U)\n }).reverse.reduce(Cat(_, _))\n stbuf_dma_kill := (0 until LSU_STBUF_DEPTH).map(i => withClock(io.lsu_free_c2_clk) {\n RegNext(Mux(stbuf_dma_kill_en(i).asBool, 1.U, stbuf_dma_kill(i)) & !stbuf_reset(i), 0.U)\n }).reverse.reduce(Cat(_, _))\n stbuf_byteen := (0 until LSU_STBUF_DEPTH).map(i => withClock(io.lsu_stbuf_c1_clk) {\n RegNext(Mux(stbuf_wr_en(i).asBool(), stbuf_byteenin(i), stbuf_byteen(i)) & Fill(stbuf_byteenin(i).getWidth, !stbuf_reset(i)), 0.U)\n })\n for (i <- 0 until LSU_STBUF_DEPTH) {\n stbuf_addr(i) := rvdffe(stbuf_addrin(i), stbuf_wr_en(i).asBool(), clock, io.scan_mode)\n stbuf_data(i) := rvdffe(stbuf_datain(i), stbuf_wr_en(i).asBool(), clock, io.scan_mode)\n }\n } else {\n stbuf_wr_en := 0.U\n stbuf_reset := 0.U\n stbuf_vld := 0.U\n stbuf_dma_kill := 0.U\n stbuf_addr := 0.U\n stbuf_byteen := 0.U\n stbuf_data := 0.U\n }\n\n // Store Buffer drain logic\n io.stbuf_reqvld_flushed_any := stbuf_vld(RdPtr) & stbuf_dma_kill(RdPtr)\n io.stbuf_reqvld_any := stbuf_vld(RdPtr) & !stbuf_dma_kill(RdPtr) & !(stbuf_dma_kill_en.orR)\n io.stbuf_addr_any := stbuf_addr(RdPtr)\n io.stbuf_data_any := stbuf_data(RdPtr)\n\n val WrPtrEn = ((io.ldst_stbuf_reqvld_r & !dual_stbuf_write_r & !(store_coalesce_hi_r | store_coalesce_lo_r)) |\n (io.ldst_stbuf_reqvld_r & dual_stbuf_write_r & !(store_coalesce_hi_r & store_coalesce_lo_r))).asBool\n val NxtWrPtr = Mux((io.ldst_stbuf_reqvld_r & dual_stbuf_write_r & !(store_coalesce_hi_r | store_coalesce_lo_r)).asBool, WrPtrPlus2, WrPtrPlus1)\n val RdPtrEn = io.lsu_stbuf_commit_any | io.stbuf_reqvld_flushed_any\n val NxtRdPtr = RdPtrPlus1\n\n withClock(io.lsu_stbuf_c1_clk){ WrPtr := RegEnable(NxtWrPtr, 0.U, WrPtrEn)}\n", "right_context": "\n val stbuf_numvld_any = VecInit.tabulate(LSU_STBUF_DEPTH)(i=>Cat(0.U(3.W), stbuf_vld(i))).reduce (_+_)\n val isdccmst_m = io.lsu_pkt_m.valid & io.lsu_pkt_m.bits.store & io.addr_in_dccm_m & !io.lsu_pkt_m.bits.dma\n val isdccmst_r = io.lsu_pkt_r.valid & io.lsu_pkt_r.bits.store & io.addr_in_dccm_r & !io.lsu_pkt_r.bits.dma\n\n stbuf_specvld_m := Cat(0.U(1.W),isdccmst_m) << (isdccmst_m & io.ldst_dual_m)\n stbuf_specvld_r := Cat(0.U(1.W),isdccmst_r) << (isdccmst_r & io.ldst_dual_r)\n val stbuf_specvld_any = stbuf_numvld_any + Cat(0.U(2.W), stbuf_specvld_m) + Cat(0.U(2.W), stbuf_specvld_r)\n\n io.lsu_stbuf_full_any := Mux((!io.ldst_dual_d & io.dec_lsu_valid_raw_d).asBool,(stbuf_specvld_any >= LSU_STBUF_DEPTH.U),(stbuf_specvld_any >= (LSU_STBUF_DEPTH-1).U))\n io.lsu_stbuf_empty_any := stbuf_numvld_any === 0.U\n\n cmpaddr_hi_m := io.end_addr_m(LSU_SB_BITS-1,log2Ceil(DCCM_BYTE_WIDTH))\n cmpaddr_lo_m := io.lsu_addr_m(LSU_SB_BITS-1,log2Ceil(DCCM_BYTE_WIDTH))\n\n\n val stbuf_match_hi = (0 until LSU_STBUF_DEPTH).map(i=> ((stbuf_addr(i)(LSU_SB_BITS-1,log2Ceil(DCCM_BYTE_WIDTH)) === cmpaddr_hi_m(13,0)) & stbuf_vld(i) & !stbuf_dma_kill(i) & io.addr_in_dccm_m).asUInt).reverse.reduce(Cat(_,_))\n val stbuf_match_lo = (0 until LSU_STBUF_DEPTH).map(i=> ((stbuf_addr(i)(LSU_SB_BITS-1,log2Ceil(DCCM_BYTE_WIDTH)) === cmpaddr_lo_m(13,0)) & stbuf_vld(i) & !stbuf_dma_kill(i) & io.addr_in_dccm_m).asUInt).reverse.reduce(Cat(_,_))\n stbuf_dma_kill_en := (0 until LSU_STBUF_DEPTH).map(i=> ((stbuf_match_hi(i) | stbuf_match_lo(i)) & io.lsu_pkt_m.valid & io.lsu_pkt_m.bits.dma & io.lsu_pkt_m.bits.store).asUInt).reverse.reduce(Cat(_,_))\n\n\n val stbuf_fwdbyteenvec_hi = (0 until LSU_STBUF_DEPTH).map(i=>(0 until DCCM_BYTE_WIDTH).map(j=> stbuf_match_hi(i) & stbuf_byteen(i)(j) & stbuf_vld(i).asUInt()))\n val stbuf_fwdbyteenvec_lo = (0 until LSU_STBUF_DEPTH).map(i=>(0 until DCCM_BYTE_WIDTH).map(j=> stbuf_match_lo(i) & stbuf_byteen(i)(j) & stbuf_vld(i).asUInt()))\n val stbuf_fwdbyteen_hi_pre_m = (0 until LSU_STBUF_DEPTH).map(j=>(0 until DCCM_BYTE_WIDTH).map(i=> stbuf_fwdbyteenvec_hi(i)(j).asUInt()).reduce(_|_))\n val stbuf_fwdbyteen_lo_pre_m = (0 until LSU_STBUF_DEPTH).map(j=>(0 until DCCM_BYTE_WIDTH).map(i=> stbuf_fwdbyteenvec_lo(i)(j).asUInt()).reduce(_|_))\n\n val stbuf_fwddata_hi_pre_m = VecInit.tabulate(LSU_STBUF_DEPTH)(i=> Fill(32,stbuf_match_hi(i)) & stbuf_data(i)).reverse.reduce(_|_)\n val stbuf_fwddata_lo_pre_m = VecInit.tabulate(LSU_STBUF_DEPTH)(i=> Fill(32,stbuf_match_lo(i)) & stbuf_data(i)).reverse.reduce(_|_)\n\n\n ldst_byteen_ext_r := ldst_byteen_r << io.lsu_addr_r(1,0)\n val ldst_byteen_hi_r = ldst_byteen_ext_r(7,4)\n val ldst_byteen_lo_r = ldst_byteen_ext_r(3,0)\n\n val ld_addr_rhit_lo_lo = (io.lsu_addr_m(31,2) === io.lsu_addr_r(31,2)) & io.lsu_pkt_r.valid & io.lsu_pkt_r.bits.store & !io.lsu_pkt_r.bits.dma\n val ld_addr_rhit_lo_hi = (io.end_addr_m(31,2) === io.lsu_addr_r(31,2)) & io.lsu_pkt_r.valid & io.lsu_pkt_r.bits.store & !io.lsu_pkt_r.bits.dma\n val ld_addr_rhit_hi_lo = (io.lsu_addr_m(31,2) === io.end_addr_r(31,2)) & io.lsu_pkt_r.valid & io.lsu_pkt_r.bits.store & !io.lsu_pkt_r.bits.dma & dual_stbuf_write_r\n val ld_addr_rhit_hi_hi = (io.end_addr_m(31,2) === io.end_addr_r(31,2)) & io.lsu_pkt_r.valid & io.lsu_pkt_r.bits.store & !io.lsu_pkt_r.bits.dma & dual_stbuf_write_r\n\n ld_byte_rhit_lo_lo := (0 until DCCM_BYTE_WIDTH).map(i=> (ld_addr_rhit_lo_lo & ldst_byteen_lo_r(i)).asUInt).reverse.reduce(Cat(_,_))\n ld_byte_rhit_lo_hi := (0 until DCCM_BYTE_WIDTH).map(i=> (ld_addr_rhit_lo_hi & ldst_byteen_lo_r(i)).asUInt).reverse.reduce(Cat(_,_))\n ld_byte_rhit_hi_lo := (0 until DCCM_BYTE_WIDTH).map(i=> (ld_addr_rhit_hi_lo & ldst_byteen_hi_r(i)).asUInt).reverse.reduce(Cat(_,_))\n ld_byte_rhit_hi_hi := (0 until DCCM_BYTE_WIDTH).map(i=> (ld_addr_rhit_hi_hi & ldst_byteen_hi_r(i)).asUInt).reverse.reduce(Cat(_,_))\n\n ld_byte_rhit_lo := (0 until DCCM_BYTE_WIDTH).map(i=> (ld_byte_rhit_lo_lo(i) | ld_byte_rhit_hi_lo(i)).asUInt).reverse.reduce(Cat(_,_))\n ld_byte_rhit_hi := (0 until DCCM_BYTE_WIDTH).map(i=> (ld_byte_rhit_lo_hi(i) | ld_byte_rhit_hi_hi(i)).asUInt).reverse.reduce(Cat(_,_))\n\n val fwdpipe1_lo = (Fill(8, ld_byte_rhit_lo_lo(0)) & io.store_data_lo_r(7,0)) | (Fill(8, ld_byte_rhit_hi_lo(0)) & io.store_data_hi_r(7,0))\n val fwdpipe2_lo = (Fill(8, ld_byte_rhit_lo_lo(1)) & io.store_data_lo_r(15,8)) | (Fill(8, ld_byte_rhit_hi_lo(1)) & io.store_data_hi_r(15,8))\n val fwdpipe3_lo = (Fill(8, ld_byte_rhit_lo_lo(2)) & io.store_data_lo_r(23,16)) | (Fill(8, ld_byte_rhit_hi_lo(2)) & io.store_data_hi_r(23,16))\n val fwdpipe4_lo = (Fill(8, ld_byte_rhit_lo_lo(3)) & io.store_data_lo_r(31,24)) | (Fill(8, ld_byte_rhit_hi_lo(3)) & io.store_data_hi_r(31,24))\n ld_fwddata_rpipe_lo := Cat(fwdpipe4_lo,fwdpipe3_lo,fwdpipe2_lo,fwdpipe1_lo)\n\n val fwdpipe1_hi = (Fill(8, ld_byte_rhit_lo_hi(0)) & io.store_data_lo_r(7,0)) | (Fill(8, ld_byte_rhit_hi_hi(0)) & io.store_data_hi_r(7,0))\n val fwdpipe2_hi = (Fill(8, ld_byte_rhit_lo_hi(1)) & io.store_data_lo_r(15,8)) | (Fill(8, ld_byte_rhit_hi_hi(1)) & io.store_data_hi_r(15,8))\n val fwdpipe3_hi = (Fill(8, ld_byte_rhit_lo_hi(2)) & io.store_data_lo_r(23,16)) | (Fill(8, ld_byte_rhit_hi_hi(2)) & io.store_data_hi_r(23,16))\n val fwdpipe4_hi = (Fill(8, ld_byte_rhit_lo_hi(3)) & io.store_data_lo_r(31,24)) | (Fill(8, ld_byte_rhit_hi_hi(3)) & io.store_data_hi_r(31,24))\n ld_fwddata_rpipe_hi := Cat(fwdpipe4_hi,fwdpipe3_hi,fwdpipe2_hi,fwdpipe1_hi)\n\n ld_byte_hit_lo := (0 until DCCM_BYTE_WIDTH).map(i=> (ld_byte_rhit_lo_lo(i) | ld_byte_rhit_hi_lo(i)).asUInt).reverse.reduce(Cat(_,_))\n ld_byte_hit_hi := (0 until DCCM_BYTE_WIDTH).map(i=> (ld_byte_rhit_lo_hi(i) | ld_byte_rhit_hi_hi(i)).asUInt).reverse.reduce(Cat(_,_))\n\n io.stbuf_fwdbyteen_hi_m := (0 until DCCM_BYTE_WIDTH).map(i=> (ld_byte_hit_hi(i) | stbuf_fwdbyteen_hi_pre_m(i)).asUInt).reverse.reduce(Cat(_,_))\n io.stbuf_fwdbyteen_lo_m := (0 until DCCM_BYTE_WIDTH).map(i=> (ld_byte_hit_lo(i) | stbuf_fwdbyteen_lo_pre_m(i)).asUInt).reverse.reduce(Cat(_,_))\n\n // Pipe vs Store Queue priority\n val stbuf_fwdpipe1_lo = Mux(ld_byte_rhit_lo(0),ld_fwddata_rpipe_lo(7,0),stbuf_fwddata_lo_pre_m(7,0))\n val stbuf_fwdpipe2_lo = Mux(ld_byte_rhit_lo(1),ld_fwddata_rpipe_lo(15,8),stbuf_fwddata_lo_pre_m(15,8))\n val stbuf_fwdpipe3_lo = Mux(ld_byte_rhit_lo(2),ld_fwddata_rpipe_lo(23,16),stbuf_fwddata_lo_pre_m(23,16))\n val stbuf_fwdpipe4_lo = Mux(ld_byte_rhit_lo(3),ld_fwddata_rpipe_lo(31,24),stbuf_fwddata_lo_pre_m(31,24))\n io.stbuf_fwddata_lo_m := Cat(stbuf_fwdpipe4_lo,stbuf_fwdpipe3_lo,stbuf_fwdpipe2_lo,stbuf_fwdpipe1_lo)\n // Pipe vs Store Queue priority\n val stbuf_fwdpipe1_hi = Mux(ld_byte_rhit_hi(0),ld_fwddata_rpipe_hi(7,0),stbuf_fwddata_hi_pre_m(7,0))\n val stbuf_fwdpipe2_hi = Mux(ld_byte_rhit_hi(1),ld_fwddata_rpipe_hi(15,8),stbuf_fwddata_hi_pre_m(15,8))\n val stbuf_fwdpipe3_hi = Mux(ld_byte_rhit_hi(2),ld_fwddata_rpipe_hi(23,16),stbuf_fwddata_hi_pre_m(23,16))\n val stbuf_fwdpipe4_hi = Mux(ld_byte_rhit_hi(3),ld_fwddata_rpipe_hi(31,24),stbuf_fwddata_hi_pre_m(31,24))\n io.stbuf_fwddata_hi_m := Cat(stbuf_fwdpipe4_hi,stbuf_fwdpipe3_hi,stbuf_fwdpipe2_hi,stbuf_fwdpipe1_hi)\n}\nobject stbuf extends App {\n println((new chisel3.stage.ChiselStage).emitVerilog(new lsu_stbuf()))\n}", "groundtruth": " withClock(io.lsu_stbuf_c1_clk){ RdPtr := RegEnable(NxtRdPtr, 0.U, RdPtrEn)}\n", "crossfile_context": ""}
{"task_id": "NagiCore", "path": "NagiCore/src/main/scala/nagicore/Main.scala", "left_context": "package nagicore\n\nimport chisel3._\nimport chisel3.util._ \nimport _root_.circt.stage._\n\nobject Main extends App {\n val target = args(0)\n val build_dir = \"./build\"\n println(target)\n def exportVerilog(core: () => chisel3.RawModule): Unit = {\n println(\"Export Verilog Started\")\n val chiselStageOption = Seq(\n chisel3.stage.ChiselGeneratorAnnotation(() => core()),\n CIRCTTargetAnnotation(CIRCTTarget.Verilog)\n )\n val firtoolOptions = Seq(\n // FirtoolOption(\"--lowering-options=disallowLocalVariables,locationInfoStyle=wrapInAtSquareBracket,noAlwaysComb\"),\n FirtoolOption(\"--lowering-options=disallowLocalVariables,locationInfoStyle=wrapInAtSquareBracket,noAlwaysComb\"),\n// FirtoolOption(\"--lowering-options=disallowLocalVariables,disallowPackedArrays,locationInfoStyle=wrapInAtSquareBracket,noAlwaysComb\"),\n\n FirtoolOption(\"--split-verilog\"),\n FirtoolOption(\"-o=\" + build_dir),\n FirtoolOption(\"--disable-all-randomization\"),\n FirtoolOption(\"--preserve-aggregate=none\"),\n )\n val executeOptions = chiselStageOption ++ firtoolOptions\n val executeArgs = Array(\"-td\", build_dir)\n (new ChiselStage).execute(executeArgs, executeOptions)\n }\n target match {\n case \"NSCSCC\" => {\n GlobalConfg.SIM = false\n exportVerilog(() => new nagicore.loongarch.nscscc2024.CoreNSCSCC)\n }\n // case \"TEST\" => {\n // exportVerilog(() => new Module{\n // val io = IO(new Bundle {\n // val clk = Input(Clock())\n // })\n // val a = \"h123\".U\n // val xbar = Module(new nagicore.unit.ip.axi_corssbar.AXI4XBar(32, 32, List((0, nagicore.unit.ip.axi_corssbar.Axi4RW.RW)), List((\"0x80000000\", \"0x807FFFFF\"))))\n // xbar.io.masters <> DontCare\n // xbar.io.slaves <> DontCare\n // xbar.io.slaves(0).ar.addr := 2.U(32.W)\n // })\n // }\n", "right_context": "\nobject GlobalConfg{\n var SIM = true\n}", "groundtruth": " case _ => {\n exportVerilog(() => new nagicore.loongarch.nscscc2024.Core)\n }\n", "crossfile_context": ""}
{"task_id": "NagiCore", "path": "NagiCore/src/main/scala/nagicore/loongarch/nscscc2024/Config.scala", "left_context": "package nagicore.loongarch.nscscc2024\n\nimport chisel3._\nimport chisel3.util._\n\ntrait Config{\n def XLEN = 32\n def GPR_NUM = 32\n def GPR_LEN = log2Up(GPR_NUM)\n\n def PC_START = \"h80000000\".U(XLEN.W)\n\n def ICACHE_WAYS = 2\n", "right_context": " def ICACHE_WORDS = 4\n\n def WBUFF_LEN = 4\n\n def BTB_ENTRYS = 8\n\n def AXI4IDBITS = 4\n}", "groundtruth": " def ICACHE_LINES = 128\n", "crossfile_context": ""}
{"task_id": "NagiCore", "path": "NagiCore/src/main/scala/nagicore/loongarch/nscscc2024/stages/IF.scala", "left_context": "package nagicore.loongarch.nscscc2024.stages\n\nimport chisel3._\nimport chisel3.util._\nimport nagicore.bus.AXI4IO\n//import nagicore.unit.{InstrsBuff, InstrsBuffCacheBundle}\nimport nagicore.unit.cache.Cache\nimport nagicore.GlobalConfg\nimport nagicore.unit.cache.CacheReplaceType\nimport nagicore.unit.BTBPredOutIO\nimport nagicore.loongarch.nscscc2024.{Config, CtrlFlags}\nimport nagicore.bus.RamType\n\n\nclass if2idBits extends Bundle with Config{\n val pc = UInt(XLEN.W)\n val bpu_out = new BTBPredOutIO(BTB_ENTRYS, XLEN)\n val instr = UInt(XLEN.W)\n \n val valid = Bool()\n}\n\nclass if2idIO extends Bundle{\n val bits = Output(new if2idBits)\n val stall = Input(Bool())\n}\n\nclass IF extends Module with Config{\n val io = IO(new Bundle {\n val preif2if = Flipped(new preif2ifIO)\n val if2id = new if2idIO\n val isram = new AXI4IO(XLEN, XLEN)\n })\n // 2-stages 1cyc cache\n val icache = Module(new Cache(XLEN, XLEN, ICACHE_WAYS, ICACHE_LINES, ICACHE_WORDS, () => new preif2ifBits(), CacheReplaceType.LRU, \n dataRamType = RamType.RAM_1CYC,\n tagVRamType = RamType.RAM_1CYC,\n debug_id = 0))\n icache.io.axi <> io.isram\n\n icache.io.master.front.bits.addr := io.preif2if.bits.pc\n icache.io.master.front.bits.size := 2.U\n icache.io.master.front.bits.uncache := false.B\n icache.io.master.front.bits.wmask := 0.U\n icache.io.master.front.bits.valid := io.preif2if.bits.valid\n icache.io.master.front.bits.wdata := DontCare\n icache.io.master.front.bits.pipedata := io.preif2if.bits\n icache.io.master.back.stall := io.if2id.stall\n\n\n io.if2id.bits.instr := icache.io.master.back.bits.rdata\n io.if2id.bits.valid := icache.io.master.back.bits.valid\n io.if2id.bits.pc := icache.io.master.back.bits.pipedata.pc\n io.if2id.bits.bpu_out := icache.io.master.back.bits.pipedata.bpu_out\n\n io.preif2if.stall := icache.io.master.front.stall\n\n", "right_context": "}", "groundtruth": " if(GlobalConfg.SIM){\n import nagicore.unit.DPIC_PERF_PIPE\n val perf_pipe_if = Module(new DPIC_PERF_PIPE())\n perf_pipe_if.io.clk := clock\n perf_pipe_if.io.rst := reset\n", "crossfile_context": ""}
{"task_id": "NagiCore", "path": "NagiCore/src/main/scala/nagicore/loongarch/nscscc2024/stages/MEM.scala", "left_context": "package nagicore.loongarch.nscscc2024.stages\n\nimport chisel3._\nimport chisel3.util._\nimport nagicore.bus.AXI4IO\nimport nagicore.unit.cache.CacheMini\nimport nagicore.utils.Flags\nimport nagicore.GlobalConfg\nimport nagicore.unit.cache.CacheReplaceType\nimport nagicore.loongarch.nscscc2024.{Config, CtrlFlags}\nimport nagicore.unit.cache.UnCache\n\nclass mem2idIO extends Bundle with Config{\n // effective signal\n val bypass_rc = Output(UInt(GPR_LEN.W))\n val bypass_val = Output(UInt(XLEN.W))\n val bypass_en = Output(Bool())\n\n val gpr_wid = Output(UInt(GPR_LEN.W))\n val gpr_wdata = Output(UInt(XLEN.W))\n val gpr_wen = Output(Bool())\n}\n\nclass MEM extends Module with Config{\n val io = IO(new Bundle {\n val ex2mem = Flipped(new ex2memIO())\n val mem2id = new mem2idIO()\n val dmem = new AXI4IO(XLEN, XLEN)\n val stall_all = Input(Bool())\n })\n\n class dcachePipeT extends Bundle {\n val instr = UInt(XLEN.W)\n val alu_out = UInt(XLEN.W)\n val rc = UInt(GPR_LEN.W)\n val ld_type = CtrlFlags.ldType()\n val pc = UInt(XLEN.W)\n val no_ldst = Bool()\n\n val valid = Bool()\n }\n \n // val dcache = Module(new CacheMini(XLEN, XLEN, 8, 8, 1))\n val dcache = Module(new UnCache(XLEN, XLEN, WBUFF_LEN, 1))\n\n // pipeline registers\n val preg = RegEnable(io.ex2mem.bits, !dcache.io.out.busy && !io.stall_all)\n io.ex2mem.stall := dcache.io.out.busy || io.stall_all\n\n dcache.io.axi <> io.dmem\n\n val addr = preg.alu_out\n\n dcache.io.in.bits.addr := addr\n // dcache.io.in.bits.uncache := addr(31, 28) === \"hb\".U\n dcache.io.in.bits.we := !Flags.OHis(preg.st_type, CtrlFlags.stType.x)\n dcache.io.in.bits.wdata := Flags.onehotMux(preg.st_type, Seq(\n CtrlFlags.stType.x -> 0.U,\n CtrlFlags.stType.b -> Fill(XLEN/8, preg.rb_val(7, 0)),\n CtrlFlags.stType.h -> Fill(XLEN/16, preg.rb_val(15, 0)),\n CtrlFlags.stType.w -> preg.rb_val(31, 0),\n ))\n dcache.io.in.bits.size := Flags.onehotMux(preg.st_type, Seq(\n CtrlFlags.stType.x -> 0.U,\n CtrlFlags.stType.b -> 0.U,\n CtrlFlags.stType.h -> 1.U,\n CtrlFlags.stType.w -> 2.U,\n )) | Flags.onehotMux(preg.ld_type, Seq(\n CtrlFlags.ldType.x -> 0.U,\n CtrlFlags.ldType.b -> 0.U,\n CtrlFlags.ldType.bu -> 0.U,\n CtrlFlags.ldType.h -> 1.U,\n CtrlFlags.ldType.hu -> 1.U,\n CtrlFlags.ldType.w -> 2.U,\n ))\n dcache.io.in.bits.wmask := Flags.onehotMux(preg.st_type, Seq(\n CtrlFlags.stType.x -> 0.U,\n CtrlFlags.stType.b -> (\"b1\".U< (\"b11\".U<<(addr(1)##0.U(1.W))),\n CtrlFlags.stType.w -> \"b1111\".U,\n ))\n // 不走Cache的指令\n val nolr = Flags.OHis(preg.ld_type, CtrlFlags.ldType.x) && Flags.OHis(preg.st_type, CtrlFlags.stType.x)\n dcache.io.in.req := preg.valid && !nolr && RegNext(!dcache.io.out.busy) && !io.stall_all\n\n val rdata_raw = dcache.io.out.rdata\n", "right_context": " val byteData = Mux(addr(0), halfData(15, 8), halfData(7, 0))\n\n val rdata_mem = Flags.onehotMux(preg.ld_type, Seq(\n CtrlFlags.ldType.x -> (0.U).zext,\n CtrlFlags.ldType.b -> byteData.asSInt,\n CtrlFlags.ldType.bu -> byteData.zext,\n CtrlFlags.ldType.h -> halfData.asSInt,\n CtrlFlags.ldType.hu -> halfData.zext,\n CtrlFlags.ldType.w -> wordData.zext,\n )).asUInt\n\n val mem_valid = preg.valid && !dcache.io.out.busy\n\n io.mem2id.bypass_rc := preg.rc\n io.mem2id.bypass_en := mem_valid\n val wb_data = Mux(Flags.OHis(preg.ld_type, CtrlFlags.ldType.x), preg.alu_out, rdata_mem)\n io.mem2id.bypass_val := wb_data\n\n // when(nolr){\n // io.mem2id.bypass_rc := Mux(preg.valid, preg.rc, 0.U)\n // io.mem2id.bypass_val := preg.alu_out\n // }.otherwise{\n // io.mem2id.bypass_rc := Mux(preg.valid && preg.ld_type === Flags.bp(CtrlFlags.ldType.w), preg.rc, 0.U)\n // io.mem2id.bypass_val := dcache.io.out.rdata\n // }\n\n io.mem2id.gpr_wid := preg.rc\n io.mem2id.gpr_wdata := wb_data\n io.mem2id.gpr_wen := mem_valid\n \n if(GlobalConfg.SIM){\n import nagicore.unit.DPIC_TRACE_MEM\n val dpic_trace_mem_w = Module(new DPIC_TRACE_MEM(XLEN, XLEN))\n dpic_trace_mem_w.io.clk := clock\n dpic_trace_mem_w.io.rst := reset\n dpic_trace_mem_w.io.valid := dcache.io.in.req && dcache.io.in.bits.wmask.orR\n dpic_trace_mem_w.io.addr := dcache.io.in.bits.addr\n dpic_trace_mem_w.io.size := dcache.io.in.bits.size\n dpic_trace_mem_w.io.data := dcache.io.in.bits.wdata\n dpic_trace_mem_w.io.wmask := dcache.io.in.bits.wmask\n\n import nagicore.unit.DPIC_PERF_PIPE\n val perf_pipe_dcache = Module(new DPIC_PERF_PIPE())\n perf_pipe_dcache.io.clk := clock\n perf_pipe_dcache.io.rst := reset\n perf_pipe_dcache.io.id := 2.U\n perf_pipe_dcache.io.invalid := !mem_valid\n perf_pipe_dcache.io.stall := io.ex2mem.stall\n\n import nagicore.unit.DPIC_UPDATE_PC\n val dpic_update_pc = Module(new DPIC_UPDATE_PC(XLEN))\n dpic_update_pc.io.clk := clock\n dpic_update_pc.io.rst := reset\n dpic_update_pc.io.pc := preg.pc\n dpic_update_pc.io.wen := mem_valid\n\n import nagicore.unit.DPIC_TRACE_MEM\n val dpic_trace_mem_r = Module(new DPIC_TRACE_MEM(XLEN, XLEN))\n dpic_trace_mem_r.io.clk := clock\n dpic_trace_mem_r.io.rst := reset\n dpic_trace_mem_r.io.valid := mem_valid && preg.ld_type =/= Flags.bp(CtrlFlags.ldType.x)\n dpic_trace_mem_r.io.addr := preg.alu_out\n dpic_trace_mem_r.io.size := Flags.onehotMux(preg.ld_type, Seq(\n CtrlFlags.ldType.x -> 0.U,\n CtrlFlags.ldType.b -> 0.U,\n CtrlFlags.ldType.bu -> 0.U,\n CtrlFlags.ldType.h -> 1.U,\n CtrlFlags.ldType.hu -> 1.U,\n CtrlFlags.ldType.w -> 2.U,\n ))\n dpic_trace_mem_r.io.data := rdata_mem\n dpic_trace_mem_r.io.wmask := 0.U\n\n\n }\n}", "groundtruth": " val wordData = if(XLEN == 64) Mux(addr(2), rdata_raw(63, 32), rdata_raw(31, 0))\n else rdata_raw(31, 0)\n", "crossfile_context": ""}
{"task_id": "NagiCore", "path": "NagiCore/src/main/scala/nagicore/loongarch/nscscc2024Dual/Config.scala", "left_context": "package nagicore.loongarch.nscscc2024Dual\n\nimport chisel3._\nimport chisel3.util._\n\ntrait Config{\n def XLEN = 32\n def GPR_NUM = 32\n def GPR_LEN = log2Up(GPR_NUM)\n\n def PC_START = \"h80000000\".U(XLEN.W)\n\n def ICACHE_WAYS = 2\n", "right_context": " def ICACHE_WORDS = 4\n\n def WBUFF_LEN = 8\n\n def BTB_ENTRYS = 8\n\n def AXI4IDBITS = 4\n}", "groundtruth": " def ICACHE_LINES = 128\n", "crossfile_context": ""}
{"task_id": "NagiCore", "path": "NagiCore/src/main/scala/nagicore/loongarch/nscscc2024Dual/stages/IS.scala", "left_context": "package nagicore.loongarch.nscscc2024Dual.stages\n\nimport chisel3._\nimport chisel3.util._\nimport nagicore.unit.GPR\nimport nagicore.unit.ALU_OP\nimport nagicore.unit.BR_TYPE\nimport nagicore.unit.BTBPredOutIO\nimport nagicore.loongarch.nscscc2024Dual.{Config, CtrlFlags, Decoder}\nimport nagicore.GlobalConfg\nimport nagicore.unit.RingBuff\nimport nagicore.utils.Flags\n\n\nclass is2exBits extends Bundle with Config{\n val instr1 = UInt(XLEN.W)\n val pc1 = UInt(XLEN.W)\n val ra1_val = UInt(XLEN.W)\n val alu1A_sel = CtrlFlags.aluASel()\n val rb1_val = UInt(XLEN.W)\n val alu1B_sel = CtrlFlags.aluBSel()\n val alu1_op = ALU_OP()\n val rc1 = UInt(GPR_LEN.W)\n val imm1 = UInt(XLEN.W)\n val pc_refill1 = Bool()\n\n val br_type = BR_TYPE()\n val brpcAdd_sel = CtrlFlags.brpcAddSel()\n val ld_type = CtrlFlags.ldType()\n val st_type = CtrlFlags.stType()\n val bpu_out = new BTBPredOutIO(BTB_ENTRYS, XLEN)\n\n val valid1 = Bool()\n\n val instr2 = UInt(XLEN.W)\n val pc2 = UInt(XLEN.W)\n val ra2_val = UInt(XLEN.W)\n val alu2A_sel = CtrlFlags.aluASel()\n val rb2_val = UInt(XLEN.W)\n val alu2B_sel = CtrlFlags.aluBSel()\n val alu2_op = ALU_OP()\n val rc2 = UInt(GPR_LEN.W)\n val imm2 = UInt(XLEN.W)\n val pc_refill2 = Bool()\n\n val valid2 = Bool()\n}\n\nclass is2exIO extends Bundle{\n val bits = Output(new is2exBits)\n val stall = Input(Bool())\n}\n\nclass IS extends Module with Config{\n val io = IO(new Bundle{\n val id2is = Flipped(new id2isIO)\n val is2ex = new is2exIO\n\n val ex2is = Flipped(new ex2isIO)\n val mem2is = Flipped(new mem2isIO)\n })\n\n val issue_buffer = Module(new RingBuff(()=>new id2isBits, 8, rchannel=2, debug_id=0))\n\n issue_buffer.io.push := io.id2is.bits.valid\n issue_buffer.io.wdata := io.id2is.bits\n issue_buffer.io.clear := io.ex2is.clear_is\n\n val is1 = issue_buffer.io.rdatas(0)\n", "right_context": " issue_buffer.io.popN := issue_double\n\n// io.id2is.stall := io.is2ex.stall\n io.id2is.stall := issue_buffer.io.full\n\n val gpr = Module(new GPR(XLEN, GPR_NUM, 4, 2))\n gpr.io.wen(0) := io.mem2is.gpr_wen1 && (!io.mem2is.gpr_wen2 || io.mem2is.gpr_wid2 =/= io.mem2is.gpr_wid1)\n gpr.io.waddr(0) := io.mem2is.gpr_wid1\n gpr.io.wdata(0) := io.mem2is.gpr_wdata1\n\n gpr.io.wen(1) := io.mem2is.gpr_wen2\n gpr.io.waddr(1) := io.mem2is.gpr_wid2\n gpr.io.wdata(1) := io.mem2is.gpr_wdata2\n\n if(GlobalConfg.SIM){\n import nagicore.unit.DPIC_UPDATE_GPR2\n val dpic_update_gpr = Module(new DPIC_UPDATE_GPR2(XLEN, GPR_NUM))\n dpic_update_gpr.io.clk := clock\n dpic_update_gpr.io.rst := reset\n\n dpic_update_gpr.io.id1 := gpr.io.waddr(0)\n dpic_update_gpr.io.wen1 := gpr.io.wen(0)\n dpic_update_gpr.io.wdata1 := gpr.io.wdata(0)\n\n dpic_update_gpr.io.id2 := gpr.io.waddr(1)\n dpic_update_gpr.io.wen2 := gpr.io.wen(1)\n dpic_update_gpr.io.wdata2 := gpr.io.wdata(1)\n }\n\n def bypass_unit(rx: UInt, gpr_rdata: UInt):UInt = {\n Mux(rx === 0.U, 0.U,\n Mux(io.ex2is.bypass_rc2 === rx && io.ex2is.bypass_en2, io.ex2is.bypass_val2,\n Mux(io.ex2is.bypass_rc1 === rx && io.ex2is.bypass_en1, io.ex2is.bypass_val1,\n Mux(io.mem2is.bypass_rc2 === rx && io.mem2is.bypass_en2, io.mem2is.bypass_val2,\n Mux(io.mem2is.bypass_rc1 === rx && io.mem2is.bypass_en1, io.mem2is.bypass_val1,\n gpr_rdata\n )\n )\n )\n )\n )\n }\n\n gpr.io.raddr(0) := is1.ra\n io.is2ex.bits.ra1_val := bypass_unit(is1.ra, gpr.io.rdata(0))\n io.is2ex.bits.alu1A_sel := is1.aluA_sel\n gpr.io.raddr(1) := is1.rb\n io.is2ex.bits.rb1_val := bypass_unit(is1.rb, gpr.io.rdata(1))\n io.is2ex.bits.alu1B_sel := is1.aluB_sel\n\n gpr.io.raddr(2) := is2.ra\n io.is2ex.bits.ra2_val := bypass_unit(is2.ra, gpr.io.rdata(2))\n io.is2ex.bits.alu2A_sel := is2.aluA_sel\n gpr.io.raddr(3) := is2.rb\n io.is2ex.bits.rb2_val := bypass_unit(is2.rb, gpr.io.rdata(3))\n io.is2ex.bits.alu2B_sel := is2.aluB_sel\n\n io.is2ex.bits.instr1 := is1.instr\n io.is2ex.bits.instr2 := is2.instr\n\n io.is2ex.bits.pc1 := is1.pc\n io.is2ex.bits.pc2 := is2.pc\n\n io.is2ex.bits.alu1_op := is1.alu_op\n io.is2ex.bits.alu2_op := is2.alu_op\n\n io.is2ex.bits.rc1 := is1.rc\n io.is2ex.bits.rc2 := is2.rc\n\n io.is2ex.bits.imm1 := is1.imm\n io.is2ex.bits.imm2 := is2.imm\n\n io.is2ex.bits.br_type := is1.br_type\n io.is2ex.bits.brpcAdd_sel := is1.brpcAdd_sel\n io.is2ex.bits.ld_type := is1.ld_type\n io.is2ex.bits.st_type := is1.st_type\n io.is2ex.bits.bpu_out := is1.bpu_out\n\n io.is2ex.bits.pc_refill1 := is1.pc_refill\n io.is2ex.bits.pc_refill2 := is2.pc_refill\n\n io.is2ex.bits.valid1 := issue_buffer.io.rvalids(0)\n io.is2ex.bits.valid2 := issue_buffer.io.rvalids(1) && issue_double\n}", "groundtruth": " val is2 = issue_buffer.io.rdatas(1)\n val data_hazard = (is1.rc === is2.ra || is1.rc === is2.rb) && is1.rc =/= 0.U\n // 只双发is2是ALU类,且无数据冒险的指令\n val issue_double =\n Flags.is(is2.instr_type, CtrlFlags.InstrType.alu) &&\n", "crossfile_context": ""}
{"task_id": "NagiCore", "path": "NagiCore/src/main/scala/nagicore/unit/DIVU.scala", "left_context": "package nagicore.unit\n\nimport chisel3._\nimport chisel3.util._\nimport nagicore.utils.Flags\n\nobject DIVU_IMP extends Enumeration {\n type DIVU_IMP = Value\n val none, radix2 = Value\n}\n\nclass DIVU(dataBits: Int, imp_way: DIVU_IMP.DIVU_IMP = DIVU_IMP.radix2) extends Module{\n val io = IO(new Bundle{\n val a = Input(UInt(dataBits.W))\n val b = Input(UInt(dataBits.W))\n val signed = Input(Bool())\n val quo = Output(UInt(dataBits.W))\n val rem = Output(UInt(dataBits.W))\n val valid = Input(Bool())\n val busy = Output(Bool())\n })\n\n imp_way match {\n", "right_context": " val sign_r = Mux(io.signed, io.a(dataBits-1), false.B)\n val src1 = Mux(io.signed && io.a(dataBits-1), ~io.a + 1.U, io.a)\n val src2 = Mux(io.signed && io.b(dataBits-1), ~io.b + 1.U, io.b)\n\n // get highest 1 in src1\n // TODO use log2\n val high_rev = PriorityEncoder(Reverse(src1))\n\n val cnt = RegInit(0.U(6.W))\n val stage1_fire = cnt === 0.U\n\n val src1_reg1 = RegEnable(src1, stage1_fire)\n val src2_reg1 = RegEnable(src2, stage1_fire)\n val signed_reg1 = RegEnable(io.signed, stage1_fire)\n val sign_s_reg1 = RegEnable(sign_s, stage1_fire)\n val sign_r_reg1 = RegEnable(sign_r, stage1_fire)\n val en_reg1 = RegEnable(io.valid, stage1_fire)\n val high_rev_reg1 = RegEnable(high_rev, stage1_fire)\n\n /* stage2+: div */\n val stage2_init = en_reg1 && cnt === 0.U\n\n val src2_reg2 = RegEnable(src2_reg1, stage2_init)\n val signed_reg2 = RegEnable(signed_reg1, stage2_init)\n val sign_s_reg2 = RegEnable(sign_s_reg1, stage2_init)\n val sign_r_reg2 = RegEnable(sign_r_reg1, stage2_init)\n\n when(cnt =/= 0.U){\n cnt := cnt - 1.U\n }.elsewhen(en_reg1){\n cnt := (dataBits+1).U - high_rev_reg1\n }\n\n val quo_rem_reg = RegInit(0.U((dataBits*2+1).W))\n val quo = quo_rem_reg(dataBits-1, 0)\n val rem = quo_rem_reg(dataBits*2-1, dataBits)\n when(cnt =/= 0.U){\n val mins = rem - src2_reg2\n when(rem >= src2_reg2){\n quo_rem_reg := mins(dataBits-1, 0) ## quo ## 1.U(1.W)\n }.otherwise{\n quo_rem_reg := quo_rem_reg(dataBits*2-1, 0) ## 0.U(1.W)\n }\n }.elsewhen(en_reg1){\n quo_rem_reg := (0.U((dataBits+1).W) ## src1_reg1) << high_rev_reg1\n }\n\n io.busy := cnt =/= 0.U || en_reg1\n\n io.quo := Mux(signed_reg2,\n Mux(sign_s_reg2, ~quo + 1.U, quo),\n quo\n )\n\n val rem_res = quo_rem_reg(dataBits*2, dataBits+1)\n io.rem := Mux(signed_reg2,\n Mux(sign_r_reg2, ~rem_res + 1.U, rem_res),\n rem_res\n )\n }\n case DIVU_IMP.none => {\n io.busy := false.B\n io.quo := DontCare\n io.rem := DontCare\n }\n }\n}\n\n/* \nclass DIVU(dataBits: Int) extends Module{\n val io = IO(new Bundle{\n val a = Input(UInt(dataBits.W))\n val b = Input(UInt(dataBits.W))\n val signed = Input(Bool())\n val quo = Output(UInt(dataBits.W))\n val rem = Output(UInt(dataBits.W))\n val valid = Input(Bool())\n val busy = Output(Bool())\n })\n\n /* ref: https://github.com/MaZirui2001/LAdataBitsR-pipeline-scala */\n\n /* stage1: solve sign */\n val sign_s = Mux(io.signed, io.a(dataBits-1) ^ io.b(dataBits-1), false.B)\n val sign_r = Mux(io.signed, io.a(dataBits-1), false.B)\n val src1 = Mux(io.signed && io.a(dataBits-1), ~io.a + 1.U, io.a)\n val src2 = Mux(io.signed && io.b(dataBits-1), ~io.b + 1.U, io.b)\n\n // get highest 1 in src1\n val high_rev = PriorityEncoder(Reverse(src1))\n\n val src1_reg1 = ShiftRegister(src1, 1, !io.busy)\n val src2_reg1 = ShiftRegister(src2, 1, !io.busy)\n val signed_reg1 = ShiftRegister(io.signed, 1, !io.busy)\n val sign_s_reg1 = ShiftRegister(sign_s, 1, !io.busy)\n val sign_r_reg1 = ShiftRegister(sign_r, 1, !io.busy)\n val en_reg1 = ShiftRegister(io.valid, 1, !io.busy)\n val high_rev_reg1 = ShiftRegister(high_rev, 1, !io.busy)\n\n /* stage2+: div */\n val cnt = RegInit(0.U(6.W))\n val stage2_init = en_reg1 && cnt === 0.U\n\n val src2_reg2 = RegEnable(src2_reg1, stage2_init)\n val signed_reg2 = RegEnable(signed_reg1, stage2_init)\n val sign_s_reg2 = RegEnable(sign_s_reg1, stage2_init)\n val sign_r_reg2 = RegEnable(sign_r_reg1, stage2_init)\n\n when(cnt =/= 0.U){\n cnt := cnt - 1.U\n }.elsewhen(en_reg1){\n cnt := (dataBits+1).U - high_rev_reg1\n }\n\n val quo_rem_reg = RegInit(0.U((dataBits*2+1).W))\n val quo = quo_rem_reg(dataBits-1, 0)\n val rem = quo_rem_reg(dataBits*2-1, dataBits)\n when(cnt =/= 0.U){\n val mins = rem - src2_reg2\n when(rem >= src2_reg2){\n quo_rem_reg := mins ## quo ## 1.U(1.W)\n }.otherwise{\n quo_rem_reg := quo_rem_reg(dataBits*2-1, 0) ## 0.U(1.W)\n }\n }.elsewhen(en_reg1){\n quo_rem_reg := (0.U((dataBits+1).W) ## src1_reg1) << high_rev_reg1\n }\n\n !io.busy := cnt === 0.U\n\n io.quo := Mux(signed_reg2,\n Mux(sign_s_reg2, ~quo + 1.U, quo),\n quo\n )\n\n io.rem := Mux(signed_reg2,\n Mux(sign_r_reg2, ~quo_rem_reg(dataBits*2, dataBits+1) + 1.U, quo_rem_reg(dataBits*2, dataBits+1)),\n quo_rem_reg(dataBits*2, dataBits+1)\n )\n}\n */", "groundtruth": " case DIVU_IMP.radix2 => {\n /* ref: https://github.com/MaZirui2001/LAdataBitsR-pipeline-scala */\n\n", "crossfile_context": ""}
{"task_id": "NagiCore", "path": "NagiCore/src/main/scala/nagicore/unit/GPR.scala", "left_context": "package nagicore.unit\n\nimport chisel3._\nimport chisel3.util._\n\nclass GPRIO(dataBits: Int, addrBits: Int, rchannel: Int, wchannel: Int) extends Bundle {\n val raddr = Input(Vec(rchannel, UInt(addrBits.W)))\n val rdata = Output(Vec(rchannel, UInt(dataBits.W)))\n", "right_context": "}\n\nclass GPR(dataBits: Int, regNum: Int, rchannel: Int, wchannel: Int) extends Module {\n val io = IO(new GPRIO(dataBits, log2Up(regNum), rchannel, wchannel))\n val regs = Reg(Vec(regNum, UInt(dataBits.W)))\n // val regs = Reg(VecInit.fill(regNum)(0.U(dataBits.W)))\n // val regs = Mem(regNum, UInt(dataBits.W))\n for(i <- 0 until rchannel){\n io.rdata(i) := Mux(io.raddr(i) =/= 0.U, regs(io.raddr(i)), 0.U)\n }\n for(i <- 0 until wchannel){\n when(io.wen(i) && io.waddr(i) =/= 0.U){\n regs(io.waddr(i)) := io.wdata(i)\n }\n }\n}\n", "groundtruth": " val wen = Input(Vec(wchannel, Bool()))\n val waddr = Input(Vec(wchannel, UInt(addrBits.W)))\n", "crossfile_context": ""}
{"task_id": "NagiCore", "path": "NagiCore/src/main/scala/nagicore/unit/cache/CachePiped.scala", "left_context": "package nagicore.unit.cache\n\nimport chisel3._\nimport chisel3.util._\n\nimport nagicore.bus._\nimport chisel3.util.random.LFSR\nimport nagicore.utils.isPowerOf2\nimport nagicore.GlobalConfg\n\nclass CachePipedIOFrontBits[T <: Bundle](addrBits: Int, dataBits: Int, pipedataT: () => T) extends Bundle{\n val valid = Bool()\n val addr = UInt(addrBits.W)\n val wmask = UInt((dataBits/8).W)\n val size = UInt(2.W)\n val wdata = UInt(dataBits.W)\n val uncache = Bool()\n val pipedata = pipedataT()\n}\n\nclass CachePipedIOFront[T <: Bundle](addrBits: Int, dataBits: Int, pipedataT: () => T) extends Bundle{\n val bits = Input(new CachePipedIOFrontBits[T](addrBits, dataBits, pipedataT))\n val stall = Output(Bool()) \n}\n\nclass CachePipedIOBackBits[T <: Bundle](addrBits: Int, dataBits: Int, blockWords: Int, pipedataT: () => T) extends Bundle{\n val valid = Bool()\n val rdata = UInt(dataBits.W)\n // 整个缓存块,注意uncahce访问时,结果无意义\n val rline = Vec(blockWords, UInt(dataBits.W))\n val pipedata_s1 = pipedataT()\n val pipedata_s2 = pipedataT()\n // for debug\n val addr = UInt(addrBits.W)\n val size = UInt(2.W)\n val wdata = UInt(dataBits.W)\n val wmask = UInt((dataBits/8).W)\n}\n\nclass CachePipedIOBack[T <: Bundle](addrBits: Int, dataBits: Int, blockWords: Int, pipedataT: () => T) extends Bundle{\n val bits = Output(new CachePipedIOBackBits[T](addrBits, dataBits, blockWords, pipedataT))\n val stall = Input(Bool())\n}\n\nclass CachePipedIO[T <: Bundle](addrBits: Int, dataBits: Int, blockWords: Int, pipedataT: () => T) extends Bundle{\n val front = new CachePipedIOFront[T](addrBits, dataBits, pipedataT)\n val back = new CachePipedIOBack[T](addrBits, dataBits, blockWords, pipedataT)\n}\n\n/**\n * 阻塞式两级流水线Cache(已弃用)\n * @pipeline\n * stage1 stage2\n * EX -> MEM1 -> MEM2 -> WB\n * 向SRAM发出地址 读SRAM和TLB 比较Tag,选择数据 字节选择,符号扩展\n * |preg1|------->|preg2|\n * |-------------------|\n * ADDR--->| Cache RAM(2 cyc) |------->|rtag, rdata ...|\n * |-------------------|\n *\n * @param addrBits\n * @param dataBits\n * @param ways 相连数,必须为2的幂次\n * @param sets 行数\n * @param blockWords 块字个数\n * @param pipedataT 流水线其他信号\n */\nclass CachePiped[T <: Bundle](addrBits: Int, dataBits: Int, ways: Int, sets: Int, blockWords: Int, pipedataT: () => T, id: Int=0, replaceT: CacheReplaceType.CacheReplaceType=CacheReplaceType.Random) extends Module{\n require(isPowerOf2(ways))\n require(isPowerOf2(dataBits))\n\n val io = IO(new Bundle{\n val axi = new AXI4IO(addrBits, dataBits)\n val master = new CachePipedIO(addrBits, dataBits, blockWords, pipedataT)\n })\n \n // Block address\n // [ Tag | Index | Word | Byte ]\n // | | | |\n // line set \n val len_byte = log2Ceil(dataBits/8)\n val num_word = blockWords\n val len_word = log2Ceil(num_word)\n val len_idx = log2Ceil(sets)\n val len_tag = addrBits - len_idx - len_word - len_byte\n val beats_len = num_word\n\n val axi_w_agent = Module(new AXI4WriteAgent(addrBits, dataBits, beats_len))\n axi_w_agent.io.axi.aw <> io.axi.aw\n axi_w_agent.io.axi.w <> io.axi.w\n axi_w_agent.io.axi.b <> io.axi.b\n axi_w_agent.io.cmd.in.req := false.B\n axi_w_agent.io.cmd.in.addr := 0.U\n axi_w_agent.io.cmd.in.wdata := VecInit.fill(blockWords)(0.U)\n axi_w_agent.io.cmd.in.wmask := VecInit.fill(blockWords)(0.U)\n axi_w_agent.io.cmd.in.size := 0.U\n axi_w_agent.io.cmd.in.len := 0.U\n\n val axi_r_agent = Module(new AXI4ReadAgent(addrBits, dataBits, beats_len))\n axi_r_agent.io.axi.ar <> io.axi.ar\n axi_r_agent.io.axi.r <> io.axi.r\n axi_r_agent.io.cmd.in.req := false.B\n axi_r_agent.io.cmd.in.addr := 0.U\n axi_r_agent.io.cmd.in.len := 0.U\n axi_r_agent.io.cmd.in.size := 0.U\n\n val random_way = LFSR(16)(log2Up(ways)-1, 0)\n val lru = Reg(Vec(sets, UInt(log2Up(ways).W)))\n\n val active_way = Reg(UInt(log2Up(ways).W))\n\n val data_bank = Seq.fill(ways)(Seq.fill(num_word)(Module(new CacheMem(dataBits, sets))))\n val data_bank_io = VecInit(data_bank.map(t => VecInit(t.map(_.io))))\n val tag_v = Seq.fill(ways)(Module(new CacheMem(len_tag+1, sets)))\n val tag_v_io = VecInit(tag_v.map(_.io))\n val dirty = Seq.fill(ways)(Module(new CacheMem(1, sets)))\n val dirty_io = VecInit(dirty.map(_.io))\n val addr_idx = io.master.front.bits.addr(len_idx+len_word+len_byte-1, len_word+len_byte)\n\n // 流水使能信号\n val pipego = Wire(Bool())\n\n tag_v_io.map(io => {\n io.addr := addr_idx\n io.en := pipego\n io.re := true.B\n io.we := false.B\n io.din := 0.U\n io.wmask := Fill(len_tag+1, true.B)\n })\n data_bank_io.map(_.map(io => {\n io.addr := addr_idx\n io.en := pipego\n io.re := true.B\n io.we := false.B\n io.din := 0.U\n io.wmask := Fill(dataBits, true.B)\n }))\n dirty_io.map(io => {\n io.addr := addr_idx\n io.en := pipego\n io.re := true.B\n io.we := false.B\n io.din := 0.U\n io.wmask := Fill(1, true.B)\n })\n\n\n\n // stage1 pipeline registers\n val preg1 = RegEnable(io.master.front.bits, pipego)\n \n // stage2 pipeline registers\n val preg2 = RegEnable(preg1, pipego)\n object Stage2State extends ChiselEnum {\n // 0 1 2 3 4 5 6\n val lookup, writeback, replace, replaceEnd, uncacheWait, uncacheRead, uncacheEnd = Value\n }\n // stage2 state\n val state_s2 = RegInit(Stage2State.lookup)\n val hit = Wire(Bool())\n\n val pipego_reg = pipego\n\n", "right_context": " tag_v_io(i).dout(0).asBool\n }, pipego_reg)\n val rdirty = RegEnable(VecInit.tabulate(ways){ i =>\n dirty_io(i).dout.asBool\n }, pipego_reg)\n\n pipego :=\n (\n // 连续命中\n (state_s2 === Stage2State.lookup && hit) ||\n // 无效命令\n !preg2.valid ||\n // 替换完成\n state_s2 === Stage2State.replaceEnd ||\n // uncache访问\n state_s2 === Stage2State.uncacheEnd\n ) &&\n // 下一级无阻塞请求\n !io.master.back.stall\n\n val addr_s2 = preg2.addr\n // TODO: VIPT, let TLB pass in real tag\n val addr_tag_s2 = addr_s2(addrBits-1, len_idx+len_word+len_byte)\n val addr_idx_s2 = addr_s2(len_idx+len_word+len_byte-1, len_word+len_byte)\n val addr_word_s2 = addr_s2(len_word+len_byte-1, len_byte)\n\n val rdatas_hit = WireDefault(VecInit.fill(blockWords)(0.U(dataBits.W)))\n val rdatas_replace = RegInit(VecInit.fill(blockWords)(0.U(dataBits.W)))\n val rdata_uncache = RegInit(0.U(dataBits.W))\n\n io.master.front.stall := !pipego\n io.master.back.bits.valid := pipego && preg2.valid\n// io.master.back.bits.rdata := Mux(state_s2 === Stage2State.replaceEnd, rdata_replace, rdata_hit)\n io.master.back.bits.rdata := MuxCase(rdatas_hit(addr_word_s2), Seq(\n (state_s2 === Stage2State.replaceEnd) -> rdatas_replace(addr_word_s2),\n (state_s2 === Stage2State.uncacheEnd) -> rdata_uncache\n ))\n io.master.back.bits.rline := Mux(state_s2 === Stage2State.replaceEnd, rdatas_replace,\n rdatas_hit\n )\n io.master.back.bits.pipedata_s1 := preg1.pipedata\n io.master.back.bits.pipedata_s2 := preg2.pipedata\n\n io.master.back.bits.addr := preg2.addr\n io.master.back.bits.size := preg2.size\n io.master.back.bits.wdata := preg2.wdata\n io.master.back.bits.wmask := preg2.wmask\n\n val bypass_addr = Reg(UInt((len_tag+len_idx).W))\n val bypass_val = Reg(Vec(blockWords, UInt(dataBits.W)))\n val bypass_valid = Reg(Vec(blockWords, Bool()))\n for(i <- 0 until blockWords){\n bypass_valid(i) := 0.U\n }\n\n val hits = VecInit.tabulate(ways){ i =>\n rtags(i) === addr_tag_s2 && rvalid(i)\n }\n hit := hits.reduceTree(_||_) && !preg2.uncache\n\n if(GlobalConfg.SIM){\n import nagicore.unit.DPIC_PERF_CACHE\n val dpic_perf_cache = Module(new DPIC_PERF_CACHE)\n dpic_perf_cache.io.clk := clock\n dpic_perf_cache.io.rst := reset\n dpic_perf_cache.io.valid := preg2.valid && state_s2 === Stage2State.lookup && !io.master.back.stall\n dpic_perf_cache.io.id := id.U\n dpic_perf_cache.io.access_type := Cat(preg2.uncache, hit)\n }\n\n\n // 请求读缺失行,并开始替换Cache行\n def load_miss_lines() = {\n axi_r_agent.io.cmd.in.req := true.B\n axi_r_agent.io.cmd.in.addr := addr_tag_s2 ## addr_idx_s2 ## 0.U((len_word+len_byte).W)\n axi_r_agent.io.cmd.in.len := (blockWords-1).U\n axi_r_agent.io.cmd.in.size := log2Up(dataBits).U\n state_s2 := Stage2State.replace\n }\n\n def writeSyncRam(io: RamIO, addr: UInt, data: UInt) = {\n io.addr := addr\n io.en := true.B\n io.re := false.B\n io.we := true.B\n io.din := data\n }\n\n def wait_uncache_ready() = {\n when(preg2.wmask.orR){\n when(axi_w_agent.io.cmd.out.ready){\n axi_w_agent.io.cmd.in.addr := preg2.addr\n axi_w_agent.io.cmd.in.req := true.B\n axi_w_agent.io.cmd.in.wdata(0) := preg2.wdata\n axi_w_agent.io.cmd.in.wmask(0) := preg2.wmask\n axi_w_agent.io.cmd.in.size := preg2.size\n axi_w_agent.io.cmd.in.len := 0.U\n state_s2 := Stage2State.uncacheEnd\n }\n }.otherwise{\n when(axi_w_agent.io.cmd.out.ready&&axi_r_agent.io.cmd.out.ready){\n axi_r_agent.io.cmd.in.req := true.B\n axi_r_agent.io.cmd.in.addr := preg2.addr\n axi_r_agent.io.cmd.in.size := preg2.size\n axi_r_agent.io.cmd.in.len := 0.U\n state_s2 := Stage2State.uncacheRead\n }\n }\n }\n\n switch(state_s2){\n is(Stage2State.lookup){\n when(preg2.valid){\n when(hit){\n val hit_way = PriorityEncoder(hits)\n if(replaceT == CacheReplaceType.LRU){\n lru(addr_idx_s2) := ~hit_way\n }\n // 当连续hit wr/ww同一Cache行时,需要前递\n val hit_rw_bypass_need = bypass_addr === Cat(addr_tag_s2, addr_idx_s2)\n val rdatas_real = VecInit.tabulate(blockWords){\n i => Mux(hit_rw_bypass_need && bypass_valid(i),\n bypass_val(i),\n rdatas(hit_way)(i)\n )\n }\n when(preg2.wmask.orR){\n // 命中写\n val wdata = Cat((0 until (dataBits/8)).reverse.map(i =>\n Mux(preg2.wmask(i),\n preg2.wdata(i*8+7, i*8),\n rdatas_real(addr_word_s2)(i*8+7, i*8)\n )))\n writeSyncRam(data_bank_io(hit_way)(addr_word_s2), addr_idx_s2, wdata)\n bypass_addr := Cat(addr_tag_s2, addr_idx_s2)\n bypass_valid(addr_word_s2) := true.B\n bypass_val(addr_word_s2) := wdata\n writeSyncRam(dirty_io(hit_way), addr_idx_s2, 1.U(1.W))\n }otherwise{\n // 命中读\n rdatas_hit := rdatas_real\n }\n state_s2 := Stage2State.lookup\n }.otherwise{\n when(preg2.uncache){\n wait_uncache_ready()\n // or just state_s2 := Stage2State.uncacheWait\n }.otherwise{\n val active_way_wire = Wire(chiselTypeOf(active_way))\n if(replaceT == CacheReplaceType.LRU){\n active_way_wire := lru(addr_idx_s2)\n }else{\n active_way_wire := random_way\n }\n active_way := active_way_wire\n when(rdirty(active_way_wire) && rvalid(active_way_wire)) {\n state_s2 := Stage2State.writeback\n }.otherwise {\n load_miss_lines()\n }\n }\n }\n }\n }\n is(Stage2State.writeback){\n // 等待代理空闲\n when(axi_w_agent.io.cmd.out.ready){\n // 交给代理写入将要被替换的脏行\n val addr = rtags(active_way) ## addr_idx_s2 ## 0.U((len_word+len_byte).W)\n axi_w_agent.io.cmd.in.addr := addr\n axi_w_agent.io.cmd.in.req := true.B\n axi_w_agent.io.cmd.in.wdata := rdatas(active_way)\n axi_w_agent.io.cmd.in.wmask := VecInit.fill(blockWords)(1.U)\n axi_w_agent.io.cmd.in.size := log2Up(dataBits).U\n axi_w_agent.io.cmd.in.len := (blockWords-1).U\n\n load_miss_lines()\n }.otherwise{\n state_s2 := Stage2State.writeback\n }\n }\n is(Stage2State.replace){\n when(axi_r_agent.io.cmd.out.ready){\n val word_i = axi_r_agent.io.cmd.out.order\n val wdata_active = Mux(word_i === addr_word_s2,\n Cat((0 until (dataBits/8)).reverse.map(i =>\n Mux(preg2.wmask(i),\n preg2.wdata(i*8+7, i*8),\n axi_r_agent.io.cmd.out.rdata(i*8+7, i*8)\n )\n )),\n axi_r_agent.io.cmd.out.rdata\n )\n\n writeSyncRam(data_bank_io(active_way)(word_i), addr_idx_s2, wdata_active)\n bypass_val(word_i) := wdata_active\n\n rdatas_replace(word_i) := wdata_active\n\n when(axi_r_agent.io.cmd.out.last){\n state_s2 := Stage2State.replaceEnd\n writeSyncRam(tag_v_io(active_way), addr_idx_s2, addr_tag_s2 ## 1.U(1.W))\n writeSyncRam(dirty_io(active_way), addr_idx_s2, 0.U(1.W))\n bypass_addr := Cat(addr_tag_s2, addr_idx_s2)\n }\n }\n }\n // 等待下一级准备好接受\n is(Stage2State.replaceEnd){\n when(!io.master.back.stall){\n state_s2 := Stage2State.lookup\n for(i <- 0 until blockWords){\n bypass_valid(i) := true.B\n }\n }\n }\n is(Stage2State.uncacheWait){\n wait_uncache_ready()\n }\n is(Stage2State.uncacheRead){\n // 等待代理空闲\n when(axi_r_agent.io.cmd.out.ready){\n rdata_uncache := axi_r_agent.io.cmd.out.rdata\n state_s2 := Stage2State.uncacheEnd\n }\n }\n is(Stage2State.uncacheEnd){\n // 等待下一级准备好接受\n when(!io.master.back.stall){\n state_s2 := Stage2State.lookup\n }\n }\n\n }\n}", "groundtruth": " val rdatas = RegEnable(VecInit.tabulate(ways){ i =>\n VecInit.tabulate(num_word){ j =>\n data_bank_io(i)(j).dout\n }\n }, pipego_reg)\n", "crossfile_context": ""}
{"task_id": "NagiCore", "path": "NagiCore/src/main/scala/nagicore/unit/cache/CacheWT.scala", "left_context": "package nagicore.unit.cache\n\nimport chisel3.VecInit._\nimport chisel3._\nimport chisel3.util._\nimport nagicore.bus._\nimport chisel3.util.random.LFSR\nimport nagicore.utils.isPowerOf2\nimport nagicore.GlobalConfg\nimport nagicore.unit.RingBuff\n\nclass CacheWTIOFrontBits[T <: Bundle](addrBits: Int, dataBits: Int, pipedataT: () => T) extends Bundle{\n val valid = Bool()\n val addr = UInt(addrBits.W)\n val we = Bool()\n val wmask = UInt((dataBits/8).W)\n val size = UInt(2.W)\n val wdata = UInt(dataBits.W)\n val uncache = Bool()\n val pipedata = pipedataT()\n}\n\nclass CacheWTIOFront[T <: Bundle](addrBits: Int, dataBits: Int, pipedataT: () => T) extends Bundle{\n val bits = Input(new CacheWTIOFrontBits[T](addrBits, dataBits, pipedataT))\n val stall = Output(Bool())\n}\n\nclass CacheWTIOBackBits[T <: Bundle](addrBits: Int, dataBits: Int, blockWords: Int, pipedataT: () => T) extends Bundle{\n val valid = Bool()\n val rdata = UInt(dataBits.W)\n // 整个缓存块,注意uncahce访问时,结果无意义\n val rline = Vec(blockWords, UInt(dataBits.W))\n val pipedata = pipedataT()\n // for debug\n val addr = UInt(addrBits.W)\n val size = UInt(2.W)\n val wdata = UInt(dataBits.W)\n val wmask = UInt((dataBits/8).W)\n}\n\nclass CacheWTIOBack[T <: Bundle](addrBits: Int, dataBits: Int, blockWords: Int, pipedataT: () => T) extends Bundle{\n val bits = Output(new CacheWTIOBackBits[T](addrBits, dataBits, blockWords, pipedataT))\n val stall = Input(Bool())\n}\n\nclass CacheWTIO[T <: Bundle](addrBits: Int, dataBits: Int, blockWords: Int, pipedataT: () => T) extends Bundle{\n val front = new CacheWTIOFront[T](addrBits, dataBits, pipedataT)\n val back = new CacheWTIOBack[T](addrBits, dataBits, blockWords, pipedataT)\n}\n\n/**\n * 单周期写通型Cache,一拍写入到WriteBuffer中\n * @pipeline\n * stage0 stage1\n 比较Tag,选择数据 字节选择,符号扩展\n * CONTROL SIGNAL---------------------->|preg|\n * |-------------|\n * ADDR------------> | Cache RAM |--->|rtag, rdata, ...|\n * |-------------|\n *\n * @param addrBits\n * @param dataBits\n * @param ways 相连数,必须为2的幂次\n * @param sets 行数\n * @param blockWords 块字个数\n * @param pipedataT 流水线其他信号\n */\nclass CacheWT[T <: Bundle](addrBits: Int, dataBits: Int, ways: Int, sets: Int, blockWords: Int, writeBuffLen: Int,\n pipedataT: () => T,\n replaceT: CacheReplaceType.CacheReplaceType=CacheReplaceType.Random,\n debug_id: Int=0) extends Module{\n require(isPowerOf2(ways))\n require(isPowerOf2(dataBits))\n\n val io = IO(new Bundle{\n val axi = new AXI4IO(addrBits, dataBits)\n val cmd = new CacheWTIO(addrBits, dataBits, blockWords, pipedataT)\n })\n \n // Block address\n // [ Tag | Index | Word | Byte ]\n // | | | |\n // line set \n val len_byte = log2Ceil(dataBits/8)\n val num_word = blockWords\n val len_word = log2Ceil(num_word)\n val len_idx = log2Ceil(sets)\n val len_tag = addrBits - len_idx - len_word - len_byte\n val beats_len = num_word\n\n val axi_w_agent = Module(new AXI4WriteAgent(addrBits, dataBits, beats_len))\n axi_w_agent.io.axi.aw <> io.axi.aw\n axi_w_agent.io.axi.w <> io.axi.w\n axi_w_agent.io.axi.b <> io.axi.b\n axi_w_agent.io.cmd.in := DontCare\n axi_w_agent.io.cmd.in.req := false.B\n val axi_r_agent = Module(new AXI4ReadAgent(addrBits, dataBits, beats_len))\n axi_r_agent.io.axi.ar <> io.axi.ar\n axi_r_agent.io.axi.r <> io.axi.r\n axi_r_agent.io.cmd.in := DontCare\n axi_r_agent.io.cmd.in.req := false.B\n\n class WriteInfo extends Bundle{\n val addr = UInt(addrBits.W)\n val size = UInt(2.W)\n val wmask = UInt((dataBits/8).W)\n val wdata = UInt(dataBits.W)\n }\n val write_buff = Module(new RingBuff(()=>new WriteInfo, writeBuffLen, 1, debug_id))\n write_buff.io.push := false.B\n write_buff.io.pop := false.B\n write_buff.io.wdata := DontCare\n write_buff.io.clear := false.B\n\n val random_way = LFSR(16)(log2Up(ways)-1, 0)\n val lru = Reg(Vec(sets, UInt(log2Up(ways).W)))\n\n val active_way = Reg(UInt(log2Up(ways).W))\n\n val data_bank = Seq.fill(ways)(Seq.fill(num_word)(Module(new Ram(dataBits, sets, RamType.RAM_1CYC))))\n val data_bank_io = VecInit(data_bank.map(t => VecInit(t.map(_.io))))\n val tag_v = Seq.fill(ways)(Module(new Ram(len_tag+1, sets, RamType.RAM_1CYC)))\n val tag_v_io = VecInit(tag_v.map(_.io))\n val addr_idx = io.cmd.front.bits.addr(len_idx+len_word+len_byte-1, len_word+len_byte)\n\n // 流水使能信号\n val pipego = Wire(Bool())\n\n tag_v_io.foreach(io => {\n io.addr := addr_idx\n io.en := pipego\n io.re := true.B\n io.we := false.B\n io.din := 0.U\n io.wmask := Fill(len_tag+1, true.B)\n })\n data_bank_io.foreach(_.foreach(io => {\n io.addr := addr_idx\n io.en := pipego\n io.re := true.B\n io.we := false.B\n io.din := 0.U\n io.wmask := Fill(dataBits, true.B)\n }))\n\n\n\n // stage1 pipeline registers\n val preg = RegEnable(io.cmd.front.bits, pipego)\n \n // // stage2 pipeline registers\n // val preg2 = RegEnable(preg, pipego)\n object StageState extends ChiselEnum {\n // 0 1 2 3 4 5 6\n val lookup, replaceWait, replace, replaceWrite, replaceEnd, uncacheReadWait, uncacheRead,\n // 7 8\n uncacheEnd, waitWriteBuff = Value\n }\n // stage2 state\n val state = RegInit(StageState.lookup)\n val hit = Wire(Bool())\n\n val pipego_reg = pipego\n\n val rdatas = RegEnable(tabulate(ways){ i =>\n tabulate(num_word){ j =>\n data_bank_io(i)(j).dout\n }\n }, pipego_reg)\n val rtags = RegEnable(tabulate(ways){ i =>\n tag_v_io(i).dout(len_tag, 1)\n }, pipego_reg)\n val rvalid = RegEnable(tabulate(ways){ i =>\n tag_v_io(i).dout(0).asBool\n }, pipego_reg)\n \n val data_ok = (\n // 当hit read/write 或者 uncache write且write_buffer未满 的时候,可以连续命中,单周期返回\n (state === StageState.lookup && ((!preg.we && hit) || (preg.we && hit && !write_buff.io.full) || (preg.we && preg.uncache && !write_buff.io.full)) ) ||\n // 替换完成\n (state === StageState.replaceEnd) ||\n // uncache访问\n (state === StageState.uncacheEnd) ||\n // 成功写入WBUFF\n (state === StageState.waitWriteBuff && !write_buff.io.full)\n )\n pipego := (data_ok ||\n // 无效命令\n !preg.valid) &&\n // 下一级无阻塞请求\n !io.cmd.back.stall\n\n\n\n val addr_reg = preg.addr\n // TODO: VIPT, let TLB pass in real tag\n val addr_tag_reg = addr_reg(addrBits-1, len_idx+len_word+len_byte)\n val addr_idx_reg = addr_reg(len_idx+len_word+len_byte-1, len_word+len_byte)\n", "right_context": "\n val rdatas_hit = WireDefault(fill(blockWords)(0.U(dataBits.W)))\n val rdatas_replace = RegInit(fill(blockWords)(0.U(dataBits.W)))\n val rdata_uncache = RegInit(0.U(dataBits.W))\n\n io.cmd.front.stall := !pipego\n io.cmd.back.bits.valid := data_ok && preg.valid\n// io.master.back.bits.rdata := Mux(state_s2 === Stage2State.replaceEnd, rdata_replace, rdata_hit)\n io.cmd.back.bits.rdata := MuxCase(rdatas_hit(addr_word_reg), Seq(\n (state === StageState.replaceEnd) -> rdatas_replace(addr_word_reg),\n (state === StageState.uncacheEnd) -> rdata_uncache\n ))\n io.cmd.back.bits.rline := Mux(state === StageState.replaceEnd, rdatas_replace,\n rdatas_hit\n )\n io.cmd.back.bits.pipedata := preg.pipedata\n\n io.cmd.back.bits.addr := addr_reg\n io.cmd.back.bits.size := preg.size\n io.cmd.back.bits.wdata := preg.wdata\n io.cmd.back.bits.wmask := preg.wmask\n\n\n val bypass_addr = Reg(UInt((len_tag+len_idx).W))\n val bypass_val = Reg(Vec(blockWords, UInt(dataBits.W)))\n val bypass_valid = Reg(Vec(blockWords, Bool()))\n for(i <- 0 until blockWords){\n bypass_valid(i) := 0.U\n }\n\n val hits = tabulate(ways){ i =>\n rtags(i) === addr_tag_reg && rvalid(i)\n }\n hit := hits.reduceTree(_||_) && !preg.uncache\n\n if(GlobalConfg.SIM){\n import nagicore.unit.DPIC_PERF_CACHE\n val dpic_perf_cache = Module(new DPIC_PERF_CACHE)\n dpic_perf_cache.io.clk := clock\n dpic_perf_cache.io.rst := reset\n dpic_perf_cache.io.valid := preg.valid && state === StageState.lookup && !io.cmd.back.stall\n dpic_perf_cache.io.id := debug_id.U\n dpic_perf_cache.io.access_type := Cat(preg.uncache, hit)\n }\n\n\n def writeRAM(io: RamIO, addr: UInt, data: UInt) = {\n io.addr := addr\n io.en := true.B\n io.re := false.B\n io.we := true.B\n io.din := data\n }\n\n // 当WriteBuff和AXIW都写完了之后,才能保证读到的是正确的\n val axi_ok_to_read = write_buff.io.empty && axi_w_agent.io.cmd.out.ready && axi_r_agent.io.cmd.out.ready\n\n def launch_uncahe_read() = {\n axi_r_agent.io.cmd.in.req := true.B\n axi_r_agent.io.cmd.in.addr := preg.addr\n axi_r_agent.io.cmd.in.size := preg.size\n axi_r_agent.io.cmd.in.len := 0.U\n state := StageState.uncacheRead\n }\n\n def lanuch_replace_read() = {\n axi_r_agent.io.cmd.in.req := true.B\n axi_r_agent.io.cmd.in.addr := addr_tag_reg ## addr_idx_reg ## 0.U((len_word+len_byte).W)\n axi_r_agent.io.cmd.in.len := (blockWords-1).U\n axi_r_agent.io.cmd.in.size := log2Up(dataBits).U\n }\n\n val hit_way = PriorityEncoder(hits)\n // 当连续hit wr/ww同一Cache行时,需要前递\n val hit_rw_bypass_need = bypass_addr === Cat(addr_tag_reg, addr_idx_reg)\n val rdatas_real = tabulate(blockWords){\n i => Mux(hit_rw_bypass_need && bypass_valid(i),\n bypass_val(i),\n rdatas(hit_way)(i)\n )\n }\n val wdata_real = Cat((0 until (dataBits/8)).reverse.map(i =>\n Mux(preg.wmask(i),\n preg.wdata(i*8+7, i*8),\n rdatas_real(addr_word_reg)(i*8+7, i*8)\n )))\n\n def write_write_buff() = {\n write_buff.io.push := true.B\n write_buff.io.wdata.addr := addr_reg\n write_buff.io.wdata.size := preg.size\n write_buff.io.wdata.wdata := wdata_real\n write_buff.io.wdata.wmask := Fill(dataBits/8, 1.U)\n }\n\n switch(state){\n is(StageState.lookup){\n when(preg.valid){\n when(hit){\n if(replaceT == CacheReplaceType.LRU){\n lru(addr_idx_reg) := ~hit_way\n }\n when(preg.we){\n // 命中写\n writeRAM(data_bank_io(hit_way)(addr_word_reg), addr_idx_reg, wdata_real)\n bypass_addr := Cat(addr_tag_reg, addr_idx_reg)\n bypass_valid(addr_word_reg) := true.B\n bypass_val(addr_word_reg) := wdata_real\n when(!write_buff.io.full){\n when(!io.cmd.back.stall){ // 防止后级阻塞时,造成多余写入\n write_write_buff()\n }\n }.otherwise{\n state := StageState.waitWriteBuff\n }\n }otherwise{\n // 命中读\n rdatas_hit := rdatas_real\n }\n state := StageState.lookup\n }.otherwise{\n when(preg.uncache){\n when(preg.we){\n when(!write_buff.io.full){\n when(!io.cmd.back.stall){ // 防止后级阻塞时,造成多余写入\n write_write_buff()\n }\n }.otherwise{\n state := StageState.waitWriteBuff\n }\n }.otherwise{\n when(axi_ok_to_read){\n launch_uncahe_read()\n }.otherwise{\n state := StageState.uncacheReadWait\n }\n }\n // or just state_s2 := Stage2State.uncacheWait\n }.otherwise{\n val active_way_wire = Wire(chiselTypeOf(active_way))\n if(replaceT == CacheReplaceType.LRU){\n active_way_wire := lru(addr_idx_reg)\n }else{\n active_way_wire := random_way\n }\n active_way := active_way_wire\n when(axi_ok_to_read){\n lanuch_replace_read()\n state := StageState.replace\n }.otherwise{\n state := StageState.replaceWait\n }\n }\n }\n }\n }\n is(StageState.replaceWait){\n when(axi_ok_to_read){\n lanuch_replace_read()\n state := StageState.replace\n }\n }\n is(StageState.replace){\n when(axi_r_agent.io.cmd.out.ready){\n val word_i = axi_r_agent.io.cmd.out.order\n val wdata_active = Mux(word_i === addr_word_reg,\n Cat((0 until (dataBits/8)).reverse.map(i =>\n Mux(preg.wmask(i),\n preg.wdata(i*8+7, i*8),\n axi_r_agent.io.cmd.out.rdata(i*8+7, i*8)\n )\n )),\n axi_r_agent.io.cmd.out.rdata\n )\n\n writeRAM(data_bank_io(active_way)(word_i), addr_idx_reg, wdata_active)\n bypass_val(word_i) := wdata_active\n\n rdatas_replace(word_i) := wdata_active\n\n when(axi_r_agent.io.cmd.out.last){\n state := StageState.replaceWrite\n writeRAM(tag_v_io(active_way), addr_idx_reg, addr_tag_reg ## 1.U(1.W))\n bypass_addr := Cat(addr_tag_reg, addr_idx_reg)\n }\n }\n }\n is(StageState.replaceWrite){\n when(!write_buff.io.full){\n write_buff.io.push := true.B\n write_buff.io.wdata.addr := preg.addr\n write_buff.io.wdata.size := preg.size\n write_buff.io.wdata.wdata := bypass_val(addr_word_reg)\n write_buff.io.wdata.wmask := Fill(dataBits/8, 1.U)\n state := StageState.replaceEnd\n }\n }\n // 等待下一级准备好接受并且成功写入到WriteBuff\n is(StageState.replaceEnd){\n when(!io.cmd.back.stall){\n state := StageState.lookup\n\n for(i <- 0 until blockWords){\n bypass_valid(i) := true.B\n }\n }\n }\n is(StageState.uncacheReadWait){\n when(axi_ok_to_read){\n launch_uncahe_read()\n }\n }\n is(StageState.uncacheRead){\n // 等待代理空闲并且WriteBuff为空\n when(axi_r_agent.io.cmd.out.ready){\n rdata_uncache := axi_r_agent.io.cmd.out.rdata\n state := StageState.uncacheEnd\n }\n }\n is(StageState.uncacheEnd){\n // 等待下一级准备好接受\n when(!io.cmd.back.stall){\n state := StageState.lookup\n }\n }\n\n is(StageState.waitWriteBuff){\n when(!write_buff.io.full){\n write_write_buff()\n\n state := StageState.lookup\n }\n }\n }\n\n when(!write_buff.io.empty){\n when(axi_w_agent.io.cmd.out.ready){\n axi_w_agent.io.cmd.in.req := true.B\n axi_w_agent.io.cmd.in.addr := write_buff.io.rdatas(0).addr\n axi_w_agent.io.cmd.in.len := 0.U\n axi_w_agent.io.cmd.in.size := write_buff.io.rdatas(0).size\n axi_w_agent.io.cmd.in.wdata(0) := write_buff.io.rdatas(0).wdata\n axi_w_agent.io.cmd.in.wmask(0) := write_buff.io.rdatas(0).wmask\n\n write_buff.io.pop := true.B\n }\n }\n}", "groundtruth": " val addr_word_reg = if(len_word!=0) addr_reg(len_word+len_byte-1, len_byte) else 0.U\n", "crossfile_context": ""}
{"task_id": "constellation", "path": "constellation/src/main/scala/channel/Nodes.scala", "left_context": "package constellation.channel\n\nimport chisel3._\nimport chisel3.experimental.SourceInfo\nimport org.chipsalliance.cde.config.{Parameters, Field}\nimport freechips.rocketchip.diplomacy._\n\n", "right_context": "\ncase class ChannelEdgeParams(cp: ChannelParams, p: Parameters)\n\nobject ChannelImp extends SimpleNodeImp[EmptyParams, ChannelParams, ChannelEdgeParams, Channel] {\n def edge(pd: EmptyParams, pu: ChannelParams, p: Parameters, sourceInfo: SourceInfo) = {\n ChannelEdgeParams(pu, p)\n }\n def bundle(e: ChannelEdgeParams) = new Channel(e.cp)(e.p)\n def render(e: ChannelEdgeParams) = if (e.cp.possibleFlows.size == 0) {\n RenderedEdge(colour = \"ffffff\", label = \"X\")\n } else {\n RenderedEdge(colour = \"#0000ff\", label = e.cp.payloadBits.toString)\n }\n\n override def monitor(bundle: Channel, edge: ChannelEdgeParams): Unit = {\n val monitor = Module(new NoCMonitor(edge.cp)(edge.p))\n monitor.io.in := bundle\n }\n // TODO: Add nodepath stuff? override def mixO, override def mixI\n}\n\ncase class ChannelSourceNode(val destId: Int)(implicit valName: ValName) extends SourceNode(ChannelImp)(Seq(EmptyParams()))\ncase class ChannelDestNode(val destParams: ChannelParams)(implicit valName: ValName) extends SinkNode(ChannelImp)(Seq(destParams))\ncase class ChannelAdapterNode(\n slaveFn: ChannelParams => ChannelParams = { d => d })(\n implicit valName: ValName) extends AdapterNode(ChannelImp)((e: EmptyParams) => e, slaveFn)\ncase class ChannelIdentityNode()(implicit valName: ValName) extends IdentityNode(ChannelImp)()\ncase class ChannelEphemeralNode()(implicit valName: ValName) extends EphemeralNode(ChannelImp)()\n\ncase class IngressChannelEdgeParams(cp: IngressChannelParams, p: Parameters)\ncase class EgressChannelEdgeParams(cp: EgressChannelParams, p: Parameters)\n\nobject IngressChannelImp extends SimpleNodeImp[EmptyParams, IngressChannelParams, IngressChannelEdgeParams, IngressChannel] {\n def edge(pd: EmptyParams, pu: IngressChannelParams, p: Parameters, sourceInfo: SourceInfo) = {\n IngressChannelEdgeParams(pu, p)\n }\n def bundle(e: IngressChannelEdgeParams) = new IngressChannel(e.cp)(e.p)\n def render(e: IngressChannelEdgeParams) = if (e.cp.possibleFlows.size == 0) {\n RenderedEdge(colour = \"ffffff\", label = \"X\")\n } else {\n RenderedEdge(colour = \"#00ff00\", label = e.cp.payloadBits.toString)\n }\n}\n\nobject EgressChannelImp extends SimpleNodeImp[EmptyParams, EgressChannelParams, EgressChannelEdgeParams, EgressChannel] {\n def edge(pd: EmptyParams, pu: EgressChannelParams, p: Parameters, sourceInfo: SourceInfo) = {\n EgressChannelEdgeParams(pu, p)\n }\n def bundle(e: EgressChannelEdgeParams) = new EgressChannel(e.cp)(e.p)\n def render(e: EgressChannelEdgeParams) = if (e.cp.possibleFlows.size == 0) {\n RenderedEdge(colour = \"ffffff\", label = \"X\")\n } else {\n RenderedEdge(colour = \"#ff0000\", label = e.cp.payloadBits.toString)\n }\n}\n\ncase class IngressChannelSourceNode(val destId: Int)(implicit valName: ValName) extends SourceNode(IngressChannelImp)(Seq(EmptyParams()))\ncase class IngressChannelDestNode(val destParams: IngressChannelParams)(implicit valName: ValName) extends SinkNode(IngressChannelImp)(Seq(destParams))\ncase class EgressChannelSourceNode(val egressId: Int)(implicit valName: ValName) extends SourceNode(EgressChannelImp)(Seq(EmptyParams()))\ncase class EgressChannelDestNode(val destParams: EgressChannelParams)(implicit valName: ValName) extends SinkNode(EgressChannelImp)(Seq(destParams))\n\n\ncase class IngressChannelAdapterNode(\n slaveFn: IngressChannelParams => IngressChannelParams = { d => d })(\n implicit valName: ValName) extends AdapterNode(IngressChannelImp)(m => m, slaveFn)\n\ncase class EgressChannelAdapterNode(\n slaveFn: EgressChannelParams => EgressChannelParams = { d => d })(\n implicit valName: ValName) extends AdapterNode(EgressChannelImp)(m => m, slaveFn)\n\ncase class IngressChannelIdentityNode()(implicit valName: ValName) extends IdentityNode(IngressChannelImp)()\ncase class EgressChannelIdentityNode()(implicit valName: ValName) extends IdentityNode(EgressChannelImp)()\n\ncase class IngressChannelEphemeralNode()(implicit valName: ValName) extends EphemeralNode(IngressChannelImp)()\ncase class EgressChannelEphemeralNode()(implicit valName: ValName) extends EphemeralNode(EgressChannelImp)()\n", "groundtruth": "case class EmptyParams()\n", "crossfile_context": ""}
{"task_id": "constellation", "path": "constellation/src/main/scala/channel/WidthWidget.scala", "left_context": "package constellation.channel\n\nimport chisel3._\nimport chisel3.util._\nimport freechips.rocketchip.diplomacy._\nimport org.chipsalliance.cde.config.{Parameters}\nimport freechips.rocketchip.util._\n\nobject WidthWidget {\n def split[T <: BaseFlit](in: IrrevocableIO[T], out: IrrevocableIO[T]) = {\n val inBits = in.bits.payload.getWidth\n val outBits = out.bits.payload.getWidth\n require(inBits > outBits && inBits % outBits == 0)\n val ratio = inBits / outBits\n val count = RegInit(0.U(log2Ceil(ratio).W))\n val first = count === 0.U\n val last = count === (ratio - 1).U\n val stored = Reg(UInt((inBits - outBits).W))\n\n out.valid := in.valid\n out.bits := in.bits\n out.bits.head := in.bits.head && first\n out.bits.tail := in.bits.tail && last\n out.bits.payload := Mux(first, in.bits.payload, stored)\n in.ready := last && out.ready\n when (out.fire) {\n count := Mux(last, 0.U, count + 1.U)\n stored := Mux(first, in.bits.payload, stored) >> outBits\n }\n }\n\n def merge[T <: BaseFlit](in: IrrevocableIO[T], out: IrrevocableIO[T]) = {\n val inBits = in.bits.payload.getWidth\n val outBits = out.bits.payload.getWidth\n require(outBits > inBits && outBits % inBits == 0)\n val ratio = outBits / inBits\n val count = RegInit(0.U(log2Ceil(ratio).W))\n val first = count === 0.U\n val last = count === (ratio - 1).U\n val flit = Reg(out.bits.cloneType)\n val payload = Reg(Vec(ratio-1, UInt(inBits.W)))\n\n out.valid := in.valid && last\n out.bits := flit\n out.bits.tail := last && in.bits.tail\n out.bits.payload := Cat(in.bits.payload, payload.asUInt)\n in.ready := !last || out.ready\n when (in.fire) {\n count := Mux(last, 0.U, count + 1.U)\n payload(count) := in.bits.payload\n when (first) {\n flit := in.bits\n }\n }\n }\n\n def apply[T <: BaseFlit](in: IrrevocableIO[T], out: IrrevocableIO[T]) = {\n val inBits = in.bits.payload.getWidth\n val outBits = out.bits.payload.getWidth\n\n if (inBits == outBits) {\n out <> in\n } else if (inBits < outBits) {\n merge(in, out)\n } else {\n split(in, out)\n }\n }\n}\n\nclass IngressWidthWidget(srcBits: Int)(implicit p: Parameters) extends LazyModule {\n val node = new IngressChannelAdapterNode(\n slaveFn = { s => s.copy(payloadBits=srcBits) }\n )\n lazy val module = new LazyModuleImp(this) {\n (node.in zip node.out) foreach { case ((in, edgeIn), (out, edgeOut)) =>\n WidthWidget(in.flit, out.flit)\n }\n }\n}\n\nobject IngressWidthWidget {\n def apply(destBits: Int, srcBits: Int)(implicit p: Parameters) = {\n if (destBits == srcBits) {\n val node = IngressChannelEphemeralNode()\n node\n } else {\n val ingress_width_widget = LazyModule(new IngressWidthWidget(srcBits))\n ingress_width_widget.node\n }\n }\n}\n\nclass EgressWidthWidget(srcBits: Int)(implicit p: Parameters) extends LazyModule {\n val node = new EgressChannelAdapterNode(\n", "right_context": " )\n lazy val module = new LazyModuleImp(this) {\n (node.in zip node.out) foreach { case ((in, edgeIn), (out, edgeOut)) =>\n WidthWidget(in.flit, out.flit)\n }\n }\n}\n\nobject EgressWidthWidget {\n def apply(destBits: Int, srcBits: Int)(implicit p: Parameters) = {\n if (destBits == srcBits) {\n val node = EgressChannelEphemeralNode()\n node\n } else {\n val egress_width_widget = LazyModule(new EgressWidthWidget(srcBits))\n egress_width_widget.node\n }\n }\n}\n\nclass ChannelWidthWidget(srcBits: Int)(implicit p: Parameters) extends LazyModule {\n val node = new ChannelAdapterNode(\n slaveFn = { s =>\n val destBits = s.payloadBits\n if (srcBits > destBits) {\n val ratio = srcBits / destBits\n val virtualChannelParams = s.virtualChannelParams.map { vP =>\n require(vP.bufferSize >= ratio)\n vP.copy(bufferSize = vP.bufferSize / ratio)\n }\n s.copy(payloadBits=srcBits, virtualChannelParams=virtualChannelParams)\n } else {\n val ratio = destBits / srcBits\n val virtualChannelParams = s.virtualChannelParams.map { vP =>\n vP.copy(bufferSize = vP.bufferSize * ratio)\n }\n s.copy(payloadBits=srcBits, virtualChannelParams=virtualChannelParams)\n }\n }\n )\n lazy val module = new LazyModuleImp(this) {\n (node.in zip node.out) foreach { case ((in, edgeIn), (out, edgeOut)) =>\n val destBits = out.cParam.payloadBits\n in.vc_free := out.vc_free\n if (srcBits == destBits) {\n in.credit_return := out.credit_return\n out.flit <> in.flit\n } else if (srcBits > destBits) {\n require(srcBits % destBits == 0, s\"$srcBits, $destBits\")\n\n (in.flit zip out.flit) foreach { case (iF, oF) =>\n val in_q = Module(new Queue(new Flit(in.cParam.payloadBits),\n in.cParam.virtualChannelParams.map(_.bufferSize).sum, pipe=true, flow=true))\n in_q.io.enq.valid := iF.valid\n in_q.io.enq.bits := iF.bits\n assert(!(in_q.io.enq.valid && !in_q.io.enq.ready))\n\n val in_flit = Wire(Irrevocable(new Flit(in.cParam.payloadBits)))\n in_flit.valid := in_q.io.deq.valid\n in_flit.bits := in_q.io.deq.bits\n in_q.io.deq.ready := in_flit.ready\n\n val out_flit = Wire(Irrevocable(new Flit(out.cParam.payloadBits)))\n oF.valid := out_flit.valid\n oF.bits := out_flit.bits\n out_flit.ready := true.B\n WidthWidget(in_flit, out_flit)\n }\n\n val ratio = srcBits / destBits\n val counts = RegInit(VecInit(Seq.fill(in.nVirtualChannels) { 0.U(log2Ceil(ratio).W) }))\n val in_credit_return = Wire(Vec(in.nVirtualChannels, Bool()))\n in.credit_return := in_credit_return.asUInt\n for (i <- 0 until in.nVirtualChannels) {\n in_credit_return(i) := false.B\n when (out.credit_return(i)) {\n val last = counts(i) === (ratio-1).U\n counts(i) := Mux(last, 0.U, counts(i) + 1.U)\n when (last) {\n in_credit_return(i) := true.B\n }\n }\n }\n } else {\n require(destBits % srcBits == 0)\n\n val in_flits = Wire(Vec(in.nVirtualChannels, Irrevocable(new Flit(in.cParam.payloadBits))))\n val out_flits = Wire(Vec(in.nVirtualChannels, Irrevocable(new Flit(out.cParam.payloadBits))))\n for (i <- 0 until in.nVirtualChannels) {\n val sel = in.flit.map(f => f.valid && f.bits.virt_channel_id === i.U)\n in_flits(i).valid := sel.orR\n in_flits(i).bits := Mux1H(sel, in.flit.map(_.bits))\n\n out_flits(i).ready := sel.orR\n WidthWidget(in_flits(i), out_flits(i))\n }\n for (i <- 0 until in.flit.size) {\n val sel = UIntToOH(in.flit(i).bits.virt_channel_id)\n out.flit(i).valid := Mux1H(sel, out_flits.map(_.valid))\n out.flit(i).bits := Mux1H(sel, out_flits.map(_.bits))\n }\n\n val ratio = destBits / srcBits\n val credits = RegInit(VecInit((0 until in.nVirtualChannels).map { i =>\n 0.U(log2Ceil(ratio*in.cParam.virtualChannelParams(i).bufferSize).W)\n }))\n val in_credit_return = Wire(Vec(in.nVirtualChannels, Bool()))\n in.credit_return := in_credit_return.asUInt\n for (i <- 0 until in.nVirtualChannels) {\n when (out.credit_return(i)) {\n in_credit_return(i) := true.B\n credits(i) := credits(i) + (ratio - 1).U\n } .otherwise {\n val empty = credits(i) === 0.U\n in_credit_return(i) := !empty\n credits(i) := Mux(empty, 0.U, credits(i) - 1.U)\n }\n }\n }\n }\n }\n}\n\nobject ChannelWidthWidget {\n def apply(destBits: Int, srcBits: Int)(implicit p: Parameters) = {\n if (destBits == srcBits) {\n val node = ChannelEphemeralNode()\n node\n } else {\n val channel_width_widget = LazyModule(new ChannelWidthWidget(srcBits))\n channel_width_widget.node\n }\n }\n}\n", "groundtruth": " slaveFn = { s => s.copy(payloadBits=srcBits) }\n", "crossfile_context": ""}
{"task_id": "constellation", "path": "constellation/src/main/scala/noc/NoC.scala", "left_context": "package constellation.noc\n\nimport chisel3._\nimport chisel3.util._\n\n\nimport org.chipsalliance.cde.config.{Field, Parameters}\nimport freechips.rocketchip.diplomacy.{LazyModule, LazyModuleImp, BundleBridgeSink, InModuleBody}\nimport freechips.rocketchip.util.ElaborationArtefacts\nimport freechips.rocketchip.prci._\nimport constellation.router._\nimport constellation.channel._\nimport constellation.routing.{RoutingRelation, ChannelRoutingInfo}\nimport constellation.topology.{PhysicalTopology, UnidirectionalLine}\n\n\nclass NoCTerminalIO(\n val ingressParams: Seq[IngressChannelParams],\n val egressParams: Seq[EgressChannelParams])(implicit val p: Parameters) extends Bundle {\n val ingress = MixedVec(ingressParams.map { u => Flipped(new IngressChannel(u)) })\n val egress = MixedVec(egressParams.map { u => new EgressChannel(u) })\n}\n\nclass NoC(nocParams: NoCParams)(implicit p: Parameters) extends LazyModule {\n\n override def shouldBeInlined = nocParams.inlineNoC\n\n val internalParams = InternalNoCParams(nocParams)\n val allChannelParams = internalParams.channelParams\n val allIngressParams = internalParams.ingressParams\n val allEgressParams = internalParams.egressParams\n val allRouterParams = internalParams.routerParams\n\n val iP = p.alterPartial({ case InternalNoCKey => internalParams })\n val nNodes = nocParams.topology.nNodes\n val nocName = nocParams.nocName\n val skipValidationChecks = nocParams.skipValidationChecks\n\n val clockSourceNodes = Seq.tabulate(nNodes) { i => ClockSourceNode(Seq(ClockSourceParameters())) }\n val router_sink_domains = Seq.tabulate(nNodes) { i =>\n val router_sink_domain = LazyModule(new ClockSinkDomain(ClockSinkParameters(\n name = Some(s\"${nocName}_router_$i\")\n )))\n router_sink_domain.clockNode := clockSourceNodes(i)\n router_sink_domain\n }\n\n val routers = Seq.tabulate(nNodes) { i => router_sink_domains(i) {\n val inParams = allChannelParams.filter(_.destId == i).map(\n _.copy(payloadBits=allRouterParams(i).user.payloadBits)\n )\n val outParams = allChannelParams.filter(_.srcId == i).map(\n _.copy(payloadBits=allRouterParams(i).user.payloadBits)\n )\n val ingressParams = allIngressParams.filter(_.destId == i).map(\n _.copy(payloadBits=allRouterParams(i).user.payloadBits)\n )\n val egressParams = allEgressParams.filter(_.srcId == i).map(\n _.copy(payloadBits=allRouterParams(i).user.payloadBits)\n )\n val noIn = inParams.size + ingressParams.size == 0\n val noOut = outParams.size + egressParams.size == 0\n if (noIn || noOut) {\n println(s\"Constellation WARNING: $nocName router $i seems to be unused, it will not be generated\")\n None\n } else {\n Some(LazyModule(new Router(\n routerParams = allRouterParams(i),\n preDiplomaticInParams = inParams,\n preDiplomaticIngressParams = ingressParams,\n outDests = outParams.map(_.destId),\n egressIds = egressParams.map(_.egressId)\n )(iP)))\n }\n }}.flatten\n\n val ingressNodes = allIngressParams.map { u => IngressChannelSourceNode(u.destId) }\n val egressNodes = allEgressParams.map { u => EgressChannelDestNode(u) }\n\n // Generate channels between routers diplomatically\n Seq.tabulate(nNodes, nNodes) { case (i, j) => if (i != j) {\n val routerI = routers.find(_.nodeId == i)\n val routerJ = routers.find(_.nodeId == j)\n if (routerI.isDefined && routerJ.isDefined) {\n val sourceNodes: Seq[ChannelSourceNode] = routerI.get.sourceNodes.filter(_.destId == j)\n val destNodes: Seq[ChannelDestNode] = routerJ.get.destNodes.filter(_.destParams.srcId == i)\n require (sourceNodes.size == destNodes.size)\n (sourceNodes zip destNodes).foreach { case (src, dst) =>\n val channelParam = allChannelParams.find(c => c.srcId == i && c.destId == j).get\n router_sink_domains(j) {\n implicit val p: Parameters = iP\n (dst\n := ChannelWidthWidget(routerJ.get.payloadBits, routerI.get.payloadBits)\n := channelParam.channelGen(p)(src)\n )\n }\n }\n }\n }}\n\n // Generate terminal channels diplomatically\n routers.foreach { dst => router_sink_domains(dst.nodeId) {\n implicit val p: Parameters = iP\n dst.ingressNodes.foreach(n => {\n val ingressId = n.destParams.ingressId\n require(dst.payloadBits <= allIngressParams(ingressId).payloadBits)\n (n\n := IngressWidthWidget(dst.payloadBits, allIngressParams(ingressId).payloadBits)\n := ingressNodes(ingressId)\n )\n })\n dst.egressNodes.foreach(n => {\n val egressId = n.egressId\n require(dst.payloadBits <= allEgressParams(egressId).payloadBits)\n (egressNodes(egressId)\n := EgressWidthWidget(allEgressParams(egressId).payloadBits, dst.payloadBits)\n := n\n )\n })\n }}\n\n val debugNodes = routers.map { r =>\n val sink = BundleBridgeSink[DebugBundle]()\n sink := r.debugNode\n sink\n }\n val ctrlNodes = if (nocParams.hasCtrl) {\n (0 until nNodes).map { i =>\n routers.find(_.nodeId == i).map { r =>\n val sink = BundleBridgeSink[RouterCtrlBundle]()\n sink := r.ctrlNode.get\n sink\n }\n }\n } else {\n Nil\n }\n\n println(s\"Constellation: $nocName Finished parameter validation\")\n lazy val module = new Impl\n class Impl extends LazyModuleImp(this) {\n println(s\"Constellation: $nocName Starting NoC RTL generation\")\n val io = IO(new NoCTerminalIO(allIngressParams, allEgressParams)(iP) {\n val router_clocks = Vec(nNodes, Input(new ClockBundle(ClockBundleParameters())))\n val router_ctrl = if (nocParams.hasCtrl) Vec(nNodes, new RouterCtrlBundle) else Nil\n })\n\n (io.ingress zip ingressNodes.map(_.out(0)._1)).foreach { case (l,r) => r <> l }\n (io.egress zip egressNodes .map(_.in (0)._1)).foreach { case (l,r) => l <> r }\n (io.router_clocks zip clockSourceNodes.map(_.out(0)._1)).foreach { case (l,r) => l <> r }\n\n if (nocParams.hasCtrl) {\n ctrlNodes.zipWithIndex.map { case (c,i) =>\n if (c.isDefined) {\n io.router_ctrl(i) <> c.get.in(0)._1\n } else {\n io.router_ctrl(i) <> DontCare\n }\n }\n }\n\n // TODO: These assume a single clock-domain across the entire noc\n val debug_va_stall_ctr = RegInit(0.U(64.W))\n val debug_sa_stall_ctr = RegInit(0.U(64.W))\n val debug_any_stall_ctr = debug_va_stall_ctr + debug_sa_stall_ctr\n debug_va_stall_ctr := debug_va_stall_ctr + debugNodes.map(_.in(0)._1.va_stall.reduce(_+_)).reduce(_+_)\n debug_sa_stall_ctr := debug_sa_stall_ctr + debugNodes.map(_.in(0)._1.sa_stall.reduce(_+_)).reduce(_+_)\n\n dontTouch(debug_va_stall_ctr)\n dontTouch(debug_sa_stall_ctr)\n dontTouch(debug_any_stall_ctr)\n\n def prepend(s: String) = Seq(nocName, s).mkString(\".\")\n ElaborationArtefacts.add(prepend(\"noc.graphml\"), graphML)\n\n val adjList = routers.map { r =>\n val outs = r.outParams.map(o => s\"${o.destId}\").mkString(\" \")\n val egresses = r.egressParams.map(e => s\"e${e.egressId}\").mkString(\" \")\n val ingresses = r.ingressParams.map(i => s\"i${i.ingressId} ${r.nodeId}\")\n", "right_context": " }.mkString(\"\\n\")\n ElaborationArtefacts.add(prepend(\"noc.adjlist\"), adjList)\n\n val xys = routers.map(r => {\n val n = r.nodeId\n val ids = (Seq(r.nodeId.toString)\n ++ r.egressParams.map(e => s\"e${e.egressId}\")\n ++ r.ingressParams.map(i => s\"i${i.ingressId}\")\n )\n val plotter = nocParams.topology.plotter\n val coords = (Seq(plotter.node(r.nodeId))\n ++ Seq.tabulate(r.egressParams.size ) { i => plotter. egress(i, r. egressParams.size, r.nodeId) }\n ++ Seq.tabulate(r.ingressParams.size) { i => plotter.ingress(i, r.ingressParams.size, r.nodeId) }\n )\n\n (ids zip coords).map { case (i, (x, y)) => s\"$i $x $y\" }.mkString(\"\\n\")\n }).mkString(\"\\n\")\n ElaborationArtefacts.add(prepend(\"noc.xy\"), xys)\n\n val edgeProps = routers.map { r =>\n val outs = r.outParams.map { o =>\n (Seq(s\"${r.nodeId} ${o.destId}\") ++ (if (o.possibleFlows.size == 0) Some(\"unused\") else None))\n .mkString(\" \")\n }\n val egresses = r.egressParams.map { e =>\n (Seq(s\"${r.nodeId} e${e.egressId}\") ++ (if (e.possibleFlows.size == 0) Some(\"unused\") else None))\n .mkString(\" \")\n }\n val ingresses = r.ingressParams.map { i =>\n (Seq(s\"i${i.ingressId} ${r.nodeId}\") ++ (if (i.possibleFlows.size == 0) Some(\"unused\") else None))\n .mkString(\" \")\n }\n (outs ++ egresses ++ ingresses).mkString(\"\\n\")\n }.mkString(\"\\n\")\n ElaborationArtefacts.add(prepend(\"noc.edgeprops\"), edgeProps)\n\n println(s\"Constellation: $nocName Finished NoC RTL generation\")\n }\n}\n", "groundtruth": " (Seq(s\"${r.nodeId} $outs $egresses\") ++ ingresses).mkString(\"\\n\")\n", "crossfile_context": ""}
{"task_id": "constellation", "path": "constellation/src/main/scala/protocol/AXI4.scala", "left_context": "package constellation.protocol\n\nimport chisel3._\nimport chisel3.util._\n\nimport constellation.channel._\nimport constellation.noc._\n\nimport org.chipsalliance.cde.config._\nimport freechips.rocketchip.diplomacy._\nimport freechips.rocketchip.util._\nimport freechips.rocketchip.amba.axi4._\n\ntrait AXI4FieldHelper {\n val wideBundle: AXI4BundleParameters\n}\nclass AXI4MasterToNoC(\n edgeIn: AXI4EdgeParameters, edgesOut: Seq[AXI4EdgeParameters],\n sourceStart: Int, sourceSize: Int,\n wideBundle: AXI4BundleParameters,\n slaveToEgressOffset: Int => Int,\n flitWidth: Int,\n awQueueDepth: Int\n)(implicit p: Parameters) extends Module {\n // Can only keep 1 in-flight per ID because NoC can't guarantee\n // FIFO between bursts with the same ID\n val maxFlightPerId = 1\n\n val io = IO(new Bundle {\n val axi4 = Flipped(new AXI4Bundle(wideBundle))\n val flits = new Bundle {\n val aw = Decoupled(new IngressFlit(flitWidth))\n val w = Decoupled(new IngressFlit(flitWidth))\n val ar = Decoupled(new IngressFlit(flitWidth))\n val r = Flipped(Decoupled(new EgressFlit(flitWidth)))\n val b = Flipped(Decoupled(new EgressFlit(flitWidth)))\n }\n })\n\n val port_addrs = edgesOut.map(_.slave.slaves.map(_.address).flatten)\n val routingMask = AddressDecoder(port_addrs)\n val route_addrs = port_addrs.map(seq => AddressSet.unify(seq.map(_.widen(~routingMask)).distinct))\n val outputPorts = route_addrs.map(seq => (addr: UInt) => seq.map(_.contains(addr)).reduce(_||_))\n\n // To route W need to record where AW went\n class AWInBundle extends Bundle {\n val out = UInt(edgesOut.size.W)\n val id = UInt(wideBundle.idBits.W)\n }\n val awIn = Module(new Queue(new AWInBundle, awQueueDepth, flow=true))\n\n val requestARIO = VecInit(outputPorts.map { o => o(io.axi4.ar.bits.addr) })\n val requestAWIO = VecInit(outputPorts.map { o => o(io.axi4.aw.bits.addr) })\n\n // W follows path dicated by AW Q\n awIn.io.enq.bits.out := requestAWIO.asUInt\n awIn.io.enq.bits.id := io.axi4.aw.bits.id | sourceStart.U\n val requestWIO = awIn.io.deq.bits.out.asBools\n\n val in = Wire(new AXI4Bundle(wideBundle))\n in <> io.axi4\n\n // Handle size = 1 gracefully (Chisel3 empty range is broken)\n def trim(id: UInt, size: Int) = if (size <= 1) 0.U else id(log2Ceil(size)-1, 0)\n\n // Manipulate the AXI IDs to differentiate masters\n in.aw.bits.id := io.axi4.aw.bits.id | sourceStart.U\n in.ar.bits.id := io.axi4.ar.bits.id | sourceStart.U\n io.axi4.r.bits.id := trim(in.r.bits.id, sourceSize)\n io.axi4.b.bits.id := trim(in.b.bits.id, sourceSize)\n\n // Block A[RW] if we switch ports, to ensure responses stay ordered (also: beware the dining philosophers)\n val endId = edgeIn.master.endId\n", "right_context": " val awFIFOMap = WireInit(VecInit(Seq.fill(endId) { true.B }))\n val arSel = UIntToOH(io.axi4.ar.bits.id, endId)\n val awSel = UIntToOH(io.axi4.aw.bits.id, endId)\n val rSel = UIntToOH(io.axi4.r .bits.id, endId)\n val bSel = UIntToOH(io.axi4.b .bits.id, endId)\n val arTag = OHToUInt(requestARIO.asUInt, edgesOut.size)\n val awTag = OHToUInt(requestAWIO.asUInt, edgesOut.size)\n\n for (master <- edgeIn.master.masters) {\n def idTracker(port: UInt, req_fire: Bool, resp_fire: Bool) = {\n if (master.maxFlight == Some(0)) {\n true.B\n } else {\n val legalFlight = master.maxFlight.getOrElse(maxFlightPerId+1)\n val flight = legalFlight min maxFlightPerId\n val canOverflow = legalFlight > flight\n val count = RegInit(0.U(log2Ceil(flight+1).W))\n val last = Reg(UInt(log2Ceil(edgesOut.size).W))\n count := count + req_fire.asUInt - resp_fire.asUInt\n assert (!resp_fire || count =/= 0.U)\n assert (!req_fire || count =/= flight.U)\n when (req_fire) { last := port }\n // No need to track where it went if we cap it at 1 request\n val portMatch = if (flight == 1) { true.B } else { last === port }\n (count === 0.U || portMatch) && (!canOverflow.B || count =/= flight.U)\n }\n }\n\n for (id <- master.id.start until master.id.end) {\n arFIFOMap(id) := idTracker(\n arTag,\n arSel(id) && io.axi4.ar.fire,\n rSel(id) && io.axi4.r.fire && io.axi4.r.bits.last)\n awFIFOMap(id) := idTracker(\n awTag,\n awSel(id) && io.axi4.aw.fire,\n bSel(id) && io.axi4.b.fire)\n }\n }\n\n val allowAR = arFIFOMap(io.axi4.ar.bits.id)\n in.ar.valid := io.axi4.ar.valid && allowAR\n io.axi4.ar.ready := in.ar.ready && allowAR\n\n // Block AW if we cannot record the W destination\n val allowAW = awFIFOMap(io.axi4.aw.bits.id)\n in.aw.valid := io.axi4.aw.valid && awIn.io.enq.ready && allowAW\n io.axi4.aw.ready := in.aw.ready && awIn.io.enq.ready && allowAW\n awIn.io.enq.valid := io.axi4.aw.valid && in.aw.ready && allowAW\n\n // Block W if we do not have an AW destination\n in.w.valid := io.axi4.w.valid && awIn.io.deq.valid\n io.axi4.w.ready := in.w.ready && awIn.io.deq.valid\n awIn.io.deq.ready := io.axi4.w.valid && io.axi4.w.bits.last && in.w.ready\n\n io.flits.aw.valid := in.aw.valid\n in.aw.ready := io.flits.aw.ready\n io.flits.aw.bits.head := true.B\n io.flits.aw.bits.tail := true.B\n io.flits.aw.bits.payload := in.aw.bits.asUInt\n io.flits.aw.bits.egress_id := Mux1H(requestAWIO.zipWithIndex.map { case (r, i) =>\n r -> (slaveToEgressOffset(i) + 0).U\n })\n\n val w_first = RegInit(true.B)\n io.flits.w.valid := in.w.valid\n in.w.ready := io.flits.w.ready\n io.flits.w.bits.head := w_first\n io.flits.w.bits.tail := in.w.bits.last\n io.flits.w.bits.payload := Cat(awIn.io.deq.bits.id, in.w.bits.asUInt)\n io.flits.w.bits.egress_id := Mux1H(requestWIO.zipWithIndex.map { case (r, i) =>\n r -> (slaveToEgressOffset(i) + 1).U\n })\n when (io.flits.w.fire) { w_first := in.w.bits.last }\n\n io.flits.ar.valid := in.ar.valid\n in.ar.ready := io.flits.ar.ready\n io.flits.ar.bits.head := true.B\n io.flits.ar.bits.tail := true.B\n io.flits.ar.bits.payload := in.ar.bits.asUInt\n io.flits.ar.bits.egress_id := Mux1H(requestARIO.zipWithIndex.map { case (r, i) =>\n r -> (slaveToEgressOffset(i) + 2).U\n })\n\n in.b.valid := io.flits.b.valid\n io.flits.b.ready := in.b.ready\n in.b.bits := io.flits.b.bits.payload.asTypeOf(in.b.bits)\n\n in.r.valid := io.flits.r.valid\n io.flits.r.ready := in.r.ready\n in.r.bits := io.flits.r.bits.payload.asTypeOf(in.r.bits)\n}\n\nclass AXI4SlaveToNoC(\n edgeOut: AXI4EdgeParameters, edgesIn: Seq[AXI4EdgeParameters],\n wideBundle: AXI4BundleParameters,\n masterToEgressOffset: Int => Int,\n flitWidth: Int,\n awQueueDepth: Int\n)(implicit p: Parameters) extends Module {\n val io = IO(new Bundle {\n val axi4 = new AXI4Bundle(wideBundle)\n val flits = new Bundle {\n val aw = Flipped(Decoupled(new EgressFlit(flitWidth)))\n val w = Flipped(Decoupled(new EgressFlit(flitWidth)))\n val ar = Flipped(Decoupled(new EgressFlit(flitWidth)))\n val r = Decoupled(new IngressFlit(flitWidth))\n val b = Decoupled(new IngressFlit(flitWidth))\n }\n })\n val out = Wire(new AXI4Bundle(wideBundle))\n val out_w_in_head = Wire(Bool())\n val out_w_in_id = Wire(UInt((1 << wideBundle.idBits).W))\n io.axi4 <> out\n\n // Grab the port ID mapping\n val inputIdRanges = AXI4Xbar.mapInputIds(edgesIn.map(_.master))\n\n val requestROI = inputIdRanges.map { i => i.contains(io.axi4.r.bits.id) }\n val requestBOI = inputIdRanges.map { i => i.contains(io.axi4.b.bits.id) }\n\n // Store the incoming AW messages in a buffer, 1 entry per source ID\n // Order the AW/W based on the arriving order of W bursts\n val aw_val = RegInit(VecInit(0.U((1 << wideBundle.idBits).W).asBools))\n val aw_buf = Reg(Vec(1 << wideBundle.idBits, new AXI4BundleAW(wideBundle)))\n val w_fire = RegInit(false.B)\n val aw_q = Module(new Queue(new AXI4BundleAW(wideBundle), awQueueDepth, pipe=true))\n\n io.axi4.aw <> aw_q.io.deq\n\n out.aw.ready := !aw_val(out.aw.bits.id)\n when (out.aw.fire) {\n aw_val(out.aw.bits.id) := true.B\n aw_buf(out.aw.bits.id) := out.aw.bits\n }\n\n aw_q.io.enq.valid := out.w.valid && Mux1H(out_w_in_id, aw_val) && out_w_in_head\n aw_q.io.enq.bits := Mux1H(out_w_in_id, aw_buf)\n when (aw_q.io.enq.fire) {\n aw_val(OHToUInt(out_w_in_id)) := false.B\n w_fire := true.B\n }\n\n out.w.ready := io.axi4.w.ready && (\n w_fire || (out_w_in_head && aw_q.io.enq.ready && Mux1H(out_w_in_id, aw_val))\n )\n io.axi4.w.bits := out.w.bits\n io.axi4.w.valid := out.w.valid && (\n w_fire || (out_w_in_head && aw_q.io.enq.ready && Mux1H(out_w_in_id, aw_val))\n )\n\n when (out.w.fire && out.w.bits.last) { w_fire := false.B }\n\n val r_first = RegInit(true.B)\n io.flits.r.valid := out.r.valid\n out.r.ready := io.flits.r.ready\n io.flits.r.bits.head := r_first\n io.flits.r.bits.tail := out.r.bits.last\n io.flits.r.bits.payload := out.r.bits.asUInt\n io.flits.r.bits.egress_id := Mux1H(requestROI.zipWithIndex.map { case (r, i) =>\n r -> (masterToEgressOffset(i) + 0).U\n })\n when (io.flits.r.fire) { r_first := out.r.bits.last }\n\n io.flits.b.valid := out.b.valid\n out.b.ready := io.flits.b.ready\n io.flits.b.bits.head := true.B\n io.flits.b.bits.tail := true.B\n io.flits.b.bits.payload := out.b.bits.asUInt\n io.flits.b.bits.egress_id := Mux1H(requestBOI.zipWithIndex.map { case (r, i) =>\n r -> (masterToEgressOffset(i) + 1).U\n })\n\n out_w_in_head := io.flits.w.bits.head\n out_w_in_id := UIntToOH(io.flits.w.bits.payload.asUInt >> out.w.bits.getWidth)\n\n out.aw.valid := io.flits.aw.valid\n io.flits.aw.ready := out.aw.ready\n out.aw.bits := io.flits.aw.bits.payload.asTypeOf(out.aw.bits)\n\n out.w.valid := io.flits.w.valid\n io.flits.w.ready := out.w.ready\n out.w.bits := io.flits.w.bits.payload.asTypeOf(out.w.bits)\n\n out.ar.valid := io.flits.ar.valid\n io.flits.ar.ready := out.ar.ready\n out.ar.bits := io.flits.ar.bits.payload.asTypeOf(out.ar.bits)\n}\n\nclass AXI4InterconnectInterface(edgesIn: Seq[AXI4EdgeParameters], edgesOut: Seq[AXI4EdgeParameters])(implicit val p: Parameters) extends Bundle {\n val in = MixedVec(edgesIn.map { e => Flipped(new AXI4Bundle(e.bundle)) })\n val out = MixedVec(edgesOut.map { e => new AXI4Bundle(e.bundle) })\n}\n\n\n// BEGIN: AXI4ProtocolParams\ncase class AXI4ProtocolParams(\n edgesIn: Seq[AXI4EdgeParameters],\n edgesOut: Seq[AXI4EdgeParameters],\n edgeInNodes: Seq[Int],\n edgeOutNodes: Seq[Int],\n awQueueDepth: Int\n) extends ProtocolParams {\n // END: AXI4ProtocolParams\n val wideBundle = AXI4BundleParameters.union(edgesIn.map(_.bundle) ++ edgesOut.map(_.bundle))\n val inputIdRanges = AXI4Xbar.mapInputIds(edgesIn.map(_.master))\n val minPayloadWidth = {\n val b = new AXI4Bundle(wideBundle)\n Seq(b.aw, b.ar, b.w, b.b, b.r).map { t => t.bits match {\n case b: AXI4BundleAW => b.getWidth\n case b: AXI4BundleW => b.getWidth + wideBundle.idBits\n case b: AXI4BundleAR => b.getWidth\n case b: AXI4BundleR => b.getWidth\n case b: AXI4BundleB => b.getWidth\n }}.max\n }\n val ingressNodes = (edgeInNodes.map(u => Seq.fill(3) (u)) ++ edgeOutNodes.map(u => Seq.fill(2) (u))).flatten\n val egressNodes = (edgeInNodes.map(u => Seq.fill(2) (u)) ++ edgeOutNodes.map(u => Seq.fill(3) (u))).flatten\n val nVirtualNetworks = 5\n val vNetBlocking = (blocker: Int, blockee: Int) => blocker < blockee\n val flows = (0 until edgeInNodes.size).map { i => (0 until edgeOutNodes.size).map { o =>\n Seq(FlowParams(i * 3 + 0 , o * 3 + 0 + edgesIn.size * 2, 4), // AW\n FlowParams(i * 3 + 1 , o * 3 + 1 + edgesIn.size * 2, 3), // W\n FlowParams(i * 3 + 2 , o * 3 + 2 + edgesIn.size * 2, 2), // AR\n FlowParams(o * 2 + 0 + edgesIn.size * 3 , i * 2 + 0 , 1), // R\n FlowParams(o * 2 + 1 + edgesIn.size * 3 , i * 2 + 1 , 0) // B\n )\n }}.flatten.flatten\n\n def genIO()(implicit p: Parameters): Data = new AXI4InterconnectInterface(edgesIn, edgesOut)\n def interface(terminals: NoCTerminalIO,\n ingressOffset: Int, egressOffset: Int, protocol: Data)(implicit p: Parameters) = {\n val ingresses = terminals.ingress\n val egresses = terminals.egress\n protocol match {\n case protocol: AXI4InterconnectInterface => {\n edgesIn.zipWithIndex.map { case (e,i) =>\n val nif_master = Module(new AXI4MasterToNoC(\n e, edgesOut,\n inputIdRanges(i).start, inputIdRanges(i).size,\n wideBundle,\n (s) => s * 3 + edgesIn.size * 2 + egressOffset,\n minPayloadWidth,\n awQueueDepth\n ))\n nif_master.io.axi4 <> protocol.in(i)\n ingresses(i * 3 + 0).flit <> nif_master.io.flits.aw\n ingresses(i * 3 + 1).flit <> nif_master.io.flits.w\n ingresses(i * 3 + 2).flit <> nif_master.io.flits.ar\n nif_master.io.flits.r <> egresses(i * 2 + 0).flit\n nif_master.io.flits.b <> egresses(i * 2 + 1).flit\n }\n edgesOut.zipWithIndex.map { case (e,i) =>\n val nif_slave = Module(new AXI4SlaveToNoC(\n e, edgesIn,\n wideBundle,\n (s) => s * 2 + egressOffset,\n minPayloadWidth,\n awQueueDepth\n ))\n protocol.out(i) <> nif_slave.io.axi4\n ingresses(i * 2 + 0 + edgesIn.size * 3).flit <> nif_slave.io.flits.r\n ingresses(i * 2 + 1 + edgesIn.size * 3).flit <> nif_slave.io.flits.b\n nif_slave.io.flits.aw <> egresses(i * 3 + 0 + edgesIn.size * 2).flit\n nif_slave.io.flits.w <> egresses(i * 3 + 1 + edgesIn.size * 2).flit\n nif_slave.io.flits.ar <> egresses(i * 3 + 2 + edgesIn.size * 2).flit\n }\n }\n }\n }\n}\n\nclass AXI4NoCNode(implicit valName: ValName) extends AXI4NexusNode(\n masterFn = { seq =>\n seq(0).copy(\n echoFields = BundleField.union(seq.flatMap(_.echoFields)),\n requestFields = BundleField.union(seq.flatMap(_.requestFields)),\n responseKeys = seq.flatMap(_.responseKeys).distinct,\n masters = (AXI4Xbar.mapInputIds(seq) zip seq) flatMap { case (range, port) =>\n port.masters map { master => master.copy(id = master.id.shift(range.start)) }\n }\n )\n },\n slaveFn = { seq =>\n seq(0).copy(\n responseFields = BundleField.union(seq.flatMap(_.responseFields)),\n requestKeys = seq.flatMap(_.requestKeys).distinct,\n minLatency = seq.map(_.minLatency).min,\n slaves = seq.flatMap { port =>\n require (port.beatBytes == seq(0).beatBytes,\n s\"Xbar data widths don't match: ${port.slaves.map(_.name)} has ${port.beatBytes}B vs ${seq(0).slaves.map(_.name)} has ${seq(0).beatBytes}B\")\n port.slaves\n }\n )\n }\n)\n\nabstract class AXI4NoCModuleImp(outer: LazyModule) extends LazyModuleImp(outer) {\n val edgesIn: Seq[AXI4EdgeParameters]\n val edgesOut: Seq[AXI4EdgeParameters]\n val nodeMapping: DiplomaticNetworkNodeMapping\n val nocName: String\n val awQueueDepth: Int\n lazy val inNames = nodeMapping.genUniqueName(edgesIn.map(_.master.masters.map(_.name)))\n lazy val outNames = nodeMapping.genUniqueName(edgesOut.map(_.slave.slaves.map(_.name)))\n lazy val edgeInNodes = nodeMapping.getNodesIn(inNames)\n lazy val edgeOutNodes = nodeMapping.getNodesOut(outNames)\n lazy val protocolParams = AXI4ProtocolParams(\n edgesIn = edgesIn,\n edgesOut = edgesOut,\n edgeInNodes = edgeInNodes.flatten,\n edgeOutNodes = edgeOutNodes.flatten,\n awQueueDepth = awQueueDepth\n )\n\n def printNodeMappings() {\n println(s\"Constellation: AXI4NoC $nocName inwards mapping:\")\n for ((n, i) <- inNames zip edgeInNodes) {\n val node = i.map(_.toString).getOrElse(\"X\")\n println(s\" $node <- $n\")\n }\n\n println(s\"Constellation: AXI4NoC $nocName outwards mapping:\")\n for ((n, i) <- outNames zip edgeOutNodes) {\n val node = i.map(_.toString).getOrElse(\"X\")\n println(s\" $node <- $n\")\n }\n }\n}\n\n// private AXI4 NoC\n// BEGIN: AXI4NoCParams\ncase class AXI4NoCParams(\n nodeMappings: DiplomaticNetworkNodeMapping,\n nocParams: NoCParams,\n awQueueDepth: Int = 2\n)\nclass AXI4NoC(params: AXI4NoCParams, name: String = \"test\")(implicit p: Parameters) extends LazyModule {\n // END: AXI4NoCParams\n val node = new AXI4NoCNode\n lazy val module = new AXI4NoCModuleImp(this) {\n val (io_in, edgesIn) = node.in.unzip\n val (io_out, edgesOut) = node.out.unzip\n val nodeMapping = params.nodeMappings\n val nocName = name\n val awQueueDepth = params.awQueueDepth\n\n printNodeMappings()\n\n val noc = Module(new ProtocolNoC(ProtocolNoCParams(\n params.nocParams.copy(hasCtrl = false, nocName = name),\n Seq(protocolParams)\n )))\n\n noc.io.protocol(0) match {\n case protocol: AXI4InterconnectInterface => {\n (protocol.in zip io_in).foreach { case (l,r) => l <> r }\n (io_out zip protocol.out).foreach { case (l,r) => l <> r }\n }\n }\n }\n}\n", "groundtruth": " val arFIFOMap = WireInit(VecInit(Seq.fill(endId) { true.B }))\n", "crossfile_context": ""}
{"task_id": "constellation", "path": "constellation/src/main/scala/protocol/Protocol.scala", "left_context": "package constellation.protocol\n\nimport chisel3._\nimport chisel3.util._\n\nimport constellation.channel._\nimport constellation.noc._\nimport constellation.router.{RouterCtrlBundle}\n\nimport org.chipsalliance.cde.config._\nimport freechips.rocketchip.diplomacy._\nimport freechips.rocketchip.subsystem._\n\nimport scala.collection.immutable.{ListMap}\n\n// BEGIN: NodeMapping\ncase class DiplomaticNetworkNodeMapping(\n inNodeMapping: ListMap[String, Int] = ListMap[String, Int](),\n outNodeMapping: ListMap[String, Int] = ListMap[String, Int]()\n) {\n // END: NodeMapping\n def genUniqueName(all: Seq[Seq[String]]) = {\n all.zipWithIndex.map { case (strs, i) =>\n val matches = all.take(i).map(_.mkString).count(_ == strs.mkString)\n strs.map(s => s\"${s}[${matches}]\").mkString(\",\") + \"|\"\n }\n }\n def getNode(l: String, nodeMapping: ListMap[String, Int]): Option[Int] = {\n val keys = nodeMapping.keys.toSeq\n val matches = keys.map(k => l.contains(k))\n if (matches.filter(i => i).size == 1) {\n val index = matches.indexWhere(i => i)\n Some(nodeMapping.values.toSeq(index))\n } else {\n None\n }\n }\n def getNodes(ls: Seq[String], mapping: ListMap[String, Int]): Seq[Option[Int]] = {\n ls.map(l => getNode(l, mapping))\n }\n\n def getNodesIn(ls: Seq[String]): Seq[Option[Int]] = getNodes(ls, inNodeMapping)\n", "right_context": "}\n\n// BEGIN: ProtocolParams\ntrait ProtocolParams {\n val minPayloadWidth: Int\n val ingressNodes: Seq[Int]\n val egressNodes: Seq[Int]\n val nVirtualNetworks: Int\n val vNetBlocking: (Int, Int) => Boolean\n val flows: Seq[FlowParams]\n def genIO()(implicit p: Parameters): Data\n def interface(\n terminals: NoCTerminalIO,\n ingressOffset: Int,\n egressOffset: Int,\n protocol: Data)(implicit p: Parameters)\n}\n// END: ProtocolParams\n\n// BEGIN: ProtocolNoC\ncase class ProtocolNoCParams(\n nocParams: NoCParams,\n protocolParams: Seq[ProtocolParams],\n widthDivision: Int = 1,\n inlineNoC: Boolean = false\n)\nclass ProtocolNoC(params: ProtocolNoCParams)(implicit p: Parameters) extends Module {\n val io = IO(new Bundle {\n val ctrl = if (params.nocParams.hasCtrl) Vec(params.nocParams.topology.nNodes, new RouterCtrlBundle) else Nil\n val protocol = MixedVec(params.protocolParams.map { u => u.genIO() })\n })\n // END: ProtocolNoC\n\n if (params.inlineNoC) {\n chisel3.experimental.annotate(this)(Seq(firrtl.passes.InlineAnnotation(toNamed)))\n }\n\n val protocolParams = params.protocolParams\n val minPayloadWidth = protocolParams.map(_.minPayloadWidth).max\n val nocPayloadWidth = math.ceil(minPayloadWidth.toDouble / params.widthDivision).toInt\n val terminalPayloadWidth = nocPayloadWidth * params.widthDivision\n val ingressOffsets = protocolParams.map(_.ingressNodes.size).scanLeft(0)(_+_)\n val egressOffsets = protocolParams.map(_.egressNodes.size).scanLeft(0)(_+_)\n val vNetOffsets = protocolParams.map(_.nVirtualNetworks).scanLeft(0)(_+_)\n\n val nocParams = params.nocParams.copy(\n ingresses = protocolParams.map(_.ingressNodes).flatten.map(i =>\n UserIngressParams(i, payloadBits=terminalPayloadWidth)),\n egresses = protocolParams.map(_.egressNodes).flatten.map(i =>\n UserEgressParams(i, payloadBits=terminalPayloadWidth)),\n routerParams = (i) => params.nocParams.routerParams(i).copy(payloadBits=nocPayloadWidth),\n vNetBlocking = (blocker, blockee) => {\n def protocolId(i: Int) = vNetOffsets.drop(1).indexWhere(_ > i)\n if (protocolId(blocker) == protocolId(blockee)) {\n protocolParams(protocolId(blocker)).vNetBlocking(\n blocker - vNetOffsets(protocolId(blocker)),\n blockee - vNetOffsets(protocolId(blockee))\n )\n } else {\n true\n }\n },\n flows = protocolParams.zipWithIndex.map { case (u,i) =>\n u.flows.map(f => f.copy(\n ingressId = f.ingressId + ingressOffsets(i),\n egressId = f.egressId + egressOffsets(i),\n vNetId = f.vNetId + vNetOffsets(i)\n ))\n }.flatten\n )\n val noc = Module(LazyModule(new NoC(nocParams)).module)\n noc.io.router_clocks.foreach(_.clock := clock)\n noc.io.router_clocks.foreach(_.reset := reset)\n (noc.io.router_ctrl zip io.ctrl).foreach { case (l, r) => l <> r }\n (protocolParams zip io.protocol).zipWithIndex.foreach { case ((u, io), x) =>\n val terminals = Wire(new NoCTerminalIO(\n noc.io.ingressParams.drop(ingressOffsets(x)).take(u.ingressNodes.size),\n noc.io.egressParams .drop(egressOffsets(x)) .take(u.egressNodes.size)\n ))\n (terminals.ingress zip noc.io.ingress.drop(ingressOffsets(x))).map { case (l,r) => l <> r }\n (terminals.egress zip noc.io.egress.drop (egressOffsets(x))).map { case (l,r) => l <> r }\n u.interface(\n terminals,\n ingressOffsets(x),\n egressOffsets(x),\n io)\n }\n}\n", "groundtruth": " def getNodesOut(ls: Seq[String]): Seq[Option[Int]] = getNodes(ls, outNodeMapping)\n", "crossfile_context": ""}
{"task_id": "constellation", "path": "constellation/src/main/scala/router/OutputUnit.scala", "left_context": "package constellation.router\n\nimport chisel3._\nimport chisel3.util._\n\nimport org.chipsalliance.cde.config.{Field, Parameters}\nimport constellation.channel._\nimport constellation.routing.{FlowRoutingBundle}\nimport constellation.noc.{HasNoCParams}\n\nclass OutputCreditAlloc extends Bundle {\n val alloc = Bool()\n val tail = Bool()\n}\n\nclass OutputChannelStatus(implicit val p: Parameters) extends Bundle with HasNoCParams {\n val occupied = Bool()\n def available = !occupied\n val flow = new FlowRoutingBundle\n}\n\nclass OutputChannelAlloc(implicit val p: Parameters) extends Bundle with HasNoCParams {\n val alloc = Bool()\n val flow = new FlowRoutingBundle\n}\n\nclass AbstractOutputUnitIO(\n val inParams: Seq[ChannelParams],\n val ingressParams: Seq[IngressChannelParams],\n val cParam: BaseChannelParams\n)(implicit val p: Parameters) extends Bundle with HasRouterInputParams {\n val nodeId = cParam.srcId\n val nVirtualChannels = cParam.nVirtualChannels\n val in = Flipped(Vec(cParam.srcSpeedup, Valid(new Flit(cParam.payloadBits))))\n val credit_available = Output(Vec(nVirtualChannels, Bool()))\n val channel_status = Output(Vec(nVirtualChannels, new OutputChannelStatus))\n val allocs = Input(Vec(nVirtualChannels, new OutputChannelAlloc))\n val credit_alloc = Input(Vec(nVirtualChannels, new OutputCreditAlloc))\n}\n\n\nabstract class AbstractOutputUnit(\n val inParams: Seq[ChannelParams],\n val ingressParams: Seq[IngressChannelParams],\n val cParam: BaseChannelParams\n)(implicit val p: Parameters) extends Module with HasRouterInputParams with HasNoCParams {\n val nodeId = cParam.srcId\n\n def io: AbstractOutputUnitIO\n}\n\nclass OutputUnit(inParams: Seq[ChannelParams], ingressParams: Seq[IngressChannelParams], cParam: ChannelParams)\n (implicit p: Parameters) extends AbstractOutputUnit(inParams, ingressParams, cParam)(p) {\n\n class OutputUnitIO extends AbstractOutputUnitIO(inParams, ingressParams, cParam) {\n val out = new Channel(cParam.asInstanceOf[ChannelParams])\n }\n val io = IO(new OutputUnitIO)\n\n class OutputState(val bufferSize: Int) extends Bundle {\n val occupied = Bool()\n val c = UInt(log2Up(1+bufferSize).W)\n val flow = new FlowRoutingBundle\n }\n\n", "right_context": " (states zip io.channel_status).map { case (s,a) =>\n a.occupied := s.occupied\n a.flow := s.flow\n }\n io.out.flit := io.in\n\n states.zipWithIndex.map { case (s,i) => if (cParam.virtualChannelParams(i).traversable) {\n when (io.out.vc_free(i)) {\n assert(s.occupied)\n s.occupied := false.B\n }\n } }\n\n\n (states zip io.allocs).zipWithIndex.map { case ((s,a),i) => if (cParam.virtualChannelParams(i).traversable) {\n when (a.alloc) {\n s.occupied := true.B\n s.flow := a.flow\n }\n } }\n\n (io.credit_available zip states).zipWithIndex.map { case ((c,s),i) =>\n c := s.c =/= 0.U //|| (io.out.credit_return.valid && io.out.credit_return.bits === i.U)\n }\n\n states.zipWithIndex.map { case (s,i) =>\n val free = io.out.credit_return(i)\n val alloc = io.credit_alloc(i).alloc\n if (cParam.virtualChannelParams(i).traversable) {\n s.c := s.c +& free - alloc\n }\n }\n\n\n\n when (reset.asBool) {\n states.foreach(_.occupied := false.B)\n states.foreach(s => s.c := s.bufferSize.U)\n }\n}\n", "groundtruth": " val states = Reg(MixedVec(cParam.virtualChannelParams.map { u => new OutputState(u.bufferSize) }))\n", "crossfile_context": ""}
{"task_id": "constellation", "path": "constellation/src/main/scala/router/vcalloc/SingleVCAllocator.scala", "left_context": "package constellation.router\n\nimport chisel3._\nimport chisel3.util._\nimport chisel3.util.random.{LFSR}\n\nimport org.chipsalliance.cde.config.{Field, Parameters}\nimport freechips.rocketchip.util._\n\nimport constellation.channel._\nimport constellation.routing.{ChannelRoutingInfo, FlowRoutingBundle}\n\n// Allocates 1 VC per cycle\nabstract class SingleVCAllocator(vP: VCAllocatorParams)(implicit p: Parameters) extends VCAllocator(vP)(p) {\n // get single input\n val mask = RegInit(0.U(allInParams.size.W))\n val in_arb_reqs = Wire(Vec(allInParams.size, MixedVec(allOutParams.map { u => Vec(u.nVirtualChannels, Bool()) })))\n val in_arb_vals = Wire(Vec(allInParams.size, Bool()))\n val in_arb_filter = PriorityEncoderOH(Cat(in_arb_vals.asUInt, in_arb_vals.asUInt & ~mask))\n val in_arb_sel = (in_arb_filter(allInParams.size-1,0) | (in_arb_filter >> allInParams.size))\n when (in_arb_vals.orR) {\n mask := Mux1H(in_arb_sel, (0 until allInParams.size).map { w => ~(0.U((w+1).W)) })\n }\n\n for (i <- 0 until allInParams.size) {\n (0 until allOutParams.size).map { m =>\n (0 until allOutParams(m).nVirtualChannels).map { n =>\n in_arb_reqs(i)(m)(n) := io.req(i).bits.vc_sel(m)(n) && !io.channel_status(m)(n).occupied\n }\n }\n\n in_arb_vals(i) := io.req(i).valid && in_arb_reqs(i).map(_.orR).toSeq.orR\n }\n\n // Input arbitration\n io.req.foreach(_.ready := false.B)\n", "right_context": " val in_flow = Mux1H(in_arb_sel, io.req.map(_.bits.flow).toSeq)\n val in_vc = Mux1H(in_arb_sel, io.req.map(_.bits.in_vc).toSeq)\n val in_vc_sel = Mux1H(in_arb_sel, in_arb_reqs)\n in_alloc := Mux(in_arb_vals.orR,\n inputAllocPolicy(in_flow, in_vc_sel, OHToUInt(in_arb_sel), in_vc, io.req.map(_.fire).toSeq.orR),\n 0.U.asTypeOf(in_alloc))\n\n // send allocation to inputunits\n for (i <- 0 until allInParams.size) {\n io.req(i).ready := in_arb_sel(i)\n for (m <- 0 until allOutParams.size) {\n (0 until allOutParams(m).nVirtualChannels).map { n =>\n io.resp(i).vc_sel(m)(n) := in_alloc(m)(n)\n }\n }\n assert(PopCount(io.resp(i).vc_sel.asUInt) <= 1.U)\n }\n\n // send allocation to output units\n for (i <- 0 until allOutParams.size) {\n (0 until allOutParams(i).nVirtualChannels).map { j =>\n io.out_allocs(i)(j).alloc := in_alloc(i)(j)\n io.out_allocs(i)(j).flow := in_flow\n }\n }\n}\n", "groundtruth": " val in_alloc = Wire(MixedVec(allOutParams.map { u => Vec(u.nVirtualChannels, Bool()) }))\n", "crossfile_context": ""}
{"task_id": "constellation", "path": "constellation/src/main/scala/routing/RoutingRelations.scala", "left_context": "package constellation.routing\n\nimport scala.math.{min, max, pow}\nimport scala.collection.mutable.HashMap\nimport org.chipsalliance.cde.config.{Parameters}\nimport scala.collection.immutable.ListMap\nimport constellation.topology.{PhysicalTopology, Mesh2DLikePhysicalTopology, HierarchicalTopology, CustomTopology}\n\nimport scala.collection.mutable\n\n/** Routing and channel allocation policy\n *\n * @param f function that takes in source channel, next channel, and packet routing info.\n * Returns True if packet can acquire/proceed to this next channel, False if not. An example\n * is the bidirectionalLine method; see its docstring.\n * @param isEscape function that takes in ChannelRoutingInfo and a virtual network ID. Returns True if the\n * channel represented by ChannelRoutingInfo is an escape channel and False if it is not.\n * By default, we ignore the escape-channel-based deadlock-free properties, and just check\n * for deadlock-freedom by verifying lack of a cyclic dependency.\n */\n// BEGIN: RoutingRelation\nabstract class RoutingRelation(topo: PhysicalTopology) {\n // Child classes must implement these\n def rel (srcC: ChannelRoutingInfo,\n nxtC: ChannelRoutingInfo,\n flow: FlowRoutingInfo): Boolean\n\n def isEscape (c: ChannelRoutingInfo,\n vNetId: Int): Boolean = true\n\n def getNPrios (src: ChannelRoutingInfo): Int = 1\n\n def getPrio (srcC: ChannelRoutingInfo,\n nxtC: ChannelRoutingInfo,\n flow: FlowRoutingInfo): Int = 0\n\n // END: RoutingRelation\n\n private val memoize = new HashMap[(ChannelRoutingInfo, ChannelRoutingInfo, FlowRoutingInfo), Boolean]()\n def apply(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo): Boolean = {\n require(srcC.dst == nxtC.src)\n val key = (srcC, nxtC, flow)\n memoize.getOrElseUpdate(key, rel(srcC, nxtC, flow))\n }\n}\n// END: RoutingRelation\n\n/** Given a deadlock-prone routing relation and a routing relation representing the network's escape\n * channels, returns a routing relation that adds the escape channels to the deadlock-prone relation.\n *\n * @param escapeRouter routing relation representing the network's escape channels\n * @param normalrouter deadlock-prone routing relation\n * @param nEscapeChannels number of escape channels\n */\nobject EscapeChannelRouting {\n def apply(\n escapeRouter: PhysicalTopology => RoutingRelation,\n normalRouter: PhysicalTopology => RoutingRelation,\n nEscapeChannels: Int = 1) = (topo: PhysicalTopology) => new RoutingRelation(topo) {\n val escape = escapeRouter(topo)\n val normal = normalRouter(topo)\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n if (srcC.src == -1) {\n if (nxtC.vc >= nEscapeChannels) { // if ingress and jumping into normal channel, use normal relation\n normal(srcC, nxtC.copy(vc=nxtC.vc-nEscapeChannels, n_vc=nxtC.n_vc-nEscapeChannels), flow)\n } else { // else use ingress and jump into escape channel\n escape(srcC, nxtC.copy(n_vc=nEscapeChannels), flow)\n }\n } else if (nxtC.vc < nEscapeChannels) {\n escape(srcC, nxtC.copy(n_vc=nEscapeChannels), flow)\n } else if (srcC.vc >= nEscapeChannels && nxtC.vc >= nEscapeChannels) {\n normal(\n srcC.copy(vc=srcC.vc-nEscapeChannels, n_vc=srcC.n_vc-nEscapeChannels),\n nxtC.copy(vc=nxtC.vc-nEscapeChannels, n_vc=nxtC.n_vc-nEscapeChannels),\n flow)\n } else {\n false\n }\n }\n override def isEscape(c: ChannelRoutingInfo, v: Int) = {\n c.isIngress || c.isEgress || c.vc < nEscapeChannels\n }\n override def getNPrios(c: ChannelRoutingInfo): Int = {\n escape.getNPrios(c) + normal.getNPrios(c)\n }\n override def getPrio(src: ChannelRoutingInfo, a: ChannelRoutingInfo, flow: FlowRoutingInfo): Int = {\n val aEscape = isEscape(a, flow.vNetId)\n val nSrc = if (src.isIngress) {\n src\n } else if (isEscape(src, flow.vNetId)) {\n src.copy(vc=src.vc, n_vc=nEscapeChannels)\n } else {\n src.copy(vc=src.vc-nEscapeChannels, n_vc=src.n_vc-nEscapeChannels)\n }\n if (aEscape) {\n escape.getPrio(nSrc, a.copy(n_vc=nEscapeChannels), flow) + normal.getNPrios(src)\n } else {\n normal.getPrio(nSrc, a.copy(vc=a.vc-nEscapeChannels, n_vc=a.n_vc-nEscapeChannels), flow)\n }\n }\n }\n}\n\n/**\n * Allows all routing. Probably not very useful\n */\nobject AllLegalRouting {\n def apply() = (topo: PhysicalTopology) => new RoutingRelation(topo) {\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = true\n }\n}\n\nobject UnidirectionalLineRouting {\n def apply() = (topo: PhysicalTopology) => new RoutingRelation(topo) {\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n nxtC.dst <= flow.egressNode\n }\n override def getNPrios(src: ChannelRoutingInfo) = 4\n override def getPrio(src: ChannelRoutingInfo, a: ChannelRoutingInfo, flow: FlowRoutingInfo): Int = {\n max(src.dst - a.dst + getNPrios(src), 0)\n }\n }\n}\n\nobject BidirectionalLineRouting {\n def apply() = (topo: PhysicalTopology) => new RoutingRelation(topo) {\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n if (nxtC.src < nxtC.dst) flow.egressNode >= nxtC.dst else flow.egressNode <= nxtC.dst\n }\n }\n}\n\nobject UnidirectionalTorus1DDatelineRouting {\n def apply() = (topo: PhysicalTopology) => new RoutingRelation(topo) {\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n if (srcC.src == -1) {\n nxtC.vc != 0\n } else if (srcC.vc == 0) {\n nxtC.vc == 0\n } else if (nxtC.src == topo.nNodes - 1) {\n nxtC.vc < srcC.vc\n } else {\n nxtC.vc <= srcC.vc && (nxtC.vc != 0 || flow.egressNode > nxtC.src)\n }\n }\n override def getNPrios(src: ChannelRoutingInfo) = 2\n override def getPrio(src: ChannelRoutingInfo, nxt: ChannelRoutingInfo, flow: FlowRoutingInfo): Int = {\n if (nxt.vc == 0 || nxt.vc == 1) 1 else 0\n }\n override def isEscape(c: ChannelRoutingInfo, v: Int) = {\n c.isIngress || c.isEgress || c.vc < 2\n }\n }\n}\n\nobject BidirectionalTorus1DDatelineRouting {\n def apply() = (topo: PhysicalTopology) => new RoutingRelation(topo) {\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n if (srcC.src == -1) {\n nxtC.vc != 0\n } else if (srcC.vc == 0) {\n nxtC.vc == 0\n } else if ((nxtC.dst + topo.nNodes - nxtC.src) % topo.nNodes == 1) {\n if (nxtC.src == topo.nNodes - 1) {\n nxtC.vc < srcC.vc\n } else {\n nxtC.vc <= srcC.vc && (nxtC.vc != 0 || flow.egressNode > nxtC.src)\n }\n } else if ((nxtC.src + topo.nNodes - nxtC.dst) % topo.nNodes == 1) {\n if (nxtC.src == 0) {\n nxtC.vc < srcC.vc\n } else {\n nxtC.vc <= srcC.vc && (nxtC.vc != 0 || flow.egressNode < nxtC.src)\n }\n } else {\n false\n }\n }\n }\n}\n\nobject BidirectionalTorus1DShortestRouting {\n def apply() = (topo: PhysicalTopology) => new RoutingRelation(topo) {\n val base = BidirectionalTorus1DDatelineRouting()(topo)\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n val cwDist = (flow.egressNode + topo.nNodes - nxtC.src) % topo.nNodes\n val ccwDist = (nxtC.src + topo.nNodes - flow.egressNode) % topo.nNodes\n val distSel = if (cwDist < ccwDist) {\n (nxtC.dst + topo.nNodes - nxtC.src) % topo.nNodes == 1\n } else if (cwDist > ccwDist) {\n (nxtC.src + topo.nNodes - nxtC.dst) % topo.nNodes == 1\n } else {\n true\n }\n distSel && base(srcC, nxtC, flow)\n }\n }\n}\n\nobject BidirectionalTorus1DRandomRouting {\n def apply() = (topo: PhysicalTopology) => new RoutingRelation(topo) {\n val base = BidirectionalTorus1DDatelineRouting()(topo)\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n val sel = if (srcC.src == -1) {\n true\n } else if ((nxtC.src + topo.nNodes - srcC.src) % topo.nNodes == 1) {\n (nxtC.dst + topo.nNodes - nxtC.src) % topo.nNodes == 1\n } else {\n (nxtC.src + topo.nNodes - nxtC.dst) % topo.nNodes == 1\n }\n sel && base(srcC, nxtC, flow)\n }\n }\n}\n\nobject ButterflyRouting {\n def apply() = (topo: PhysicalTopology) => topo match {\n case topo: constellation.topology.Butterfly => new RoutingRelation(topo) {\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n val (nxtX, nxtY) = (nxtC.dst / topo.height, nxtC.dst % topo.height)\n val (nodeX, nodeY) = (nxtC.src / topo.height, nxtC.src % topo.height)\n val (dstX, dstY) = (flow.egressNode / topo.height, flow.egressNode % topo.height)\n if (dstX <= nodeX) {\n false\n } else if (nodeX == topo.nFly-1) {\n true\n } else {\n val dsts = (nxtX until topo.nFly-1).foldRight((0 until topo.height).map { i => Seq(i) }) {\n case (i,l) => (0 until topo.height).map { s => topo.channels(i).filter(_._1 == s).map { case (_,d) =>\n l(d)\n }.flatten }\n }\n dsts(nxtY).contains(flow.egressNode % topo.height)\n }\n }\n }\n }\n}\n\nobject BidirectionalTreeRouting {\n def apply() = (topo: PhysicalTopology) => topo match {\n case topo: constellation.topology.BidirectionalTree => new RoutingRelation(topo) {\n /** Returns a boolean indicating whether src is an ancestor node of dst */\n def isAncestor(src: Int, dst: Int): Boolean = {\n if (src == dst) {\n true\n } else if (src > dst) {\n false\n } else {\n ((topo.dAry * src + 1) to (topo.dAry * src + topo.dAry)).foldLeft(false)((sofar, nextChild) => sofar || isAncestor(nextChild, dst))\n }\n }\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n if (isAncestor(nxtC.src, flow.egressNode)) {\n isAncestor(nxtC.dst, flow.egressNode) && (nxtC.dst >= nxtC.src)\n } else {\n isAncestor(nxtC.dst, nxtC.src)\n }\n }\n }\n }\n}\n\nobject Mesh2DDimensionOrderedRouting {\n def apply(firstDim: Int = 0) = (topo: PhysicalTopology) => topo match {\n case topo: Mesh2DLikePhysicalTopology => new RoutingRelation(topo) {\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n val (nxtX, nxtY) = (nxtC.dst % topo.nX , nxtC.dst / topo.nX)\n val (nodeX, nodeY) = (nxtC.src % topo.nX , nxtC.src / topo.nX)\n val (dstX, dstY) = (flow.egressNode % topo.nX , flow.egressNode / topo.nX)\n\n if (firstDim == 0) {\n if (dstX != nodeX) {\n (if (nodeX < nxtX) dstX >= nxtX else dstX <= nxtX) && nxtY == nodeY\n } else {\n (if (nodeY < nxtY) dstY >= nxtY else dstY <= nxtY) && nxtX == nodeX\n }\n } else {\n if (dstY != nodeY) {\n (if (nodeY < nxtY) dstY >= nxtY else dstY <= nxtY) && nxtX == nodeX\n } else {\n (if (nodeX < nxtX) dstX >= nxtX else dstX <= nxtX) && nxtY == nodeY\n }\n }\n }\n }\n }\n}\n\n// WARNING: Not deadlock free\nobject Mesh2DMinimalRouting {\n def apply() = (topo: PhysicalTopology) => topo match {\n case topo: Mesh2DLikePhysicalTopology => new RoutingRelation(topo) {\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n val (nxtX, nxtY) = (nxtC.dst % topo.nX , nxtC.dst / topo.nX)\n val (nodeX, nodeY) = (nxtC.src % topo.nX , nxtC.src / topo.nX)\n val (dstX, dstY) = (flow.egressNode % topo.nX , flow.egressNode / topo.nX)\n\n val xR = (if (nodeX < nxtX) dstX >= nxtX else if (nodeX > nxtX) dstX <= nxtX else nodeX == nxtX)\n val yR = (if (nodeY < nxtY) dstY >= nxtY else if (nodeY > nxtY) dstY <= nxtY else nodeY == nxtY)\n xR && yR\n }\n }\n }\n}\n\nobject Mesh2DWestFirstRouting {\n def apply() = (topo: PhysicalTopology) => topo match {\n case topo: Mesh2DLikePhysicalTopology => new RoutingRelation(topo) {\n val base = Mesh2DMinimalRouting()(topo)\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n val (nxtX, nxtY) = (nxtC.dst % topo.nX , nxtC.dst / topo.nX)\n val (nodeX, nodeY) = (nxtC.src % topo.nX , nxtC.src / topo.nX)\n val (dstX, dstY) = (flow.egressNode % topo.nX , flow.egressNode / topo.nX)\n\n if (dstX < nodeX) {\n nxtX == nodeX - 1\n } else {\n base(srcC, nxtC, flow)\n }\n }\n }\n }\n}\n\nobject Mesh2DNorthLastRouting {\n def apply() = (topo: PhysicalTopology) => topo match {\n case topo: Mesh2DLikePhysicalTopology => new RoutingRelation(topo) {\n val base = Mesh2DMinimalRouting()(topo)\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n val (nxtX, nxtY) = (nxtC.dst % topo.nX , nxtC.dst / topo.nX)\n val (nodeX, nodeY) = (nxtC.src % topo.nX , nxtC.src / topo.nX)\n val (dstX, dstY) = (flow.egressNode % topo.nX , flow.egressNode / topo.nX)\n\n val minimal = base(srcC, nxtC, flow)\n if (dstY > nodeY && dstX != nodeX) {\n minimal && nxtY != nodeY + 1\n } else if (dstY > nodeY) {\n nxtY == nodeY + 1\n } else {\n minimal\n }\n }\n }\n }\n}\n\nobject Mesh2DEscapeRouting {\n def apply() = (topo: PhysicalTopology) => topo match {\n case topo: Mesh2DLikePhysicalTopology => EscapeChannelRouting(\n escapeRouter=Mesh2DDimensionOrderedRouting(),\n normalRouter=Mesh2DMinimalRouting())(topo)\n }\n}\n\nobject UnidirectionalTorus2DDatelineRouting {\n def apply() = (topo: PhysicalTopology) => topo match {\n case topo: Mesh2DLikePhysicalTopology => new RoutingRelation(topo) {\n val baseX = UnidirectionalTorus1DDatelineRouting()(constellation.topology.UnidirectionalTorus1D(topo.nX))\n val baseY = UnidirectionalTorus1DDatelineRouting()(constellation.topology.UnidirectionalTorus1D(topo.nY))\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n\n val (nxtX, nxtY) = (nxtC.dst % topo.nX , nxtC.dst / topo.nX)\n val (nodeX, nodeY) = (nxtC.src % topo.nX , nxtC.src / topo.nX)\n val (dstX, dstY) = (flow.egressNode % topo.nX , flow.egressNode / topo.nX)\n val (srcX, srcY) = (srcC.src % topo.nX , srcC.src / topo.nX)\n\n val turn = nxtX != srcX && nxtY != srcY\n if (srcC.src == -1 || turn) {\n nxtC.vc != 0\n } else if (srcX == nxtX) {\n baseY(\n srcC.copy(src=srcY, dst=nodeY),\n nxtC.copy(src=nodeY, dst=nxtY),\n flow.copy(egressNode=dstY)\n )\n } else if (srcY == nxtY) {\n baseX(\n srcC.copy(src=srcX, dst=nodeX),\n nxtC.copy(src=nodeX, dst=nxtX),\n flow.copy(egressNode=dstX)\n )\n } else {\n false\n }\n }\n override def isEscape(c: ChannelRoutingInfo, v: Int) = {\n c.isIngress || c.isEgress || c.vc < 2\n }\n }\n }\n}\n\nobject BidirectionalTorus2DDatelineRouting {\n def apply() = (topo: PhysicalTopology) => topo match {\n case topo: Mesh2DLikePhysicalTopology => new RoutingRelation(topo) {\n val baseX = UnidirectionalTorus1DDatelineRouting()(constellation.topology.UnidirectionalTorus1D(topo.nX))\n val baseY = UnidirectionalTorus1DDatelineRouting()(constellation.topology.UnidirectionalTorus1D(topo.nY))\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n val (nxtX, nxtY) = (nxtC.dst % topo.nX , nxtC.dst / topo.nX)\n val (nodeX, nodeY) = (nxtC.src % topo.nX , nxtC.src / topo.nX)\n val (dstX, dstY) = (flow.egressNode % topo.nX , flow.egressNode / topo.nX)\n val (srcX, srcY) = (srcC.src % topo.nX , srcC.src / topo.nX)\n\n if (srcC.src == -1) {\n nxtC.vc != 0\n } else if (nodeX == nxtX) {\n baseY(\n srcC.copy(src=srcY, dst=nodeY),\n nxtC.copy(src=nodeY, dst=nxtY),\n flow.copy(egressNode=dstY)\n )\n } else if (nodeY == nxtY) {\n baseX(\n srcC.copy(src=srcX, dst=nodeX),\n nxtC.copy(src=nodeX, dst=nxtX),\n flow.copy(egressNode=dstX)\n )\n } else {\n false\n }\n }\n }\n }\n}\n\nobject DimensionOrderedUnidirectionalTorus2DDatelineRouting {\n def apply() = (topo: PhysicalTopology) => topo match {\n case topo: Mesh2DLikePhysicalTopology => new RoutingRelation(topo) {\n val base = UnidirectionalTorus2DDatelineRouting()(topo)\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n val (nxtX, nxtY) = (nxtC.dst % topo.nX , nxtC.dst / topo.nX)\n val (nodeX, nodeY) = (nxtC.src % topo.nX , nxtC.src / topo.nX)\n val (dstX, dstY) = (flow.egressNode % topo.nX , flow.egressNode / topo.nX)\n val (srcX, srcY) = (srcC.src % topo.nX , srcC.src / topo.nX)\n\n def sel = if (dstX != nodeX) {\n nxtY == nodeY\n } else {\n nxtX == nodeX\n }\n base(srcC, nxtC, flow) && sel\n }\n }\n }\n}\n\nobject DimensionOrderedBidirectionalTorus2DDatelineRouting {\n def apply() = (topo: PhysicalTopology) => topo match {\n case topo: Mesh2DLikePhysicalTopology => new RoutingRelation(topo) {\n val baseX = BidirectionalTorus1DShortestRouting()(constellation.topology.BidirectionalTorus1D(topo.nX))\n val baseY = BidirectionalTorus1DShortestRouting()(constellation.topology.BidirectionalTorus1D(topo.nY))\n val base = BidirectionalTorus2DDatelineRouting()(topo)\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n\n val (nxtX, nxtY) = (nxtC.dst % topo.nX , nxtC.dst / topo.nX)\n val (nodeX, nodeY) = (nxtC.src % topo.nX , nxtC.src / topo.nX)\n val (dstX, dstY) = (flow.egressNode % topo.nX , flow.egressNode / topo.nX)\n val (srcX, srcY) = (srcC.src % topo.nX , srcC.src / topo.nX)\n\n val xdir = baseX(\n srcC.copy(src=(if (srcC.src == -1) -1 else srcX), dst=nodeX),\n nxtC.copy(src=nodeX, dst=nxtX),\n flow.copy(egressNode=dstX)\n ) && nxtX != nodeX\n val ydir = baseY(\n srcC.copy(src=(if (srcC.src == -1) -1 else srcY), dst=nodeY),\n nxtC.copy(src=nodeY, dst=nxtY),\n flow.copy(egressNode=dstY)\n ) && nxtY != nodeY\n\n val sel = if (dstX != nodeX) xdir else ydir\n\n sel && base(srcC, nxtC, flow)\n }\n }\n }\n}\n\n\nobject TerminalRouterRouting {\n def apply(baseRouting: PhysicalTopology => RoutingRelation) = (topo: PhysicalTopology) => topo match {\n case topo: constellation.topology.TerminalRouter => new RoutingRelation(topo) {\n val base = baseRouting(topo.base)\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n if (srcC.isIngress && topo.isBase(nxtC.dst)) {\n true\n } else if (nxtC.dst == flow.egressNode) {\n true\n } else if (topo.isBase(nxtC.src) &&\n topo.isBase(nxtC.dst) &&\n nxtC.src % topo.base.nNodes != flow.egressNode % topo.base.nNodes) {\n if (topo.isTerminal(srcC.src)) {\n base(\n srcC.copy(src=(-1), dst=srcC.dst % topo.base.nNodes, vc=0, n_vc=1),\n nxtC.copy(src=nxtC.src % topo.base.nNodes, dst=nxtC.dst % topo.base.nNodes),\n flow.copy(egressNode=flow.egressNode % topo.base.nNodes))\n } else {\n base(\n srcC.copy(src=srcC.src % topo.base.nNodes, dst=srcC.dst % topo.base.nNodes),\n nxtC.copy(src=nxtC.src % topo.base.nNodes, dst=nxtC.dst % topo.base.nNodes),\n flow.copy(egressNode=flow.egressNode % topo.base.nNodes))\n }\n } else {\n false\n }\n }\n override def getNPrios(c: ChannelRoutingInfo): Int = {\n if (topo.isBase(c.dst) && topo.isBase(c.src)){\n base.getNPrios(c.copy(src=c.src % topo.base.nNodes, dst=c.dst % topo.base.nNodes))\n } else {\n 1\n }\n }\n override def getPrio(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo): Int = {\n if (topo.isBase(srcC.dst) && topo.isBase(nxtC.dst)) {\n if (topo.isTerminal(srcC.src)) {\n base.getPrio(\n srcC.copy(src=(-1) , dst=srcC.dst % topo.base.nNodes, vc=0, n_vc=1),\n nxtC.copy(src=nxtC.src % topo.base.nNodes, dst=nxtC.dst % topo.base.nNodes),\n flow.copy(egressNode=flow.egressNode % topo.base.nNodes))\n } else {\n base.getPrio(\n srcC.copy(src=srcC.src % topo.base.nNodes, dst=srcC.dst % topo.base.nNodes),\n nxtC.copy(src=nxtC.src % topo.base.nNodes, dst=nxtC.dst % topo.base.nNodes),\n flow.copy(egressNode=flow.egressNode % topo.base.nNodes))\n }\n } else {\n 0\n }\n }\n\n override def isEscape(c: ChannelRoutingInfo, v: Int) = {\n !topo.isBase(c.src) || !topo.isBase(c.dst) || base.isEscape(\n c.copy(src=c.src % topo.base.nNodes, dst=c.dst % topo.base.nNodes), v)\n }\n }\n }\n}\n\n\n// The below tables implement support for virtual subnetworks in a variety of ways\n// NOTE: The topology must have sufficient virtual channels for these to work correctly\n// TODO: Write assertions to check this\n\n/** Produces a system with support for n virtual subnetworks. The output routing relation ensures that\n * the virtual subnetworks do not block each other. This is accomplished by allocating a portion of the\n * virtual channels to each subnetwork; all physical resources are shared between virtual subnetworks\n * but virtual channels and buffers are not shared.\n */\nobject NonblockingVirtualSubnetworksRouting {\n def apply(f: PhysicalTopology => RoutingRelation, n: Int, nDedicatedChannels: Int) = (topo: PhysicalTopology) => new RoutingRelation(topo) {\n def trueVIdToVirtualVId(vId: Int) = if (vId < n * nDedicatedChannels) {\n vId % nDedicatedChannels\n } else {\n nDedicatedChannels + vId - n * nDedicatedChannels\n }\n def lower(c: ChannelRoutingInfo) = c.copy(\n vc = trueVIdToVirtualVId(c.vc),\n n_vc = if (c.isIngress) 1 else c.n_vc - n * nDedicatedChannels + nDedicatedChannels\n )\n val base = f(topo)\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n val able = (nxtC.vc >= n * nDedicatedChannels) || ((nxtC.vc / nDedicatedChannels) == flow.vNetId)\n able && base(lower(srcC), lower(nxtC), flow.copy(vNetId=0))\n }\n override def isEscape(c: ChannelRoutingInfo, v: Int) = {\n base.isEscape(lower(c), 0)\n }\n }\n}\n\nobject BlockingVirtualSubnetworksRouting {\n def apply(f: PhysicalTopology => RoutingRelation, n: Int, nDedicated: Int = 1) = (topo: PhysicalTopology) => new RoutingRelation(topo) {\n val base = f(topo)\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n val lNxtV = nxtC.vc - flow.vNetId * nDedicated\n val lSrcV = srcC.vc - flow.vNetId * nDedicated\n val r = if (srcC.isIngress && lNxtV >= 0) {\n base(srcC,\n nxtC.copy(n_vc = nxtC.n_vc - flow.vNetId * nDedicated, vc = lNxtV),\n flow.copy(vNetId=0)\n )\n } else if (lNxtV < 0 || lSrcV < 0) {\n false\n } else {\n base(srcC.copy(n_vc = srcC.n_vc - flow.vNetId * nDedicated, vc = lSrcV),\n nxtC.copy(n_vc = nxtC.n_vc - flow.vNetId * nDedicated, vc = lNxtV),\n flow.copy(vNetId=0)\n )\n }\n r\n }\n override def isEscape(c: ChannelRoutingInfo, v: Int) = {\n c.vc >= v * nDedicated && base.isEscape(c.copy(vc=c.vc - v * nDedicated, n_vc=c.n_vc - v * nDedicated), 0)\n }\n }\n}\n\n\nobject HierarchicalRouting {\n def apply(\n baseRouting: PhysicalTopology => RoutingRelation,\n childRouting: Seq[PhysicalTopology => RoutingRelation]\n ) = (topo: PhysicalTopology) => topo match {\n case topo: HierarchicalTopology => new RoutingRelation(topo) {\n val base = baseRouting(topo.base)\n val children = (childRouting zip topo.children).map { case (l,r) => l(r.topo) }\n def copyChannel(c: ChannelRoutingInfo, o: Int) = {\n val nSrc = if (c.src < topo.base.nNodes) -1 else c.src - o\n val nDst = if (c.dst == -1) -1 else c.dst - o\n assert(nSrc >= -1 && nDst >= -1, s\"$c $o\")\n c.copy(src=nSrc, dst=nDst)\n }\n\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n val thisBase = topo.isBase(srcC.dst)\n val flowBase = topo.isBase(flow.egressNode)\n val nextBase = topo.isBase(nxtC.dst)\n (thisBase, flowBase, nextBase) match {\n case (true , true , true ) => base(\n srcC.copy(src=if (srcC.src >= topo.base.nNodes) -1 else srcC.src),\n nxtC, flow\n )\n case (true , true , false) => false\n case (true , false, true ) => {\n val src = topo.children(topo.childId(flow.egressNode)).src\n val atDst = src == srcC.dst\n !atDst && base(\n srcC.copy(src=if (srcC.src >= topo.base.nNodes) -1 else srcC.src),\n nxtC,\n flow.copy(egressNode=src)\n )\n }\n case (true , false, false) => topo.childId(nxtC.dst) == topo.childId(flow.egressNode)\n case (false, true , true ) => true\n case (false, true , false) => {\n val id = topo.childId(srcC.dst)\n children(id)(\n srcC=copyChannel(srcC, topo.offsets(id)),\n nxtC=copyChannel(nxtC, topo.offsets(id)),\n flow=flow.copy(egressNode=topo.children(id).dst)\n ) && topo.children(id).dst != srcC.dst - topo.offsets(id)\n }\n case (false, false, true ) => topo.childId(srcC.dst) != topo.childId(flow.egressNode)\n case (false, false, false) => {\n val fid = topo.childId(flow.egressNode)\n val sid = topo.childId(srcC.dst)\n val fdst = if (fid == sid) {\n flow.egressNode - topo.offsets(sid)\n } else {\n topo.children(sid).dst\n }\n val at_exit = (fid != sid &&\n (srcC.dst - topo.offsets(sid) == topo.children(sid).dst))\n children(sid)(\n srcC=copyChannel(srcC, topo.offsets(sid)),\n nxtC=copyChannel(nxtC, topo.offsets(sid)),\n flow=flow.copy(egressNode=fdst)\n ) && !at_exit\n }\n }\n }\n override def getNPrios(c: ChannelRoutingInfo): Int = {\n if (topo.isBase(c.dst) && topo.isBase(c.src)){\n base.getNPrios(c)\n } else if (topo.childId(c.src) == topo.childId(c.dst) && !c.isEgress) {\n children(topo.childId(c.src)).getNPrios(c.copy(\n src=if (c.src >= topo.base.nNodes) -1 else c.src))\n } else {\n 1\n }\n }\n override def getPrio(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo): Int = {\n val thisBase = topo.isBase(srcC.dst)\n val nextBase = topo.isBase(nxtC.dst)\n val id = topo.childId(srcC.dst)\n (thisBase, nextBase) match {\n case (true, true) => base.getPrio(\n srcC.copy(src=if (srcC.src >= topo.base.nNodes) -1 else srcC.src),\n nxtC,\n flow.copy(egressNode=topo.children(topo.childId(flow.egressNode)).src))\n case (false, false) => {\n if (topo.childId(srcC.dst) == topo.childId(nxtC.dst)) {\n children(id).getPrio(\n copyChannel(srcC, topo.offsets(id)),\n copyChannel(nxtC, topo.offsets(id)),\n flow.copy(egressNode=topo.children(id).dst))\n } else {\n 0\n }\n }\n case _ => 0\n }\n }\n\n override def isEscape(c: ChannelRoutingInfo, v: Int) = {\n val srcBase = topo.isBase(c.src)\n val dstBase = topo.isBase(c.dst)\n (srcBase, dstBase) match {\n case (true, true) => base.isEscape(c, v)\n case (true, false) => true\n case (false, true) => true\n case (false, false) => {\n val sid = topo.childId(c.dst)\n children(sid).isEscape(copyChannel(c, topo.offsets(sid)), v)\n }\n }\n }\n }\n }\n}\n\n\n/**\n * Pure shortest-path routing strategy with some VC-based load balancing.\n *\n * This routing relation computes single-path shortest routes between all node pairs\n * using BFS and restricts flow transitions to only those that follow the precomputed\n * shortest-path next hop. No deadlock avoidance mechanism is enforced.\n *\n * If multiple virtual channels (VCs) are available, we can assist the\n * PrioritizingVCAllocator by assigning priorities deterministically via a hashing \n * of (flow.ingressNode, flow.egressNode) to help with better VC utilization. \n * However VC transitions are not enforced and per-hop flows are allowed to use any VC \n * as long as the edge is on the shortest path.\n *\n * This routing strategy is best for minimal-hop designs, and \n * scenarios where higher-level deadlock prevention is handled \n * externally such as through EscapeChannelRouting.\n *\n * maxVCs: The number of virtual channels available per physical channel.\n * This must be >= 1. Defaults to 1 (no VC usage).\n * \n */\n\nobject ShortestPathRouting {\n def apply(maxVCs: Int = 1) = (topo: PhysicalTopology) => new RoutingRelation(topo) {\n require(maxVCs >= 1, s\"[ShortestPathRouting] maxVCs must be >= 1 (got $maxVCs)\")\n\n // Build adjacency list\n val adjList: Map[Int, Seq[Int]] = (0 until topo.nNodes).map { src =>\n src -> (0 until topo.nNodes).filter(dst => topo.topo(src, dst))\n }.toMap\n\n // Precompute shortest-path next hops using BFS\n val nextHop: Map[(Int, Int), Int] = {\n val paths = for (src <- 0 until topo.nNodes; dst <- 0 until topo.nNodes if src != dst) yield {\n val next = bfsNextHop(src, dst)\n (src, dst) -> next\n }\n paths.collect { case ((s, d), Some(n)) => (s, d) -> n }.toMap\n }\n\n // BFS shortest-path helper\n private def bfsNextHop(src: Int, dst: Int): Option[Int] = {\n val visited = scala.collection.mutable.Set[Int]()\n val queue = scala.collection.mutable.Queue[(Int, List[Int])]()\n queue.enqueue((src, List()))\n while (queue.nonEmpty) {\n val (node, path) = queue.dequeue()\n if (node == dst) return path.headOption\n if (!visited.contains(node)) {\n visited += node\n adjList(node).foreach { neighbor =>\n queue.enqueue((neighbor, if (path.isEmpty) List(neighbor) else path))\n }\n }\n }\n None\n }\n\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo): Boolean = {\n val flowKey = (flow.ingressNode, flow.egressNode)\n\n if (srcC.src == -1) {\n // Ingress: only inject into first hop of shortest path\n val expected = nextHop.get((flow.ingressNode, flow.egressNode))\n val legal = nxtC.src == flow.ingressNode && expected.contains(nxtC.dst)\n return legal\n }\n\n if (srcC.dst == flow.egressNode) return false\n\n val expected = nextHop.get((srcC.dst, flow.egressNode))\n val legal = expected.contains(nxtC.dst)\n legal\n }\n\n // VC configuration\n", "right_context": "\n override def getPrio(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo): Int = {\n (flow.ingressNode * 31 + flow.egressNode) % maxVCs\n }\n\n override def isEscape(c: ChannelRoutingInfo, vNetId: Int): Boolean = c.isIngress || c.isEgress\n\n println(s\"[ShortestPathRouting] Initialized with maxVCs = $maxVCs\")\n }\n}\n\n\nobject EscapeIDOrderRouting {\n def apply() = (topo: PhysicalTopology) => new RoutingRelation(topo) {\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo) = {\n if (srcC.src == -1) {\n true // allow ingress to inject anywhere\n } else {\n (srcC.dst < nxtC.dst) && topo.topo(srcC.dst, nxtC.dst)\n }\n }\n }\n}\n\n/*\n * CustomLayeredRouting: This is a a generalized deadlock-free routing policy for arbitrary\n * topologies. \n * \n * This routing relation assigns each flow (src, dst) a dedicated virtual channel (VC) layer\n * such that all paths in the same layer do not introduce cyclic dependencies. This is done by:\n * 1. Finding all shortest paths between flow pairs\n * 2. Deduplicating and pruning strict subpaths\n * 3. Packing flow paths into the minimum number of layers while preserving DAG constraints\n * 4. Assigning a VC layer to each flow based on its path\n * \n * The rel() function enforces this policy by:\n * - Ensuring packets flow only along the assigned VC\n * - Ensuring only legal hops in the assigned flow path are taken\n * - Ensuring the hop is within the assigned VC layer\n */\n\nobject CustomLayeredRouting {\n \n def apply() = (topo: PhysicalTopology) => topo match {\n case topo: CustomTopology => new RoutingRelation(topo) {\n val edgeList = topo.edgeList.map(e => (e.src, e.dst))\n val graph = new CustomGraph(topo.nNodes, edgeList)\n val allSSPs = graph.generateSSPs()\n\n val deduped = graph.deduplicateSSPs(allSSPs)\n val pruned = graph.pruneSubpaths(deduped)\n val packed = graph.packLayersMinimal(pruned)\n\n println(s\"[CustomLayeredRouting] Required VCs: ${packed.length}\")\n\n // VC assignment for all flows based on first matching layer\n val allFlowAssignments: Map[(Int, Int), Int] = allSSPs.map { case ((src, dst), path) =>\n val assignedLayer = packed.indexWhere(layer => path.toSet.subsetOf(layer.flatMap(_._2).toSet))\n ((src, dst), assignedLayer)\n }.toMap\n\n // Build nextHop map per VC (layer)\n val nextHopMap: Map[Int, Map[(Int, Int), Int]] = packed.zipWithIndex.map { case (layer, vc) =>\n val nhs = mutable.Map[(Int, Int), Int]()\n\n for (((src, dst), path) <- layer) {\n val nodes = path.map(_._1) :+ path.last._2\n for (i <- 0 until nodes.length - 1) {\n nhs((nodes(i), dst)) = nodes(i + 1)\n }\n }\n\n vc -> nhs.toMap\n }.toMap\n\n val flowPaths: Map[(Int, Int), List[(Int, Int)]] = allSSPs.toMap\n val vcToEdges = packed.map(_.flatMap(_._2).toSet)\n\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo): Boolean = {\n val flowKey = (flow.ingressNode, flow.egressNode)\n\n // Step 1: Lookup assigned VC\n val assignedVC = allFlowAssignments.getOrElse(flowKey, {\n return false\n })\n\n // Step 2: Lookup full path and verify layer correctness\n val flowPath = flowPaths.getOrElse(flowKey, {\n return false\n })\n\n val flowPathEdges = flowPath.toSet\n val assignedEdgeSet = vcToEdges(assignedVC)\n\n val fullPathOk = flowPathEdges.subsetOf(assignedEdgeSet)\n if (!fullPathOk) {\n return false\n }\n\n // Step 3: Current and next node\n val curNode = if (srcC.src == -1) flow.ingressNode else srcC.dst\n val nextNode = nxtC.dst\n val edge = (curNode, nextNode)\n\n // Step 4: Legal check\n val edgeOk = flowPathEdges.contains(edge)\n val vcOk = nxtC.vc == assignedVC && (srcC.src == -1 || srcC.vc == assignedVC)\n\n val legal = edgeOk && vcOk\n\n legal\n }\n\n\n override def isEscape(c: ChannelRoutingInfo, v: Int): Boolean =\n c.isIngress || c.isEgress\n\n val guAssignedLayer = allFlowAssignments\n val nVirtualLayers = vcToEdges.length\n\n override def getNPrios(c: ChannelRoutingInfo): Int = nVirtualLayers\n\n override def getPrio(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo): Int = 0\n\n }\n }\n\n}\n\n/**\n * ShortestPathGeneralizedDatelineRouting implements a deadlock-free routing relation\n * based on identifying cycle-breaking datelines and the presence of virtual channels.\n *\n * This routing strategy:\n * 1. Analyzes the given topology using DatelineAnalyzer to:\n * - Identify cycles in the channel dependency graph (CDG)\n * - Select a minimal set of \"dateline\" edges to break those cycles\n * - Compute the minimum number of virtual channels (VCs) needed to support\n * all shortest paths without deadlock\n *\n * 2. Recomputes all-pairs shortest paths and annotates each hop with the\n * required VC level. VC level increases only at dateline crossings,\n * and remains constant otherwise. This leads to an enforced acyclic traversal \n * of the dependency graph.\n *\n * 3. rel()) only permits transitions which:\n * - Follow the exact shortest path between (ingress, egress) nodes\n * - Match the expected VC at each hop\n * - Begin from the ingress using an assigned VC\n * - If useStaticVC0 is true then injections are only allowed on VC 0\n * - Otherwise there is a hashing scheme used to calculate the injection VC\n *\n */\n\nobject ShortestPathGeneralizedDatelineRouting {\n // def apply() = (topo: PhysicalTopology) => new RoutingRelation(topo) {\n def apply(\n useStaticVC0: Boolean = false,\n vcHashCoeffs: (Int, Int) = (19, 4)\n ) = (topo: PhysicalTopology) => new RoutingRelation(topo) {\n val result = DatelineAnalyzer.analyze(topo)\n val datelineEdges = result.datelineEdges\n val maxVC = result.vcCount\n val nextHop = result.nextHop\n\n // Recompute shortest paths and expected VC transitions\n val (shortestPaths, pathVCs): (Map[(Int, Int), List[Int]], Map[(Int, Int), List[Int]]) = {\n val g = new CustomGraph(topo.nNodes, (0 until topo.nNodes).flatMap(u => (0 until topo.nNodes).collect {\n case v if topo.topo(u, v) => (u, v)\n }))\n val sspPaths = g.generateSSPs()\n val pathMap = sspPaths.map { case ((src, dst), edges) => ((src, dst), src +: edges.map(_._2)) }.toMap\n val vcMap = pathMap.map { case ((src, dst), path) =>\n val vcs = if (useStaticVC0) {\n path.sliding(2).scanLeft(0) {\n case (vc, Seq(u, v)) =>\n if (datelineEdges.contains((u, v))) vc + 1 else vc\n }.toList\n } else {\n val (a, b) = vcHashCoeffs\n val baseVC = (src * a + dst * b) % maxVC \n path.sliding(2).scanLeft(baseVC) {\n case (vc, Seq(u, v)) =>\n if (datelineEdges.contains((u, v))) (vc + 1) % maxVC else vc\n }.toList\n }\n ((src, dst), vcs)\n }\n (pathMap, vcMap)\n }\n\n println(s\"[ShortestPathGeneralizedDatelineRouting] Initialized with ${datelineEdges.size} datelines and $maxVC VCs\")\n\n def rel(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo): Boolean = {\n\n val flowKey = (flow.ingressNode, flow.egressNode)\n\n val path = shortestPaths.getOrElse((flow.ingressNode, flow.egressNode), Nil)\n val vcs = pathVCs.getOrElse((flow.ingressNode, flow.egressNode), Nil)\n\n if (srcC.src == -1) {\n val validInjectionEdge = path.headOption.contains(nxtC.src) && path.lift(1).contains(nxtC.dst)\n val expectedVC = vcs.lift(1).getOrElse(-1)\n val vcValid = nxtC.vc == expectedVC\n validInjectionEdge && vcValid\n } else if (flow.egressNode == srcC.dst) {\n false\n } else {\n val edge = (srcC.dst, nxtC.dst)\n val pathEdges = path.sliding(2).toList\n val idx = pathEdges.indexWhere { case Seq(a, b) => a == edge._1 && b == edge._2 }\n\n val validEdge = idx != -1\n val expectedVC = if (idx >= 0 && idx < vcs.length) vcs(idx + 1) else -1\n val vcValid = nxtC.vc == expectedVC\n\n validEdge && vcValid\n }\n }\n\n override def getNPrios(src: ChannelRoutingInfo): Int = {\n maxVC\n }\n\n override def getPrio(srcC: ChannelRoutingInfo, nxtC: ChannelRoutingInfo, flow: FlowRoutingInfo): Int = {\n // Priority is highest for lowest VC to prefer dateline avoidance\n maxVC - nxtC.vc\n }\n\n override def isEscape(c: ChannelRoutingInfo, vNetId: Int): Boolean = {\n c.isIngress || c.isEgress || c.vc == 0\n }\n }\n}\n", "groundtruth": " override def getNPrios(src: ChannelRoutingInfo): Int = maxVCs\n", "crossfile_context": ""}
{"task_id": "constellation", "path": "constellation/src/main/scala/soc/Buses.scala", "left_context": "package constellation.soc\n\nimport chisel3._\nimport chisel3.util._\n\nimport org.chipsalliance.cde.config._\nimport freechips.rocketchip.diplomacy._\nimport freechips.rocketchip.devices.tilelink._\nimport freechips.rocketchip.tilelink._\nimport freechips.rocketchip.subsystem._\nimport freechips.rocketchip.util._\n\nimport constellation.noc.{NoCParams}\nimport constellation.protocol._\n\nimport scala.collection.immutable.{ListMap}\n\ncase class ConstellationSystemBusParams(\n sbusParams: SystemBusParams,\n tlNoCParams: TLNoCParams,\n inlineNoC: Boolean\n) extends TLBusWrapperInstantiationLike {\n def instantiate(context: HasTileLinkLocations, loc: Location[TLBusWrapper]\n )(implicit p: Parameters): ConstellationSystemBus = {\n val constellation = LazyModule(new ConstellationSystemBus(\n sbusParams, tlNoCParams, loc.name, context, inlineNoC))\n\n constellation.suggestName(loc.name)\n context.tlBusWrapperLocationMap += (loc -> constellation)\n constellation\n }\n}\n\nclass ConstellationSystemBus(\n sbus_params: SystemBusParams, noc_params: TLNoCParams, name: String, context: HasTileLinkLocations,\n inlineNoC: Boolean\n)(implicit p: Parameters) extends TLBusWrapper(sbus_params, name) {\n private val replicator = sbus_params.replication.map(r => LazyModule(new RegionReplicator(r)))\n val prefixNode = replicator.map { r =>\n r.prefix := addressPrefixNexusNode\n addressPrefixNexusNode\n }\n\n override def shouldBeInlined = inlineNoC\n\n private val system_bus_noc = noc_params match {\n case params: GlobalTLNoCParams => context.asInstanceOf[CanHaveGlobalNoC].globalNoCDomain {\n LazyModule(new TLGlobalNoC(params, name))\n }\n case params: SimpleTLNoCParams => LazyModule(new TLNoC(params, name, inlineNoC))\n case params: SplitACDxBETLNoCParams => LazyModule(new TLSplitACDxBENoC(params, name, inlineNoC))\n }\n\n val inwardNode: TLInwardNode = (system_bus_noc.node :=* TLFIFOFixer(TLFIFOFixer.allVolatile)\n :=* replicator.map(_.node).getOrElse(TLTempNode()))\n val outwardNode: TLOutwardNode = system_bus_noc.node\n def busView: TLEdge = system_bus_noc.node.edges.in.head\n\n val builtInDevices: BuiltInDevices = BuiltInDevices.attach(sbus_params, outwardNode)\n}\n\ncase class ConstellationMemoryBusParams(\n mbusParams: MemoryBusParams,\n tlNoCParams: TLNoCParams,\n inlineNoC: Boolean\n) extends TLBusWrapperInstantiationLike {\n def instantiate(context: HasTileLinkLocations, loc: Location[TLBusWrapper]\n )(implicit p: Parameters): ConstellationMemoryBus = {\n val constellation = LazyModule(new ConstellationMemoryBus(\n mbusParams, tlNoCParams, loc.name, context, inlineNoC))\n\n constellation.suggestName(loc.name)\n context.tlBusWrapperLocationMap += (loc -> constellation)\n constellation\n }\n}\n\nclass ConstellationMemoryBus(mbus_params: MemoryBusParams, noc_params: TLNoCParams, name: String, context: HasTileLinkLocations, inlineNoC: Boolean)\n (implicit p: Parameters) extends TLBusWrapper(mbus_params, name) {\n private val replicator = mbus_params.replication.map(r => LazyModule(new RegionReplicator(r)))\n val prefixNode = replicator.map { r =>\n r.prefix := addressPrefixNexusNode\n addressPrefixNexusNode\n }\n\n private val memory_bus_noc = noc_params match {\n case params: GlobalTLNoCParams => context.asInstanceOf[CanHaveGlobalNoC].globalNoCDomain {\n LazyModule(new TLGlobalNoC(params, name))\n }\n case params: SimpleTLNoCParams => LazyModule(new TLNoC(params, name, inlineNoC))\n case params: SplitACDxBETLNoCParams => LazyModule(new TLSplitACDxBENoC(params, name, inlineNoC))\n }\n\n val inwardNode: TLInwardNode =\n replicator.map(memory_bus_noc.node :*=* TLFIFOFixer(TLFIFOFixer.all) :*=* _.node)\n .getOrElse(memory_bus_noc.node :*=* TLFIFOFixer(TLFIFOFixer.all))\n\n val outwardNode: TLOutwardNode = ProbePicker() :*= memory_bus_noc.node\n def busView: TLEdge = memory_bus_noc.node.edges.in.head\n\n val builtInDevices: BuiltInDevices = BuiltInDevices.attach(mbus_params, outwardNode)\n}\n\ncase class ConstellationPeripheryBusParams(\n pbusParams: PeripheryBusParams,\n tlNoCParams: TLNoCParams,\n inlineNoC: Boolean\n) extends TLBusWrapperInstantiationLike {\n def instantiate(context: HasTileLinkLocations, loc: Location[TLBusWrapper]\n )(implicit p: Parameters): ConstellationPeripheryBus = {\n val constellation = LazyModule(new ConstellationPeripheryBus(pbusParams, tlNoCParams, loc.name, context, inlineNoC))\n\n constellation.suggestName(loc.name)\n context.tlBusWrapperLocationMap += (loc -> constellation)\n constellation\n }\n}\n\nclass ConstellationPeripheryBus(pbus_params: PeripheryBusParams, noc_params: TLNoCParams, name: String, context: HasTileLinkLocations, inlineNoC: Boolean)\n (implicit p: Parameters) extends TLBusWrapper(pbus_params, name) {\n\n private val replicator = pbus_params.replication.map(r => LazyModule(new RegionReplicator(r)))\n val prefixNode = replicator.map { r =>\n r.prefix := addressPrefixNexusNode\n addressPrefixNexusNode\n }\n\n def genNoC()(implicit valName: ValName): TLNoCLike = noc_params match {\n case params: GlobalTLNoCParams => context.asInstanceOf[CanHaveGlobalNoC].globalNoCDomain {\n LazyModule(new TLGlobalNoC(params, name))\n }\n case params: SimpleTLNoCParams => LazyModule(new TLNoC(params, name, inlineNoC))\n case params: SplitACDxBETLNoCParams => LazyModule(new TLSplitACDxBENoC(params, name, inlineNoC))\n }\n\n private val fixer = LazyModule(new TLFIFOFixer(TLFIFOFixer.all))\n private val node: TLNode = pbus_params.atomics.map { pa =>\n val in_xbar = LazyModule(new TLXbar)\n val out_noc = genNoC()\n val fixer_node = replicator.map(fixer.node :*= _.node).getOrElse(fixer.node)\n (out_noc.node\n :*= fixer_node\n :*= TLBuffer(pa.buffer)\n :*= (pa.widenBytes.filter(_ > beatBytes).map { w =>\n TLWidthWidget(w) :*= TLAtomicAutomata(arithmetic = pa.arithmetic)\n", "right_context": " :*= in_xbar.node)\n } .getOrElse {\n val noc = genNoC()\n noc.node :*= fixer.node\n }\n\n def inwardNode: TLInwardNode = node\n def outwardNode: TLOutwardNode = node\n def busView: TLEdge = fixer.node.edges.in.head\n\n val builtInDevices: BuiltInDevices = BuiltInDevices.attach(pbus_params, outwardNode)\n}\n\n", "groundtruth": " } .getOrElse { TLAtomicAutomata(arithmetic = pa.arithmetic) })\n", "crossfile_context": ""}
{"task_id": "constellation", "path": "constellation/src/main/scala/util/Utils.scala", "left_context": "package constellation.util\n\nimport chisel3._\nimport chisel3.util._\n\nobject WrapInc {\n // \"n\" is the number of increments, so we wrap at n-1.\n def apply(value: UInt, n: Int): UInt = {\n if (n == 1) {\n 0.U\n } else if (isPow2(n)) {\n (value + 1.U)(log2Ceil(n)-1,0)\n } else {\n", "right_context": " def apply(value: UInt, n: UInt): UInt = {\n val wrap = value === n - 1.U\n Mux(wrap, 0.U, value + 1.U)\n }\n}\n\n", "groundtruth": " val wrap = (value === (n-1).U)\n Mux(wrap, 0.U, value + 1.U)\n }\n", "crossfile_context": ""}
{"task_id": "essent", "path": "essent/src/main/scala/Driver.scala", "left_context": "package essent\n\nimport scala.io.Source\nimport scala.sys.process._\n\nimport logger._\n\n\nobject Driver {\n def main(args: Array[String]): Unit = {\n", "right_context": " Logger.setClassLogLevels(Map(\"essent\" -> logger.LogLevel(opt.essentLogLevel)))\n Logger.setClassLogLevels(Map(\"firrtl\" -> logger.LogLevel(opt.firrtlLogLevel)))\n val sourceReader = Source.fromFile(opt.firInputFile)\n val circuit = firrtl.Parser.parse(sourceReader.getLines(), firrtl.Parser.IgnoreInfo)\n sourceReader.close()\n val compiler = new EssentCompiler(opt)\n compiler.compileAndEmit(circuit)\n }\n\n def compileCPP(dutName: String, buildDir: String): ProcessBuilder = {\n Seq(\"g++\", \"-O3\", \"-std=c++11\", s\"-I$buildDir\", s\"-Ifirrtl-sig\",\n s\"$buildDir/$dutName-harness.cc\", \"-o\", s\"$buildDir/$dutName\")\n }\n}\n", "groundtruth": " (new ArgsParser).getConfig(args.toSeq) match {\n case Some(config) => generate(config)\n case None =>\n }\n", "crossfile_context": ""}
{"task_id": "essent", "path": "essent/src/main/scala/Emitter.scala", "left_context": "package essent\n\nimport essent.Extract._\nimport essent.ir._\n\nimport firrtl._\nimport firrtl.annotations._\nimport firrtl.ir._\nimport firrtl.Mappers._\nimport firrtl.PrimOps._\nimport firrtl.Utils._\n\nimport scala.util.Random\n\nobject Emitter {\n case class HyperedgeDep(name: String, deps: Seq[String], stmt: Statement)\n\n // Type Declaration & Initialization\n //----------------------------------------------------------------------------\n def genCppType(tpe: Type) = tpe match {\n case UIntType(IntWidth(w)) => s\"UInt<$w>\"\n case SIntType(IntWidth(w)) => s\"SInt<$w>\"\n case AsyncResetType => \"UInt<1>\"\n case _ => throw new Exception(s\"No CPP type implemented for $tpe\")\n }\n\n def initializeVals(topLevel: Boolean)(m: Module, registers: Seq[DefRegister], memories: Seq[DefMemory]) = {\n def initVal(name: String, tpe:Type) = s\"$name.rand_init();\"\n val regInits = registers map {\n r: DefRegister => initVal(r.name, r.tpe)\n }\n val memInits = memories flatMap { m: DefMemory => {\n if ((m.depth > 1000) && (bitWidth(m.dataType)) <= 64) {\n Seq(s\"${m.name}[0].rand_init();\",\n s\"for (size_t a=0; a < ${m.depth}; a++) ${m.name}[a] = ${m.name}[0].as_single_word() + a;\")\n } else\n Seq(s\"for (size_t a=0; a < ${m.depth}; a++) ${m.name}[a].rand_init();\")\n }}\n val portInits = m.ports flatMap { p => p.tpe match {\n case ClockType => Seq()\n case _ => if (!topLevel) Seq()\n else Seq(initVal(p.name, p.tpe))\n }}\n regInits ++ memInits ++ portInits\n }\n\n\n // Prefixing & Replacement\n //----------------------------------------------------------------------------\n def addPrefixToNameStmt(prefix: String)(s: Statement): Statement = {\n val replaced = s match {\n case n: DefNode => n.copy(name = prefix + n.name)\n case r: DefRegister => r.copy(name = prefix + r.name)\n case m: DefMemory => m.copy(name = prefix + m.name)\n case w: DefWire => w.copy(name = prefix + w.name)\n case mw: MemWrite => mw.copy(memName = prefix + mw.memName)\n case _ => s\n }\n replaced map addPrefixToNameStmt(prefix) map addPrefixToNameExpr(prefix)\n }\n\n def addPrefixToNameExpr(prefix: String)(e: Expression): Expression = {\n val replaced = e match {\n case w: WRef => w.copy(name = prefix + w.name)\n case _ => e\n }\n replaced map addPrefixToNameExpr(prefix)\n }\n\n def replaceNamesStmt(renames: Map[String, String])(s: Statement): Statement = {\n val nodeReplaced = s match {\n case n: DefNode if (renames.contains(n.name)) => n.copy(name = renames(n.name))\n case cm: CondMux if (renames.contains(cm.name)) => cm.copy(name = renames(cm.name))\n case mw: MemWrite if (renames.contains(mw.memName)) => mw.copy(memName = renames(mw.memName))\n case _ => s\n }\n nodeReplaced map replaceNamesStmt(renames) map replaceNamesExpr(renames)\n }\n\n def replaceNamesExpr(renames: Map[String, String])(e: Expression): Expression = {\n def findRootKind(e: Expression): Kind = e match {\n case w: WRef => w.kind\n case w: WSubField => findRootKind(w.expr)\n }\n e match {\n case w: WRef => {\n if (renames.contains(w.name)) w.copy(name = renames(w.name))\n else w\n }\n case w: WSubField => {\n val fullName = emitExpr(w)\n // flattens out nested WSubFields\n if (renames.contains(fullName)) WRef(renames(fullName), w.tpe, findRootKind(w), w.flow)\n else w\n }\n case _ => e map replaceNamesExpr(renames)\n }\n }\n\n\n // Emission\n //----------------------------------------------------------------------------\n def emitPort(topLevel: Boolean)(p: Port): Seq[String] = p.tpe match {\n case ClockType => if (!topLevel) Seq()\n else Seq(genCppType(UIntType(IntWidth(1))) + \" \" + p.name + \";\")\n // FUTURE: suppress generation of clock field if not making harness (or used)?\n case _ => if (!topLevel) Seq()\n else Seq(genCppType(p.tpe) + \" \" + p.name + \";\")\n }\n\n def chunkLitString(litStr: String, chunkWidth:Int = 16): Seq[String] = {\n if (litStr.length % chunkWidth == 0) litStr.grouped(chunkWidth).toSeq\n else Seq(litStr.take(litStr.length % chunkWidth)) ++ chunkLitString(litStr.drop(litStr.length % chunkWidth), chunkWidth)\n }\n\n // NOTE: assuming no large UIntLiteral is negative\n def splatLargeLiteralIntoRawArray(value: BigInt, width: BigInt): String = {\n val rawHexStr = value.toString(16)\n val isNeg = value < 0\n val asHexStr = if (isNeg) rawHexStr.tail else rawHexStr\n val arrStr = chunkLitString(asHexStr) map { \"0x\" + _} mkString(\",\")\n val leadingNegStr = if (isNeg) \"(uint64_t) -\" else \"\"\n val numWords = (width + 63) / 64\n s\"std::array({$leadingNegStr$arrStr})\"\n }\n\n def emitExpr(e: Expression)(implicit rn: Renamer = null): String = e match {\n case w: WRef => if (rn != null) rn.emit(w.name) else w.name\n case u: UIntLiteral => {\n val maxIn64Bits = (BigInt(1) << 64) - 1\n val width = bitWidth(u.tpe)\n val asHexStr = u.value.toString(16)\n if ((width <= 64) || (u.value <= maxIn64Bits)) s\"UInt<$width>(0x$asHexStr)\"\n else s\"UInt<$width>(${splatLargeLiteralIntoRawArray(u.value, width)})\"\n }\n case u: SIntLiteral => {\n val width = bitWidth(u.tpe)\n if (width <= 64) s\"SInt<$width>(${u.value.toString(10)})\"\n else s\"SInt<$width>(${splatLargeLiteralIntoRawArray(u.value, width)})\"\n }\n case m: Mux => {\n val condName = emitExprWrap(m.cond)\n val tvalName = emitExprWrap(m.tval)\n val fvalName = emitExprWrap(m.fval)\n s\"$condName ? $tvalName : $fvalName\"\n }\n case w: WSubField => {\n val result = s\"${emitExpr(w.expr)(null)}.${w.name}\"\n if (rn != null)\n rn.emit(result)\n else\n result\n }\n case w: WSubAccess => s\"${emitExpr(w.expr)}[${emitExprWrap(w.index)}.as_single_word()]\"\n case p: DoPrim => p.op match {\n case Add => p.args map emitExprWrap mkString(\" + \")\n", "right_context": " case Sub => p.args map emitExprWrap mkString(\" - \")\n case Subw => s\"${emitExprWrap(p.args(0))}.subw(${emitExprWrap(p.args(1))})\"\n case Mul => p.args map emitExprWrap mkString(\" * \")\n case Div => p.args map emitExprWrap mkString(\" / \")\n case Rem => p.args map emitExprWrap mkString(\" % \")\n case Lt => p.args map emitExprWrap mkString(\" < \")\n case Leq => p.args map emitExprWrap mkString(\" <= \")\n case Gt => p.args map emitExprWrap mkString(\" > \")\n case Geq => p.args map emitExprWrap mkString(\" >= \")\n case Eq => p.args map emitExprWrap mkString(\" == \")\n case Neq => p.args map emitExprWrap mkString(\" != \")\n case Pad => s\"${emitExprWrap(p.args.head)}.pad<${bitWidth(p.tpe)}>()\"\n case AsUInt => s\"${emitExprWrap(p.args.head)}.asUInt()\"\n case AsSInt => s\"${emitExprWrap(p.args.head)}.asSInt()\"\n case AsClock => throw new Exception(\"AsClock unimplemented!\")\n case AsAsyncReset => emitExpr(p.args.head) // TODO: make async\n case Shl => s\"${emitExprWrap(p.args.head)}.shl<${p.consts.head.toInt}>()\"\n // case Shlw => s\"${emitExprWrap(p.args.head)}.shlw<${p.consts.head.toInt}>()\"\n case Shr => s\"${emitExprWrap(p.args.head)}.shr<${p.consts.head.toInt}>()\"\n case Dshl => p.args map emitExprWrap mkString(\" << \")\n case Dshlw => s\"${emitExprWrap(p.args(0))}.dshlw(${emitExpr(p.args(1))})\"\n case Dshr => p.args map emitExprWrap mkString(\" >> \")\n case Cvt => s\"${emitExprWrap(p.args.head)}.cvt()\"\n case Neg => s\"-${emitExprWrap(p.args.head)}\"\n case Not => s\"~${emitExprWrap(p.args.head)}\"\n case And => p.args map emitExprWrap mkString(\" & \")\n case Or => p.args map emitExprWrap mkString(\" | \")\n case Xor => p.args map emitExprWrap mkString(\" ^ \")\n case Andr => s\"${emitExprWrap(p.args.head)}.andr()\"\n case Orr => s\"${emitExprWrap(p.args.head)}.orr()\"\n case Xorr => s\"${emitExprWrap(p.args.head)}.xorr()\"\n case Cat => s\"${emitExprWrap(p.args(0))}.cat(${emitExpr(p.args(1))})\"\n case Bits => s\"${emitExprWrap(p.args.head)}.bits<${p.consts(0).toInt},${p.consts(1).toInt}>()\"\n case Head => s\"${emitExprWrap(p.args.head)}.head<${p.consts.head.toInt}>()\"\n case Tail => s\"${emitExprWrap(p.args.head)}.tail<${p.consts.head.toInt}>()\"\n }\n case _ => throw new Exception(s\"Don't yet support $e\")\n }\n\n def emitExprWrap(e: Expression)(implicit rn: Renamer): String = e match {\n case DoPrim(_,_,_,_) | Mux(_,_,_,_) => s\"(${emitExpr(e)})\"\n case _ => emitExpr(e)\n }\n\n def emitStmt(s: Statement)(implicit rn: Renamer): Seq[String] = s match {\n case b: Block => b.stmts flatMap emitStmt\n case d: DefNode => {\n val lhs_orig = d.name\n val lhs = rn.emit(lhs_orig)\n val rhs = emitExpr(d.value)\n if (rn.decLocal(lhs_orig)) Seq(s\"${genCppType(d.value.tpe)} $lhs = $rhs;\")\n else Seq(s\"$lhs = $rhs;\")\n }\n case c: Connect => {\n val lhs_orig = emitExpr(c.loc)(null)\n val lhs = rn.emit(lhs_orig)\n val rhs = emitExpr(c.expr)\n if (rn.decLocal(lhs_orig)) Seq(s\"${genCppType(c.loc.tpe)} $lhs = $rhs;\")\n else Seq(s\"$lhs = $rhs;\")\n }\n case p: Print => {\n val formatters = \"(%h)|(%x)|(%d)|(%ld)\".r.findAllIn(p.string.serialize).toList\n val argWidths = p.args map {e: Expression => bitWidth(e.tpe)}\n if (!(argWidths forall { _ <= 64 })) throw new Exception(s\"Can't print wide signals\")\n val replacements = formatters zip argWidths map { case(format, width) =>\n if (format == \"%h\" || format == \"%x\") {\n val printWidth = math.ceil(width.toDouble/4).toInt\n (format, s\"\"\"%0${printWidth}\" PRIx64 \"\"\"\")\n } else {\n val printWidth = math.ceil(math.log10((1L< str.replaceFirst(searchFor, replaceWith)\n }\n val printfArgs = Seq(s\"\"\"\"$formatString\"\"\"\") ++\n (p.args map {arg => s\"${emitExprWrap(arg)}.as_single_word()\"})\n Seq(s\"if (UNLIKELY(done_reset && update_registers && verbose && ${emitExprWrap(p.en)})) printf(${printfArgs mkString(\", \")});\")\n }\n case st: Stop => {\n Seq(s\"if (UNLIKELY(${emitExpr(st.en)})) {assert_triggered = true; assert_exit_code = ${st.ret};}\")\n }\n case mw: MemWrite => {\n Seq(s\"if (UNLIKELY(update_registers && ${emitExprWrap(mw.wrEn)} && ${emitExprWrap(mw.wrMask)})) ${mw.memName}[${emitExprWrap(mw.wrAddr)}.as_single_word()] = ${emitExpr(mw.wrData)};\")\n }\n case ru: RegUpdate => Seq(s\"if (update_registers) ${emitExpr(ru.regRef)} = ${emitExpr(ru.expr)};\")\n case r: DefRegister => Seq()\n case w: DefWire => Seq()\n case m: DefMemory => Seq()\n case i: WDefInstance => Seq()\n case _ => throw new Exception(s\"Don't yet support $s\")\n }\n}\n", "groundtruth": " case Addw => s\"${emitExprWrap(p.args(0))}.addw(${emitExprWrap(p.args(1))})\"\n", "crossfile_context": ""}
{"task_id": "essent", "path": "essent/src/main/scala/IR.scala", "left_context": "package essent.ir\n\nimport firrtl._\nimport firrtl.ir._\n\n// ESSENT's additions to the IR for optimization\n\ncase class RegUpdate(info: Info, regRef: Expression, expr: Expression) extends Statement {\n def serialize: String = s\"${regRef.serialize} <= ${expr.serialize}\" + info.serialize\n def mapStmt(f: Statement => Statement): Statement = this\n def mapExpr(f: Expression => Expression): Statement = this.copy(regRef = f(regRef), expr = f(expr))\n def mapType(f: Type => Type): Statement = this\n def mapString(f: String => String): Statement = this\n def mapInfo(f: Info => Info): Statement = this\n def foreachExpr(f: firrtl.ir.Expression => Unit): Unit = ???\n def foreachInfo(f: firrtl.ir.Info => Unit): Unit = ???\n def foreachStmt(f: firrtl.ir.Statement => Unit): Unit = ???\n def foreachString(f: String => Unit): Unit = ???\n def foreachType(f: firrtl.ir.Type => Unit): Unit = ???\n}\n\ncase class MemWrite(memName: String,\n portName: String,\n wrEn: Expression,\n wrMask: Expression,\n wrAddr: Expression,\n wrData: Expression) extends Statement {\n", "right_context": " def mapStmt(f: Statement => Statement): Statement = this\n def mapExpr(f: Expression => Expression): Statement = {\n MemWrite(memName, portName, f(wrEn), f(wrMask), f(wrAddr), f(wrData))\n }\n def mapType(f: Type => Type): Statement = this\n def mapString(f: String => String): Statement = this\n def mapInfo(f: Info => Info): Statement = this\n def nodeName(): String = s\"$memName.$portName\"\n def foreachExpr(f: firrtl.ir.Expression => Unit): Unit = ???\n def foreachInfo(f: firrtl.ir.Info => Unit): Unit = ???\n def foreachStmt(f: firrtl.ir.Statement => Unit): Unit = ???\n def foreachString(f: String => Unit): Unit = ???\n def foreachType(f: firrtl.ir.Type => Unit): Unit = ???\n}\n\ncase class CondMux(name: String, mux: Mux, tWay: Seq[Statement], fWay: Seq[Statement]) extends Statement {\n def serialize: String = \"conditional mux\"\n def mapStmt(f: Statement => Statement): Statement = this.copy(tWay = tWay map f, fWay = fWay map f)\n def mapExpr(f: Expression => Expression): Statement = this\n def mapType(f: Type => Type): Statement = this\n def mapString(f: String => String): Statement = this\n def mapInfo(f: Info => Info): Statement = this\n def foreachExpr(f: firrtl.ir.Expression => Unit): Unit = ???\n def foreachInfo(f: firrtl.ir.Info => Unit): Unit = ???\n def foreachStmt(f: firrtl.ir.Statement => Unit): Unit = ???\n def foreachString(f: String => Unit): Unit = ???\n def foreachType(f: firrtl.ir.Type => Unit): Unit = ???\n}\n\ncase class CondPart(\n id: Int,\n alwaysActive: Boolean,\n inputs: Seq[String],\n memberStmts: Seq[Statement],\n outputsToDeclare: Map[String,firrtl.ir.Type]) extends Statement {\n def serialize: String = s\"CondPart #$id\"\n def mapStmt(f: Statement => Statement): Statement = this.copy(memberStmts = memberStmts map f)\n def mapExpr(f: Expression => Expression): Statement = this\n def mapType(f: Type => Type): Statement = this\n def mapString(f: String => String): Statement = this\n def mapInfo(f: Info => Info): Statement = this\n def foreachExpr(f: firrtl.ir.Expression => Unit): Unit = ???\n def foreachInfo(f: firrtl.ir.Info => Unit): Unit = ???\n def foreachStmt(f: firrtl.ir.Statement => Unit): Unit = ???\n def foreachString(f: String => Unit): Unit = ???\n def foreachType(f: firrtl.ir.Type => Unit): Unit = ???\n}\n", "groundtruth": " def serialize: String = s\"if (${wrEn.serialize} && ${wrMask.serialize}) $memName[${wrAddr.serialize}] = ${wrData.serialize}\"\n", "crossfile_context": ""}
{"task_id": "essent", "path": "essent/src/main/scala/MFFC.scala", "left_context": "package essent\n\nimport Graph._\n\nimport collection.mutable.ArrayBuffer\n\n\nclass MFFC(val g: Graph) {\n import MFFC.{Unclaimed,Excluded}\n\n // numeric vertex ID -> MFFC ID\n val mffc = ArrayBuffer.fill(g.numNodes())(Unclaimed)\n\n def overrideMFFCs(newAssignments: ArrayBuffer[NodeID]): Unit = {\n mffc.clear()\n mffc ++= newAssignments\n }\n\n def findMFFCs(): ArrayBuffer[NodeID] = {\n val unvisitedSinks = g.nodeRange() filter {\n id => mffc(id) == Unclaimed && g.outNeigh(id).isEmpty\n }\n val visited = g.nodeRange() filter { id => mffc(id) != Unclaimed }\n val fringe = (visited flatMap(g.inNeigh)).distinct\n val unvisitedFringe = fringe filter { mffc(_) == Unclaimed }\n val newMFFCseeds = unvisitedSinks.toSet ++ unvisitedFringe\n if (newMFFCseeds.isEmpty) {\n mffc\n } else {\n newMFFCseeds foreach { id => mffc(id) = id }\n maximizeFFCs(newMFFCseeds)\n findMFFCs()\n }\n }\n\n def maximizeFFCs(fringe: Set[NodeID]): Unit = {\n val fringeAncestors = fringe flatMap g.inNeigh filter { mffc(_) == Unclaimed }\n val newMembers = fringeAncestors flatMap { parent => {\n val childrenMFFCs = (g.outNeigh(parent) map mffc).distinct\n if ((childrenMFFCs.size == 1) && (childrenMFFCs.head != Unclaimed)) {\n mffc(parent) = childrenMFFCs.head\n Seq(parent)\n } else Seq()\n }}\n if (newMembers.nonEmpty)\n maximizeFFCs(newMembers)\n }\n}\n\n\nobject MFFC {\n val Unclaimed = -1\n val Excluded = -2\n\n", "right_context": "}\n", "groundtruth": " def apply(g: Graph, excludeSet: Set[NodeID] = Set()): ArrayBuffer[NodeID] = {\n val worker = new MFFC(g)\n excludeSet foreach { id => worker.mffc(id) = Excluded }\n val mffc = worker.findMFFCs()\n", "crossfile_context": ""}
{"task_id": "essent", "path": "essent/src/main/scala/StatementGraph.scala", "left_context": "package essent\n\nimport firrtl.ir._\n\nimport essent.Emitter._\nimport essent.Extract._\nimport essent.ir._\n\nimport collection.mutable.{ArrayBuffer, BitSet, HashMap}\nimport scala.reflect.ClassTag\n\n// Extends Graph to include more attributes per node\n// - Associates a name (String) and Statement with each node\n// - Name must be unique, since can find nodes by name too\n// - Nodes can have an EmptyStatement if no need to emit\n\nclass StatementGraph extends Graph {\n // Access companion object's type aliases without prefix\n // TODO: type alias for name type? Hard to imagine other than String?\n import Graph.{NodeID, AdjacencyList}\n\n\n // Internal data structures\n //----------------------------------------------------------------------------\n // Vertex name (string of destination variable) -> numeric ID\n val nameToID = HashMap[String,NodeID]()\n // Numeric vertex ID -> name (string destination variable)\n val idToName = ArrayBuffer[String]()\n // Numeric vertex ID -> firrtl statement (Block used for aggregates)\n val idToStmt = ArrayBuffer[Statement]()\n // Numeric vertex ID -> Boolean indicating whether node should be emitted\n val validNodes = BitSet()\n\n\n // Graph building\n //----------------------------------------------------------------------------\n def getID(vertexName: String) = {\n if (nameToID contains vertexName) nameToID(vertexName)\n else {\n val newID = nameToID.size\n nameToID(vertexName) = newID\n idToName += vertexName\n idToStmt += EmptyStmt\n growNeighsIfNeeded(newID)\n // TODO: is it better to trust Graph to grow for new ID? (current)\n newID\n }\n }\n\n def addEdge(sourceName: String, destName: String): Unit = {\n super.addEdge(getID(sourceName), getID(destName))\n }\n\n def addEdgeIfNew(sourceName: String, destName: String): Unit = {\n super.addEdgeIfNew(getID(sourceName), getID(destName))\n }\n\n def addStatementNode(resultName: String, depNames: Seq[String],\n stmt: Statement = EmptyStmt): Unit = {\n val potentiallyNewDestID = getID(resultName)\n depNames foreach {depName : String => addEdge(depName, resultName)}\n if (potentiallyNewDestID >= idToStmt.size) {\n val numElemsToGrow = potentiallyNewDestID - idToStmt.size + 1\n idToStmt.appendAll(ArrayBuffer.fill(numElemsToGrow)(EmptyStmt))\n }\n idToStmt(potentiallyNewDestID) = stmt\n // Don't want to emit state element declarations\n if (!stmt.isInstanceOf[DefRegister] && !stmt.isInstanceOf[DefMemory])\n validNodes += potentiallyNewDestID\n }\n\n def buildFromBodies(bodies: Seq[Statement]): Unit = {\n val bodyHE = bodies flatMap {\n case b: Block => b.stmts flatMap findDependencesStmt\n case s => findDependencesStmt(s)\n }\n bodyHE foreach { he => addStatementNode(he.name, he.deps, he.stmt) }\n }\n\n\n // Traversal / Queries / Extraction\n //----------------------------------------------------------------------------\n def collectValidStmts(ids: Seq[NodeID]): Seq[Statement] = ids filter validNodes map idToStmt\n\n", "right_context": "\n def containsStmtOfType[T <: Statement]()(implicit tag: ClassTag[T]): Boolean = {\n (idToStmt collectFirst { case s: T => s }).isDefined\n }\n\n def findIDsOfStmtOfType[T <: Statement]()(implicit tag: ClassTag[T]): Seq[NodeID] = {\n (idToStmt.zipWithIndex collect { case (s: T , id: Int) => id }).toSeq\n }\n\n def allRegDefs(): Seq[DefRegister] = (idToStmt collect {\n case dr: DefRegister => dr\n }).toSeq\n\n def stateElemNames(): Seq[String] = (idToStmt collect {\n case dr: DefRegister => dr.name\n case dm: DefMemory => dm.name\n }).toSeq\n\n def stateElemIDs() = findIDsOfStmtOfType[DefRegister]() ++ findIDsOfStmtOfType[DefMemory]()\n\n def mergeIsAcyclic(nameA: String, nameB: String): Boolean = {\n val idA = nameToID(nameA)\n val idB = nameToID(nameB)\n super.mergeIsAcyclic(idA, idB)\n }\n\n def extractSourceIDs(e: Expression): Seq[NodeID] = findDependencesExpr(e) map nameToID\n\n\n // Mutation\n //----------------------------------------------------------------------------\n def addOrderingDepsForStateUpdates(): Unit = {\n def addOrderingEdges(writerID: NodeID, readerTargetID: NodeID): Unit = {\n outNeigh(readerTargetID) foreach {\n readerID => if (readerID != writerID) addEdgeIfNew(readerID, writerID)\n }\n }\n idToStmt.zipWithIndex foreach { case(stmt, id) => {\n val readerTargetName = stmt match {\n case ru: RegUpdate => Some(emitExpr(ru.regRef))\n case mw: MemWrite => Some(mw.memName)\n case _ => None\n }\n readerTargetName foreach {\n name => if (nameToID.contains(name)) addOrderingEdges(id, nameToID(name))\n }\n }}\n }\n\n def mergeStmtsMutably(mergeDest: NodeID, mergeSources: Seq[NodeID], mergeStmt: Statement): Unit = {\n val mergedID = mergeDest\n val idsToRemove = mergeSources\n idsToRemove foreach { id => idToStmt(id) = EmptyStmt }\n // NOTE: keeps mappings of name (idToName & nameToID) for debugging dead nodes\n mergeNodesMutably(mergeDest, mergeSources)\n idToStmt(mergeDest) = mergeStmt\n validNodes(mergeDest) = (mergeSources :+ mergeDest) exists { validNodes }\n validNodes --= idsToRemove\n }\n\n\n // Stats\n //----------------------------------------------------------------------------\n def numValidNodes() = validNodes.size\n\n def numNodeRefs() = idToName.size\n\n def makeStatsString() =\n s\"Graph has ${numNodes()} nodes (${numValidNodes()} valid) and ${numEdges()} edges\"\n}\n\n\n\nobject StatementGraph {\n def apply(bodies: Seq[Statement]): StatementGraph = {\n val sg = new StatementGraph\n sg.buildFromBodies(bodies)\n sg.addOrderingDepsForStateUpdates()\n sg\n }\n\n def apply(circuit: Circuit, removeFlatConnects: Boolean = true): StatementGraph =\n apply(flattenWholeDesign(circuit, removeFlatConnects))\n}\n", "groundtruth": " def stmtsOrdered(): Seq[Statement] = collectValidStmts(TopologicalSort(this).toSeq)\n", "crossfile_context": ""}
{"task_id": "essent", "path": "essent/src/main/scala/disabled/disabledInferAddw.scala", "left_context": "package disabled\n\nimport collection.mutable.HashMap\n\nimport firrtl._\nimport firrtl.ir._\nimport firrtl.Mappers._\nimport firrtl.passes._\nimport firrtl.PrimOps._\nimport firrtl.Utils._\n\n\n// Replaces a tail following an add with an addw if:\n// - result of add is used only in the one tail\n// - tail only clips top bit\n// - also does sub -> subw\n\n\nobject InferAddw extends Pass {\n def desc = \"Replace tail on add results with addw (or sub with subw)\"\n\n val WRefCounts = HashMap[String, Int]()\n\n // return names of all nodes with add expressions\n def findAddSigs(s: Statement): Seq[(String,DoPrim)] = s match {\n case b: Block => b.stmts flatMap findAddSigs\n case DefNode(_, name: String, primE: DoPrim) => primE.op match { \n case Add => Seq((name, primE copy (tpe = oneNarrower(primE.tpe))))\n // case Sub => Seq((name, primE copy (tpe = oneNarrower(primE.tpe))))\n case _ => Seq()\n }\n case _ => Seq()\n }\n\n def countWRefsExpr(addSigs: Set[String])(e: Expression): Expression = {\n e match {\n case WRef(name, _, _, _) => {\n if (addSigs.contains(name)) WRefCounts(name) = WRefCounts.getOrElse(name,0) + 1\n }\n case _ => e\n }\n e map countWRefsExpr(addSigs)\n }\n\n def countWRefsStmt(addSigs: Set[String])(s: Statement): Statement = {\n s map countWRefsStmt(addSigs) map countWRefsExpr(addSigs)\n }\n\n // return names of all nodes that tail an add expressions\n def findDependentTails(addSigs: Set[String])(s: Statement): Seq[(String,String)] = {\n s match {\n case b: Block => b.stmts flatMap findDependentTails(addSigs)\n case DefNode(_, tName: String, primE: DoPrim) => primE.op match { \n case Tail => {\n", "right_context": " }\n\n def oneNarrower(tpe: Type): Type = tpe match {\n case UIntType(w) => UIntType(w - IntWidth(1))\n case SIntType(w) => SIntType(w - IntWidth(1))\n case _ => throw new Exception(\"can't narrow a non-ground type!\")\n }\n\n def convertExpToW(primE: DoPrim): DoPrim = {\n val newOp = primE.op match {\n case Add => Addw\n // case Sub => Subw\n }\n primE copy (op = newOp)\n }\n\n def replaceInferAddwStmt(tailMap: Map[String,DoPrim], addsToRemove: Set[String])(s: Statement): Statement = {\n val replaced = s match {\n case DefNode(info, nodeName: String, primE: DoPrim) => primE.op match { \n case Tail => {\n if (tailMap.contains(nodeName))\n DefNode(info, nodeName, convertExpToW(tailMap(nodeName)))\n else s\n }\n case Add => {\n if (addsToRemove.contains(nodeName)) EmptyStmt\n else s\n }\n // case Sub => {\n // if (addsToRemove.contains(nodeName)) EmptyStmt\n // else s\n // }\n case _ => s\n }\n case _ => s\n }\n replaced map replaceInferAddwStmt(tailMap, addsToRemove)\n }\n\n def InferAddwModule(m: Module): Module = {\n val addMap = findAddSigs(m.body).toMap\n WRefCounts.clear()\n m.body map countWRefsStmt(addMap.keySet)\n val singleUseAddSigs = addMap.filter { case (k, v) => WRefCounts(k) == 1 }\n val tailPairs = findDependentTails(singleUseAddSigs.keySet)(m.body)\n val tailMap = (tailPairs map { case (tailSig: String, addSig: String) =>\n (tailSig, addMap(addSig)) }).toMap\n val addsToRemove = (tailPairs map { _._2 }).toSet\n val newBody = m.body map replaceInferAddwStmt(tailMap, addsToRemove)\n Module(m.info, m.name, m.ports, squashEmpty(newBody))\n }\n\n def run(c: Circuit): Circuit = {\n val modulesx = c.modules.map {\n case m: ExtModule => m\n case m: Module => InferAddwModule(m)\n }\n Circuit(c.info, modulesx, c.main)\n }\n}\n", "groundtruth": " val eName = primE.args.head match { case w: WRef => w.name }\n if ((addSigs.contains(eName)) && (primE.consts.head == 1) && (bitWidth(primE.tpe) == 64))\n Seq((tName, eName))\n else Seq()\n }\n", "crossfile_context": ""}
{"task_id": "essent", "path": "essent/src/main/scala/disabled/disabledRandInitInvalids.scala", "left_context": "package disabled\n\nimport essent.Emitter._\n\nimport firrtl._\nimport firrtl.ir._\nimport firrtl.Mappers._\nimport firrtl.passes._\nimport firrtl.Utils._\n\nimport scala.math.BigInt\nimport scala.util.Random\n\n\nobject RandInitInvalids extends Pass {\n def desc = \"Randomly initialize invalid signals\"\n\n def genRandomLiteral(width: Int): BigInt = BigInt(width, Random)\n\n def randInitStmt(portNames: Set[String])(s: Statement): Statement = {\n val replaced = s match {\n case i: IsInvalid => {\n val randLit = i.expr.tpe match {\n case UIntType(IntWidth(w)) => UIntLiteral(genRandomLiteral(w.toInt), IntWidth(w))\n case SIntType(IntWidth(w)) => SIntLiteral(genRandomLiteral(w.toInt), IntWidth(w))\n }\n if (portNames.contains(emitExpr(i.expr)))\n Connect(i.info, i.expr, randLit)\n else\n DefNode(i.info, emitExpr(i.expr), randLit)\n }\n case _ => s\n }\n replaced map randInitStmt(portNames)\n }\n\n def randInitModule(m: Module): Module = {\n", "right_context": " Module(m.info, m.name, m.ports, squashEmpty(randInitStmt(portNames)(m.body)))\n }\n\n def run(c: Circuit): Circuit = {\n val modulesx = c.modules.map {\n case m: ExtModule => m\n case m: Module => randInitModule(m)\n }\n Circuit(c.info, modulesx, c.main)\n }\n}\n", "groundtruth": " val portNames = (m.ports map { _.name }).toSet\n", "crossfile_context": ""}
{"task_id": "essent", "path": "essent/src/main/scala/disabled/disabledZeroFromBits.scala", "left_context": "package disabled\n\nimport firrtl._\nimport firrtl.ir._\nimport firrtl.Mappers._\nimport firrtl.passes._\nimport firrtl.PrimOps._\n\n\nobject ZeroFromBits extends Pass {\n def desc = \"Replaces bit extracts on literal zeros with zeros\"\n\n def simpBitsExpr(e: Expression): Expression = {\n val bigZero = BigInt(0)\n val replaced = e match {\n case p: DoPrim => p.op match {\n case Bits => p.args.head match {\n case UIntLiteral(bigZero, _) => UIntLiteral(bigZero, IntWidth(bitWidth(p.tpe)))\n case _ => p\n }\n case _ => p\n }\n case _ => e\n }\n replaced map simpBitsExpr\n }\n\n def simpBitsStmt(s: Statement): Statement = {\n s map simpBitsStmt map simpBitsExpr\n }\n\n def simpBitsModule(m: Module): Module = {\n Module(m.info, m.name, m.ports, simpBitsStmt(m.body))\n }\n\n", "right_context": "", "groundtruth": " def run(c: Circuit): Circuit = {\n val modulesx = c.modules.map {\n case m: ExtModule => m\n case m: Module => simpBitsModule(m)\n }\n", "crossfile_context": ""}
{"task_id": "essent", "path": "essent/src/main/scala/passes/RegFromMem1.scala", "left_context": "package essent.passes\n\nimport essent.Emitter._\n\nimport firrtl._\nimport firrtl.ir._\nimport firrtl.Mappers._\nimport firrtl.options.Dependency\nimport firrtl.passes._\nimport firrtl.Utils._\n\n\nobject RegFromMem1 extends Pass {\n def desc = \"Replaces single-element mems with a register\"\n\n override def prerequisites = Seq(Dependency(essent.passes.NoClockConnects))\n override def optionalPrerequisites = firrtl.stage.Forms.LowFormOptimized\n override def invalidates(a: Transform) = false\n\n def memHasRightParams(m: DefMemory) = {\n (m.depth == 1) && (m.writeLatency == 1) && (m.readLatency == 0) &&\n (m.readwriters.isEmpty) && (m.writers.size <= 1)\n }\n\n def grabMemConnects(s: Statement): Seq[(String, Expression)] = s match {\n case b: Block => b.stmts flatMap grabMemConnects\n case c: Connect if firrtl.Utils.kind(c.loc) == firrtl.MemKind => Seq(emitExpr(c.loc) -> c.expr)\n case _ => Seq()\n }\n\n def dropMemConnects(memsToReplace: Set[String])(s: Statement): Statement = {\n val noConnects = s match {\n case Connect(_,WSubField(WSubField(WRef(name: String,_,_,_),_,_,_),_,_,_),_) => {\n if (memsToReplace.contains(name)) EmptyStmt\n else s\n }\n case _ => s\n }\n noConnects map dropMemConnects(memsToReplace)\n }\n\n // replace mem def's and mem reads\n def replaceMemsStmt(memsToTypes: Map[String,Type])(s: Statement): Statement = {\n val memsReplaced = s match {\n case mem: DefMemory if (memsToTypes.contains(mem.name)) => {\n // FUTURE: what is clock for a mem? assuming it is based on surrounding context\n DefRegister(mem.info, mem.name, mem.dataType, WRef(\"clock\", ClockType, PortKind),\n UIntLiteral(0,IntWidth(1)), UIntLiteral(0,IntWidth(1)))\n }\n case _ => s\n }\n memsReplaced map replaceMemsStmt(memsToTypes) map replaceMemsExpr(memsToTypes)\n }\n\n def replaceMemsExpr(memsToTypes: Map[String,Type])(e: Expression): Expression = {\n val replaced = e match {\n case WSubField(WSubField(WRef(name: String, _, _, f: Flow),_,_,_),\"data\",_,_) => {\n if (memsToTypes.contains(name)) WRef(name, memsToTypes(name), firrtl.RegKind, f)\n else e\n }\n case _ => e\n }\n replaced map replaceMemsExpr(memsToTypes)\n }\n\n // insert reg write muxes\n def generateRegUpdates(memsToReplace: Seq[DefMemory], body: Statement): Seq[Statement] = {\n val memConnects = grabMemConnects(body).toMap\n", "right_context": " memsWithWrites flatMap { mem => mem.writers map { writePortName => {\n val selfRef = WRef(mem.name, mem.dataType, firrtl.RegKind, firrtl.DuplexFlow)\n val enSig = memConnects(s\"${mem.name}.$writePortName.en\")\n val wrDataSig = memConnects(s\"${mem.name}.$writePortName.data\")\n val wrEnableMux = Mux(enSig, wrDataSig, selfRef, mem.dataType)\n Connect(NoInfo, selfRef, wrEnableMux)\n }}}\n }\n\n def memReplaceModule(m: Module): Module = {\n val allMems = essent.Extract.findInstancesOf[DefMemory](m.body)\n // FUTURE: need to explicitly handle read enables?\n val singleElementMems = allMems filter memHasRightParams\n if (singleElementMems.isEmpty) m\n else {\n val memNamesToReplace = (singleElementMems map { _.name }).toSet\n val memConnectsRemoved = squashEmpty(dropMemConnects(memNamesToReplace)(m.body))\n val memsToTypes = (singleElementMems map { mem => (mem.name, mem.dataType)}).toMap\n val memsReplaced = replaceMemsStmt(memsToTypes)(memConnectsRemoved)\n val regUpdateStmts = generateRegUpdates(singleElementMems, m.body)\n val newBlock = Block(Seq(memsReplaced) ++ regUpdateStmts)\n m.copy(body = newBlock)\n }\n }\n\n def run(c: Circuit): Circuit = {\n val modulesx = c.modules.map {\n case m: ExtModule => m\n case m: Module => memReplaceModule(m)\n }\n Circuit(c.info, modulesx, c.main)\n }\n}", "groundtruth": " val memsWithWrites = memsToReplace filter { _.writers.nonEmpty }\n", "crossfile_context": ""}
{"task_id": "essent", "path": "essent/src/test/scala/ReplaceRsvdKeyTest.scala", "left_context": "package essent\nimport org.scalatest.flatspec.AnyFlatSpec\nimport essent.passes.ReplaceRsvdKeywords\nimport firrtl.CircuitState\nimport firrtl.options.Dependency\n\nimport java.io.{File, FileWriter}\nimport scala.io.Source\n\nclass ReplaceRsvdKeyTest extends AnyFlatSpec{\n \"Mypass\" should \"Replace all reserve keyword\" in {\n val sourceReader = Source.fromURL(getClass.getResource(\"/ReplacedRsvdKey.fir\"))\n val circuit = firrtl.Parser.parse(sourceReader.getLines(), firrtl.Parser.IgnoreInfo)\n sourceReader.close()\n val deps = firrtl.stage.Forms.LowFormOptimized ++ Seq(Dependency(ReplaceRsvdKeywords))\n val firrtlCompiler = new firrtl.stage.transforms.Compiler(deps)\n", "right_context": "\n", "groundtruth": " val resultState = firrtlCompiler.execute(CircuitState(circuit, Seq()))\n val CorrectReader = Source.fromURL(getClass.getResource(\"/ReplacedRsvdKey_correct.fir\"))\n val correctString = CorrectReader.getLines().mkString(\"\\n\")\n assert(correctString == resultState.circuit.serialize)\n", "crossfile_context": ""}
{"task_id": "essent", "path": "essent/src/test/scala/StatementGraphTest.scala", "left_context": "package essent\n\nimport firrtl.ir._\n\nimport org.scalatest.flatspec.AnyFlatSpec\n\nclass StatementGraphSpec extends AnyFlatSpec {\n \"A NamedGraph\" should \"grow as necessary for new edges\" in {\n val sg = new StatementGraph\n sg.addEdge(\"alpha\", \"beta\")\n assertResult(0) { sg.numValidNodes() }\n assertResult(2) { sg.numNodeRefs() }\n assertResult(1) { sg.numEdges() }\n sg.addEdge(\"gamma\", \"zeta\")\n assertResult(0) { sg.numValidNodes() }\n assertResult(4) { sg.numNodeRefs() }\n assertResult(2) { sg.numEdges() }\n }\n\n it should \"not add duplicate edges (if requested)\" in {\n val sg = new StatementGraph\n sg.addEdgeIfNew(\"alpha\", \"beta\")\n assertResult(0) { sg.numValidNodes() }\n", "right_context": " assertResult(1) { sg.numEdges() }\n sg.addEdgeIfNew(\"alpha\", \"beta\")\n assertResult(0) { sg.numValidNodes() }\n\n assertResult(1) { sg.numEdges() }\n }\n\n it should \"be buildable from hyperedges\" in {\n val sg = new StatementGraph\n sg.addStatementNode(\"child\", Seq(\"parent0\",\"parent1\"))\n assertResult(1) { sg.numValidNodes() }\n assertResult(3) { sg.numNodeRefs() }\n assertResult(2) { sg.numEdges() }\n assert(sg.idToStmt(sg.nameToID(\"child\")) == EmptyStmt)\n sg.addStatementNode(\"sibling\", Seq(\"parent0\",\"parent1\"), Block(Seq()))\n assertResult(2) { sg.numValidNodes() }\n assertResult(4) { sg.numNodeRefs() }\n assertResult(4) { sg.numEdges() }\n assert(sg.idToStmt(sg.nameToID(\"sibling\")) == Block(Seq()))\n }\n\n it should \"fill in idToStmts as necessary with EmptyStmt\" in {\n val sg = new StatementGraph\n sg.addEdge(\"alpha\", \"beta\")\n assertResult(EmptyStmt)(sg.idToStmt(sg.nameToID(\"alpha\")))\n sg.addStatementNode(\"sibling\", Seq(\"parent0\",\"parent1\"), Block(Seq()))\n assertResult(EmptyStmt)(sg.idToStmt(sg.nameToID(\"parent1\")))\n }\n\n it should \"test safety or merges (whether acyclic)\" in {\n val sg = new StatementGraph\n sg.addEdge(\"a\",\"b\")\n sg.addEdge(\"b\",\"c\")\n assert( sg.mergeIsAcyclic(\"a\",\"b\"))\n assert( sg.mergeIsAcyclic(\"b\",\"a\"))\n assert(!sg.mergeIsAcyclic(\"a\",\"c\"))\n assert(!sg.mergeIsAcyclic(\"c\",\"a\"))\n sg.addEdge(\"a\",\"c\")\n assert(!sg.mergeIsAcyclic(\"a\",\"c\"))\n sg.addEdge(\"x\",\"y\")\n assert( sg.mergeIsAcyclic(\"a\",\"x\"))\n assert( sg.mergeIsAcyclic(\"y\",\"a\"))\n }\n\n it should \"be able to merge Statements\" in {\n val sg = new StatementGraph\n sg.addStatementNode(\"b\", Seq(\"a\"), Attach(NoInfo,Seq()))\n sg.addStatementNode(\"c\", Seq(\"b\",\"a\"), Attach(NoInfo,Seq()))\n sg.mergeStmtsMutably(sg.nameToID(\"b\"), Seq(sg.nameToID(\"c\")), Block(Seq()))\n assertResult(Block(Seq()))(sg.idToStmt(sg.nameToID(\"b\")))\n assertResult(EmptyStmt)(sg.idToStmt(sg.nameToID(\"c\")))\n assert( sg.validNodes(sg.nameToID(\"b\")))\n assert(!sg.validNodes(sg.nameToID(\"c\")))\n // trusts Graph's test for mergeNodesMutably\n }\n\n it should \"be able to detect if Statement type anywhere in graph\" in {\n val sg = new StatementGraph\n sg.addStatementNode(\"child\", Seq(\"parent0\",\"parent1\"), Block(Seq()))\n assert( sg.containsStmtOfType[Block]())\n assert(!sg.containsStmtOfType[DefWire]())\n }\n\n it should \"find IDs of requested Statement type\" in {\n val sg = new StatementGraph\n sg.addStatementNode(\"child\", Seq(\"parent0\",\"parent1\"), Block(Seq()))\n assertResult(Seq(sg.nameToID(\"child\"))) { sg.findIDsOfStmtOfType[Block]() }\n assertResult(Seq()) { sg.findIDsOfStmtOfType[DefWire]() }\n }\n\n it should \"collect valid statements from subset\" in {\n val sg = new StatementGraph\n sg.addStatementNode(\"b\", Seq(\"a\"), Attach(NoInfo,Seq()))\n sg.addStatementNode(\"c\", Seq(\"b\",\"a\"), Block(Seq()))\n val goal = Seq(Attach(NoInfo,Seq()), Block(Seq()))\n val result = sg.collectValidStmts(Seq(sg.nameToID(\"b\"), sg.nameToID(\"c\")))\n assertResult(goal.toSet)(result.toSet)\n }\n\n it should \"be able to handle a 1 node graph with no edges\" in {\n val stmt = DefNode(NoInfo,\"dummy\",UIntLiteral(0,IntWidth(1)))\n val sg = StatementGraph(Seq(stmt))\n assertResult(Seq(stmt)) { sg.stmtsOrdered() }\n }\n}\n", "groundtruth": " assertResult(2) { sg.numNodeRefs() }\n", "crossfile_context": ""}
{"task_id": "tree-core-cpu", "path": "tree-core-cpu/rtl/TreeCoreL2/tc_l2/src/main/scala/common/InstConfig.scala", "left_context": "package treecorel2\n\nimport chisel3._\nimport chisel3.util._\n\ntrait IOConfig {\n val XLen = 64\n val InstLen = 32\n val RegfileLen = 5\n val RegfileNum = 1 << RegfileLen\n val ISALen = 6\n // mem\n val MaskLen = 8\n val LDSize = 3\n // branch prediction\n val GHRLen = 5\n val PHTSize = 1 << GHRLen\n val BTBIdxLen = 5\n val BTBPcLen = XLen - BTBIdxLen\n val BTBTgtLen = XLen\n val BTBSize = 1 << BTBIdxLen\n}\n\ntrait InstConfig extends IOConfig {\n val SoCEna = false\n val CacheEna = false\n\n val FlashStartAddr = \"h0000000030000000\".U(XLen.W)\n val SimStartAddr = \"h0000000080000000\".U(XLen.W)\n val DiffStartBaseAddr = \"h0000000080000000\".U(XLen.W)\n val SoCStartBaseAddr = \"h0000000000000000\".U(XLen.W)\n val DifftestAddrMask = \"hfffffffffffffff8\".U(XLen.W)\n val SoCAddrMask = \"hffffffffffffffff\".U(XLen.W)\n val InstSoCRSize = 2.U\n val InstDiffRSize = 3.U\n val DiffRWSize = 3.U\n\n val NOPInst = 0x13.U\n // inst type\n // nop is equal to [addi x0, x0, 0], so the oper is same as 'addi' inst\n val InstTypeLen = 3\n val nopInstType = 2.U(InstTypeLen.W)\n val rInstType = 1.U(InstTypeLen.W)\n val iInstType = 2.U(InstTypeLen.W)\n val sInstType = 3.U(InstTypeLen.W)\n val bInstType = 4.U(InstTypeLen.W)\n", "right_context": " val jInstType = 6.U(InstTypeLen.W)\n val wtRegTrue = true.B\n val wtRegFalse = false.B\n // inst\n val InstValLen = 6\n val instADDI = 0.U(InstValLen.W)\n val instADDIW = 1.U(InstValLen.W)\n val instSLTI = 2.U(InstValLen.W)\n val instSLTIU = 3.U(InstValLen.W)\n val instANDI = 4.U(InstValLen.W)\n val instORI = 5.U(InstValLen.W)\n val instXORI = 6.U(InstValLen.W)\n val instSLLI = 7.U(InstValLen.W)\n val instSLLIW = 8.U(InstValLen.W)\n val instSRLI = 9.U(InstValLen.W)\n val instSRLIW = 10.U(InstValLen.W)\n val instSRAI = 11.U(InstValLen.W)\n val instSRAIW = 12.U(InstValLen.W)\n val instLUI = 13.U(InstValLen.W)\n val instAUIPC = 14.U(InstValLen.W)\n val instADD = 15.U(InstValLen.W)\n val instADDW = 16.U(InstValLen.W)\n val instSLT = 17.U(InstValLen.W)\n val instSLTU = 18.U(InstValLen.W)\n val instAND = 19.U(InstValLen.W)\n val instOR = 20.U(InstValLen.W)\n val instXOR = 21.U(InstValLen.W)\n val instSLL = 22.U(InstValLen.W)\n val instSLLW = 23.U(InstValLen.W)\n val instSRL = 24.U(InstValLen.W)\n val instSRLW = 25.U(InstValLen.W)\n val instSUB = 26.U(InstValLen.W)\n val instSUBW = 27.U(InstValLen.W)\n val instSRA = 28.U(InstValLen.W)\n val instSRAW = 29.U(InstValLen.W)\n val instNOP = 30.U(InstValLen.W)\n val instJAL = 31.U(InstValLen.W)\n val instJALR = 32.U(InstValLen.W)\n val instBEQ = 33.U(InstValLen.W)\n val instBNE = 34.U(InstValLen.W)\n val instBLT = 35.U(InstValLen.W)\n val instBLTU = 36.U(InstValLen.W)\n val instBGE = 37.U(InstValLen.W)\n val instBGEU = 38.U(InstValLen.W)\n val instLB = 39.U(InstValLen.W)\n val instLBU = 40.U(InstValLen.W)\n val instLH = 41.U(InstValLen.W)\n val instLHU = 42.U(InstValLen.W)\n val instLW = 43.U(InstValLen.W)\n val instLWU = 44.U(InstValLen.W)\n val instLD = 45.U(InstValLen.W)\n val instSB = 46.U(InstValLen.W)\n val instSH = 47.U(InstValLen.W)\n val instSW = 48.U(InstValLen.W)\n val instSD = 49.U(InstValLen.W)\n val instCSRRW = 50.U(InstValLen.W)\n val instCSRRS = 51.U(InstValLen.W)\n val instCSRRC = 52.U(InstValLen.W)\n val instCSRRWI = 53.U(InstValLen.W)\n val instCSRRSI = 54.U(InstValLen.W)\n val instCSRRCI = 55.U(InstValLen.W)\n val instECALL = 56.U(InstValLen.W)\n val instMRET = 57.U(InstValLen.W)\n val instFENCE = 58.U(InstValLen.W)\n val instFENCE_I = 59.U(InstValLen.W)\n val instCUST = 60.U(InstValLen.W)\n\n // cache\n val NWay = 4\n val NBank = 4\n val NSet = 32\n val CacheLineSize = XLen * NBank\n val ICacheSize = NWay * NSet * CacheLineSize\n val DCacheSize = NWay * NSet * CacheLineSize\n\n // clint\n val ClintBaseAddr = 0x02000000.U(XLen.W)\n val ClintBoundAddr = 0x0200bfff.U(XLen.W)\n val MSipOffset = 0x0.U(XLen.W)\n val MTimeOffset = 0xbff8.U(XLen.W)\n val MTimeCmpOffset = 0x4000.U(XLen.W)\n // csr addr\n val CSRAddrLen = 12\n val mhartidAddr = 0xf14.U(CSRAddrLen.W)\n val mstatusAddr = 0x300.U(CSRAddrLen.W)\n val mieAddr = 0x304.U(CSRAddrLen.W)\n val mtvecAddr = 0x305.U(CSRAddrLen.W)\n val mscratchAddr = 0x340.U(CSRAddrLen.W)\n val mepcAddr = 0x341.U(CSRAddrLen.W)\n val mcauseAddr = 0x342.U(CSRAddrLen.W)\n val mipAddr = 0x344.U(CSRAddrLen.W)\n val mcycleAddr = 0xb00.U(CSRAddrLen.W)\n val medelegAddr = 0x302.U(CSRAddrLen.W)\n val timeCause = \"h8000_0000_0000_0007\".U(XLen.W)\n val ecallCause = \"h0000_0000_0000_000b\".U(XLen.W)\n\n // special inst\n val customInst = \"h0000007b\".U(InstLen.W)\n val haltInst = \"h0000006b\".U(InstLen.W)\n}\n", "groundtruth": " val uInstType = 5.U(InstTypeLen.W)\n", "crossfile_context": ""}
{"task_id": "tree-core-cpu", "path": "tree-core-cpu/rtl/TreeCoreL2/tc_l2/src/main/scala/core/ex/ALU.scala", "left_context": "package treecorel2\n\nimport chisel3._\nimport chisel3.util._\n\nclass ALU extends Module with InstConfig {\n val io = IO(new Bundle {\n val isa = Input(UInt(InstValLen.W))\n val src1 = Input(UInt(XLen.W))\n val src2 = Input(UInt(XLen.W))\n val imm = Input(UInt(XLen.W))\n val res = Output(UInt(XLen.W))\n })\n\n io.res := MuxLookup(\n io.isa,\n 0.U(XLen.W),\n Seq(\n instADDI -> (io.src1 + io.imm),\n instADD -> (io.src1 + io.src2),\n instLUI -> (io.imm),\n instSUB -> (io.src1 - io.src2),\n instADDIW -> SignExt((io.src1 + io.imm)(31, 0), 64),\n instADDW -> SignExt((io.src1 + io.src2)(31, 0), 64),\n instSUBW -> SignExt((io.src1 - io.src2)(31, 0), 64),\n instANDI -> (io.src1 & io.imm),\n instAND -> (io.src1 & io.src2),\n instORI -> (io.src1 | io.imm),\n instOR -> (io.src1 | io.src2),\n instXORI -> (io.src1 ^ io.imm),\n instXOR -> (io.src1 ^ io.src2),\n instSLT -> Mux(io.src1.asSInt < io.src2.asSInt, 1.U(XLen.W), 0.U(XLen.W)),\n instSLTI -> Mux(io.src1.asSInt < io.imm.asSInt, 1.U(XLen.W), 0.U(XLen.W)),\n", "right_context": " instSRAI -> (io.src1.asSInt >> io.imm(5, 0)).asUInt,\n instSLLW -> SignExt((io.src1 << io.src2(4, 0))(31, 0), 64),\n instSRLW -> SignExt((io.src1(31, 0) >> io.src2(4, 0)), 64),\n instSRAW -> SignExt((io.src1(31, 0).asSInt >> io.src2(4, 0)).asUInt, 64),\n instSLLIW -> SignExt((io.src1 << io.imm(4, 0))(31, 0), 64),\n instSRLIW -> SignExt((io.src1(31, 0) >> io.imm(4, 0)), 64),\n instSRAIW -> SignExt((io.src1(31, 0).asSInt >> io.imm(4, 0)).asUInt, 64)\n )\n )\n}\n", "groundtruth": " instSLTU -> Mux(io.src1.asUInt < io.src2.asUInt, 1.U(XLen.W), 0.U(XLen.W)),\n instSLTIU -> Mux(io.src1.asUInt < io.imm.asUInt, 1.U(XLen.W), 0.U(XLen.W)),\n instSLL -> (io.src1 << io.src2(5, 0))(63, 0),\n instSRL -> (io.src1 >> io.src2(5, 0)),\n", "crossfile_context": ""}
{"task_id": "tree-core-cpu", "path": "tree-core-cpu/rtl/TreeCoreL2/tc_l2/src/main/scala/core/ex/EXU.scala", "left_context": "package treecorel2\n\nimport chisel3._\nimport chisel3.util._\n\nclass EXU extends Module with InstConfig {\n val io = IO(new Bundle {\n val globalEn = Input(Bool())\n val mtip = Input(Bool())\n val stall = Output(Bool())\n val id2ex = Flipped(new ID2EXIO)\n val bypassMem = Flipped(new WBDATAIO)\n val bypassWb = Flipped(new WBDATAIO)\n val ex2mem = new EX2MEMIO\n val nxtPC = new NXTPCIO\n val branchInfo = new BRANCHIO\n })\n\n protected val exReg = RegEnable(io.id2ex, WireInit(0.U.asTypeOf(new ID2EXIO())), io.globalEn)\n protected val valid = exReg.valid\n protected val inst = exReg.inst\n protected val pc = exReg.pc\n protected val branIdx = exReg.branIdx\n protected val predTaken = exReg.predTaken\n protected val isa = exReg.isa\n", "right_context": "\n // handle bypass signal\n protected val bypassMemSrc1En = io.bypassMem.wen && (rs1 === io.bypassMem.wdest) && (rs1 =/= 0.U)\n protected val bypassMemSrc2En = io.bypassMem.wen && (rs2 === io.bypassMem.wdest) && (rs2 =/= 0.U)\n protected val bypassWbSrc1En = io.bypassWb.wen && (rs1 === io.bypassWb.wdest) && (rs1 =/= 0.U)\n protected val bypassWbSrc2En = io.bypassWb.wen && (rs2 === io.bypassWb.wdest) && (rs2 =/= 0.U)\n protected val src1 = Mux(bypassMemSrc1En, io.bypassMem.data, Mux(bypassWbSrc1En, io.bypassWb.data, exReg.src1))\n protected val src2 = Mux(bypassMemSrc2En, io.bypassMem.data, Mux(bypassWbSrc2En, io.bypassWb.data, exReg.src2))\n\n protected val alu = Module(new ALU)\n alu.io.isa := isa\n alu.io.imm := imm\n alu.io.src1 := src1\n alu.io.src2 := src2\n protected val aluRes = alu.io.res\n\n // protected val mdu = Module(new MDU)\n // mdu.io.isa := isa\n // mdu.io.src1 := src1\n // mdu.io.src2 := src2\n // protected val mduRes = mdu.io.res\n\n // protected val agu = Module(new AGU)\n // agu.io.isa := isa\n // agu.io.src1 := src1\n // agu.io.src2 := src2\n // protected val aguRes = agu.io.res\n\n protected val beu = Module(new BEU)\n beu.io.isa := isa\n beu.io.imm := imm\n beu.io.src1 := src1\n beu.io.src2 := src2\n beu.io.pc := pc\n beu.io.branIdx := branIdx\n beu.io.branchInfo <> io.branchInfo\n protected val branch = beu.io.branch\n protected val tgt = beu.io.tgt\n\n protected val link = SignExt(((isa === instJAL) | (isa === instJALR)).asUInt, 64) & (pc + 4.U)\n protected val auipc = SignExt((isa === instAUIPC).asUInt, 64) & (pc + imm)\n\n protected val csrReg = Module(new CSRReg)\n protected val csrData = csrReg.io.data\n protected val timeIntrEn = csrReg.io.timeIntrEn\n protected val ecallEn = csrReg.io.ecallEn\n csrReg.io.globalEn := io.globalEn\n csrReg.io.pc := pc\n csrReg.io.inst := Mux(valid, inst, NOPInst)\n csrReg.io.src := src1\n csrReg.io.mtip := io.mtip\n\n io.nxtPC.trap := valid && (timeIntrEn || ecallEn)\n io.nxtPC.mtvec := csrReg.io.csrState.mtvec\n io.nxtPC.mret := valid && (isa === instMRET)\n io.nxtPC.mepc := csrReg.io.csrState.mepc\n // (pred, fact)--->(NT, T) or (T, NT)\n protected val predNTfactT = branch && !predTaken\n protected val predTfactNT = !branch && predTaken\n io.nxtPC.branch := valid && (predNTfactT || predTfactNT)\n io.nxtPC.tgt := Mux(valid && predNTfactT, tgt, Mux(valid && predTfactNT, pc + 4.U, 0.U(XLen.W)))\n io.stall := valid && (io.nxtPC.branch || timeIntrEn || ecallEn || (isa === instMRET))\n\n io.ex2mem.valid := Mux(timeIntrEn, false.B, valid)\n io.ex2mem.inst := inst\n io.ex2mem.pc := pc\n io.ex2mem.branIdx := branIdx\n io.ex2mem.predTaken := predTaken\n io.ex2mem.isa := isa\n io.ex2mem.src1 := src1\n io.ex2mem.src2 := src2\n io.ex2mem.imm := imm\n io.ex2mem.wen := wen\n io.ex2mem.wdest := wdest\n io.ex2mem.aluRes := aluRes\n io.ex2mem.branch := branch\n io.ex2mem.tgt := tgt\n io.ex2mem.link := link\n io.ex2mem.auipc := auipc\n io.ex2mem.csrData := csrData\n io.ex2mem.timeIntrEn := timeIntrEn\n io.ex2mem.ecallEn := ecallEn\n io.ex2mem.csr.mstatus := csrReg.io.csrState.mstatus\n io.ex2mem.csr.mcause := csrReg.io.csrState.mcause\n io.ex2mem.csr.mepc := csrReg.io.csrState.mepc\n io.ex2mem.csr.mie := csrReg.io.csrState.mie\n io.ex2mem.csr.mscratch := csrReg.io.csrState.mscratch\n io.ex2mem.csr.medeleg := csrReg.io.csrState.medeleg\n io.ex2mem.csr.mtvec := csrReg.io.csrState.mtvec\n io.ex2mem.csr.mhartid := 0.U\n io.ex2mem.csr.mcycle := 0.U\n io.ex2mem.csr.mip := 0.U\n}\n", "groundtruth": " protected val imm = exReg.imm\n protected val wen = exReg.wen\n protected val rs1 = exReg.inst(19, 15)\n", "crossfile_context": ""}
{"task_id": "tree-core-cpu", "path": "tree-core-cpu/rtl/TreeCoreL2/tc_l2/src/main/scala/core/ex/Multiplier.scala", "left_context": "package treecorel2\n\nimport chisel3._\nimport chisel3.util._\n\nclass Multiplier(val len: Int, val latency: Int = 0) extends Module {\n val io = IO(new Bundle {\n val en = Input(Bool())\n val flush = Input(Bool())\n val done = Output(Bool())\n val src1 = Input(UInt(len.W))\n val src2 = Input(UInt(len.W))\n val res = Output(UInt((len * 2).W))\n })\n\n require(latency >= 0)\n\n protected val res = io.src1 * io.src2\n\n def generatePipe(en: Bool, data: UInt, latency: Int): (Bool, UInt) = {\n if (latency == 0) {\n (en, data)\n", "right_context": " io.res := data\n}\n", "groundtruth": " } else {\n val done = RegNext(Mux(io.flush, false.B, en), false.B)\n val bits = RegEnable(data, en)\n generatePipe(done, bits, latency - 1)\n }\n", "crossfile_context": ""}
{"task_id": "tree-core-cpu", "path": "tree-core-cpu/rtl/TreeCoreL2/tc_l2/src/main/scala/core/if/Cache.scala", "left_context": "package treecorel2\n\nimport chisel3._\nimport chisel3.util._\n\n", "right_context": "\nclass CacheCoreIO extends Bundle {\n val abort = Input(Bool())\n val req = Flipped(Valid(new CacheReqIO))\n val resp = Valid(new CacheRespIO)\n}\n\nclass CacheMemReqIO extends Bundle with InstConfig {\n val id = UInt(4.W)\n val cmd = UInt(4.W)\n val addr = UInt(XLen.W)\n val data = UInt(XLen.W)\n val len = UInt(2.W)\n}\n\nclass CacheMemRespIO extends Bundle with InstConfig {\n val id = UInt(4.W)\n val cmd = UInt(4.W)\n val data = UInt(XLen.W)\n\n}\n\nclass CacheMemIO extends Bundle {\n val req = Decoupled(new CacheMemReqIO)\n val resp = Flipped(Decoupled(new CacheMemRespIO))\n}\n\nclass Cache(val cacheType: String) extends Module with InstConfig {\n val io = IO(new Bundle {\n val core = new CacheCoreIO\n val mem = new CacheMemIO\n })\n}\n", "groundtruth": "class CacheReqIO extends Bundle with InstConfig {\n val addr = UInt(XLen.W)\n val data = UInt(XLen.W) // for write\n val mask = UInt((XLen / 8).W) // for write\n}\n", "crossfile_context": ""}
{"task_id": "tree-core-cpu", "path": "tree-core-cpu/rtl/TreeCoreL2/tc_l2/src/main/scala/port/AXI4IO.scala", "left_context": "package treecorel2\n\nimport chisel3._\nimport chisel3.util._\n\nclass SOCAXI4ARWIO extends Bundle with AXI4Config {\n val addr = Output(UInt(32.W))\n val id = Output(UInt(AxiIdLen.W))\n val len = Output(UInt(AxiLen.W))\n val size = Output(UInt(AxiSizeLen.W))\n val burst = Output(UInt(AxiBurstLen.W))\n}\n\nclass AXI4ARWIO extends SOCAXI4ARWIO {\n override val addr = Output(UInt(XLen.W))\n val prot = Output(UInt(AxiProtLen.W))\n val user = Output(UInt(AxiUserLen.W))\n val lock = Output(Bool())\n val cache = Output(UInt(AxiCacheLen.W))\n val qos = Output(UInt(AxiQosLen.W))\n}\n\nclass SOCAXI4WIO extends Bundle with AXI4Config {\n val data = Output(UInt(XLen.W))\n val strb = Output(UInt(AxiStrb.W))\n val last = Output(Bool())\n}\n\n", "right_context": "\nclass SOCAXI4BIO extends Bundle with AXI4Config {\n val resp = Output(UInt(AxiRespLen.W))\n val id = Output(UInt(AxiIdLen.W))\n}\n\nclass AXI4BIO extends SOCAXI4BIO {\n val user = Output(UInt(AxiUserLen.W))\n}\n\nclass SOCAXI4RIO extends Bundle with AXI4Config {\n val resp = Output(UInt(AxiRespLen.W))\n val data = Output(UInt(XLen.W))\n val last = Output(Bool())\n val id = Output(UInt(AxiIdLen.W))\n}\n\nclass AXI4RIO extends SOCAXI4RIO {\n val user = Output(UInt(AxiUserLen.W))\n}\n\nclass SOCAXI4IO extends Bundle {\n val aw = Decoupled(new SOCAXI4ARWIO)\n val w = Decoupled(new SOCAXI4WIO)\n val b = Flipped(Decoupled(new SOCAXI4BIO))\n val ar = Decoupled(new SOCAXI4ARWIO)\n val r = Flipped(Decoupled(new SOCAXI4RIO))\n}\n\nclass AXI4IO extends SOCAXI4IO {\n override val aw = Decoupled(new AXI4ARWIO)\n override val w = Decoupled(new AXI4WIO)\n override val b = Flipped(Decoupled(new AXI4BIO))\n override val ar = Decoupled(new AXI4ARWIO)\n override val r = Flipped(Decoupled(new AXI4RIO))\n}\n", "groundtruth": "class AXI4WIO extends SOCAXI4WIO {}\n", "crossfile_context": ""}
{"task_id": "tree-core-cpu", "path": "tree-core-cpu/rtl/TreeCoreL2/tc_l2/src/main/scala/port/BRANCHIO.scala", "left_context": "package treecorel2\n\nimport chisel3._\nimport chisel3.util._\n\nclass BRANCHIO extends Bundle with IOConfig {\n val branch = Output(Bool()) // prev inst is a b/j\n val jump = Output(Bool()) // is 'jal' or 'jalr'\n", "right_context": " val tgt = Output(UInt(XLen.W)) // prev branch tgt\n}\n", "groundtruth": " val taken = Output(Bool()) // is prev branch taken\n val idx = Output(UInt(GHRLen.W)) // prev idx of PHT(GHRLen)\n", "crossfile_context": ""}
{"task_id": "tree-core-cpu", "path": "tree-core-cpu/rtl/TreeCoreL2/tc_l2/src/main/scala/port/COREIO.scala", "left_context": "package treecorel2\n\nimport chisel3._\nimport chisel3.util._\n\nclass COREIO extends Bundle {\n", "right_context": "", "groundtruth": " val globalEn = Output(Bool())\n val fetch = Flipped(new IFIO)\n val ld = Flipped(new LDIO)\n val sd = Flipped(new SDIO)\n}\n", "crossfile_context": ""}
{"task_id": "tree-core-cpu", "path": "tree-core-cpu/rtl/TreeCoreL2/tc_l2/src/main/scala/port/IFIO.scala", "left_context": "package treecorel2\n\nimport chisel3._\nimport chisel3.util._\n\n", "right_context": "", "groundtruth": "class IFIO extends Bundle with IOConfig {\n val en = Output(Bool())\n val addr = Output(UInt(XLen.W))\n val data = Input(UInt(InstLen.W))\n}\n", "crossfile_context": ""}
{"task_id": "tree-core-cpu", "path": "tree-core-cpu/rtl/TreeCoreL2/tc_l2/src/main/scala/port/LSIO.scala", "left_context": "package treecorel2\n\nimport chisel3._\nimport chisel3.util._\n\nclass LDIO extends Bundle with IOConfig {\n val en = Output(Bool())\n val addr = Output(UInt(XLen.W))\n val data = Input(UInt(XLen.W))\n val size = Output(UInt(LDSize.W))\n}\n\nclass SDIO extends Bundle with IOConfig {\n val en = Output(Bool())\n", "right_context": "}\n", "groundtruth": " val addr = Output(UInt(XLen.W))\n val data = Output(UInt(XLen.W))\n", "crossfile_context": ""}
{"task_id": "tree-core-cpu", "path": "tree-core-cpu/rtl/TreeCoreL2/tc_l2/src/main/scala/port/WBDATAIO.scala", "left_context": "package treecorel2\n\nimport chisel3._\nimport chisel3.util._\n\n", "right_context": "", "groundtruth": "class WBDATAIO extends Bundle with IOConfig {\n val wen = Output(Bool())\n val wdest = Output(UInt(RegfileLen.W))\n val data = Output(UInt(XLen.W))\n}\n", "crossfile_context": ""}
{"task_id": "rocket_chip_vpu", "path": "rocket_chip_vpu/vpu/src/main/scala/VCompare.scala", "left_context": "// See LICENSE.UCTECHIP for license details.\n// See LICENSE.SZU for license details.\n/************************************************************\n*\n* Filename : VCompare.scala\n* Author : yexc\n* Revision : 2019/04/12\n* Company : UC TECH IP\n* Department : STG\n* Description : compare data\n*\n* io.vsrc1e : input, bundle of vectors, data, SEW relative, operand 2\n* io.vsrc2e : input, bundle of vectors, data, SEW relative, operand 1\n* io.cmpFun : input[CmpFun_SZ-1:0], control, function select\n* io.sign : input, control, show whether operands are signed values or not\n* io.vlmul : input[VLMUL_SZ-1:0], control, vlmul field from vtype CSR\n* io.vCmpOut : output, bundle of vectors, data, elements 1 bit width, compare result\n* io.vMinMaxOut : output, bundle of vectors, data, SEW relative, Min/Max ones between two values \n*\n************************************************************/\npackage vpu\n\nimport chisel3._\nimport chisel3.util._\n\nclass VCompare(params: VPUParams) extends VModule(params) {\n val io = IO(new Bundle {\n // Input\n val vsrc1e = Input(new SEWVec)\n val vsrc2e = Input(new SEWVec)\n val cmpFun = Input(UInt(CmpFun_SZ.W))\n val sign = Input(Bool())\n val vlmul = Input(UInt(VLMUL_SZ.W))\n // Output\n val vCmpOut = Output(new SEW1wVec)\n val vMinMaxOut = Output(new SEWVec)\n }) \n\n def equal(src1: UInt, src2: UInt): Bool = src1 === src2\n", "right_context": " def cmp(src1: UInt, src2: UInt, fun: UInt, sign: Bool): Bool = {\n val equal_wire = Wire(Bool())\n val less_wire = Wire(Bool()) \n val greater_wire = Wire(Bool())\n\n equal_wire := equal(src1, src2)\n less_wire := less(src1, src2, sign)\n greater_wire := Mux(equal_wire, false.B, ~less_wire)\n\n MuxCase(false.B, Array((fun === \"b000\".U) -> equal_wire,\n (fun === \"b001\".U) -> ~equal_wire,\n (fun === \"b010\".U) -> less_wire,\n (fun === \"b011\".U) -> (less_wire | equal_wire), \n (fun === \"b100\".U) -> greater_wire,\n (fun === \"b101\".U) -> less_wire,\n (fun === \"b110\".U) -> greater_wire\n )) \n }\n\n\n // compare bit output\n for(i <- 0 until e8Depth)\n io.vCmpOut.e8(i) := Mux(cmp(io.vsrc2e.e8(i), io.vsrc1e.e8(i), io.cmpFun, io.sign), 1.U, 0.U)\n\n for(i <- 0 until e16Depth)\n io.vCmpOut.e16(i) := Mux(cmp(io.vsrc2e.e16(i), io.vsrc1e.e16(i), io.cmpFun, io.sign), 1.U, 0.U)\n\n for(i <- 0 until e32Depth)\n io.vCmpOut.e32(i) := Mux(cmp(io.vsrc2e.e32(i), io.vsrc1e.e32(i), io.cmpFun, io.sign), 1.U, 0.U)\n\n for(i <- 0 until e64Depth)\n io.vCmpOut.e64(i) := Mux(cmp(io.vsrc2e.e64(i), io.vsrc1e.e64(i), io.cmpFun, io.sign), 1.U, 0.U)\n\n for(i <- 0 until e128Depth)\n io.vCmpOut.e128(i) := Mux(cmp(io.vsrc2e.e128(i), io.vsrc1e.e128(i), io.cmpFun, io.sign), 1.U, 0.U)\n\n for(i <- 0 until e256Depth)\n io.vCmpOut.e256(i) := Mux(cmp(io.vsrc2e.e256(i), io.vsrc1e.e256(i), io.cmpFun, io.sign), 1.U, 0.U)\n\n for(i <- 0 until e512Depth)\n io.vCmpOut.e512(i) := Mux(cmp(io.vsrc2e.e512(i), io.vsrc1e.e512(i), io.cmpFun, io.sign), 1.U, 0.U)\n\n for(i <- 0 until e1024Depth)\n io.vCmpOut.e1024(i) := Mux(cmp(io.vsrc2e.e1024(i), io.vsrc1e.e1024(i), io.cmpFun, io.sign), 1.U, 0.U)\n\n\n\n // select min/max value\n for(i <- 0 until e8Depth)\n io.vMinMaxOut.e8(i) := Mux(io.vCmpOut.e8(i) === 1.U, io.vsrc2e.e8(i), io.vsrc1e.e8(i))\n\n for(i <- 0 until e16Depth)\n io.vMinMaxOut.e16(i) := Mux(io.vCmpOut.e16(i) === 1.U, io.vsrc2e.e16(i), io.vsrc1e.e16(i))\n\n for(i <- 0 until e32Depth)\n io.vMinMaxOut.e32(i) := Mux(io.vCmpOut.e32(i) === 1.U, io.vsrc2e.e32(i), io.vsrc1e.e32(i))\n\n for(i <- 0 until e64Depth)\n io.vMinMaxOut.e64(i) := Mux(io.vCmpOut.e64(i) === 1.U, io.vsrc2e.e64(i), io.vsrc1e.e64(i))\n\n for(i <- 0 until e128Depth)\n io.vMinMaxOut.e128(i) := Mux(io.vCmpOut.e128(i) === 1.U, io.vsrc2e.e128(i), io.vsrc1e.e128(i))\n\n for(i <- 0 until e256Depth)\n io.vMinMaxOut.e256(i) := Mux(io.vCmpOut.e256(i) === 1.U, io.vsrc2e.e256(i), io.vsrc1e.e256(i))\n\n for(i <- 0 until e512Depth)\n io.vMinMaxOut.e512(i) := Mux(io.vCmpOut.e512(i) === 1.U, io.vsrc2e.e512(i), io.vsrc1e.e512(i))\n\n for(i <- 0 until e1024Depth)\n io.vMinMaxOut.e1024(i) := Mux(io.vCmpOut.e1024(i) === 1.U, io.vsrc2e.e1024(i), io.vsrc1e.e1024(i))\n}\n\n\n\n", "groundtruth": " def less(src1: UInt, src2: UInt, sign: Bool): Bool = Mux(sign, src1.asSInt < src2.asSInt, src1 < src2)\r\n", "crossfile_context": ""}
{"task_id": "rocket_chip_vpu", "path": "rocket_chip_vpu/vpu/src/main/scala/VDmemResp.scala", "left_context": "// See LICENSE.UCTECHIP for license details.\n// See LICENSE.SZU for license details.\n/************************************************************\n*\n* Filename : VDmemResp.scala\n* Author : sujy\n* Revision : 2019/06/18\n* Company : UC TECH IP\n* Department : MAG\n* Description : VPU DCache response handling module\n (using finite machine)\n*\n* io.en : input, ...\n* io.din : input[width-1:0], ...\n* io.dout : output[width-1:0], ...\n*\n************************************************************/\npackage vpu\n\nimport chisel3._\nimport chisel3.util._\n\nclass VDmemResp(params: VPUParams, tagBits: Int, addrBits: Int) extends VModule(params) {\n val dataBits = XLEN max FLEN\n val dataBytes = dataBits/8\n val sizeBits = log2Ceil(log2Ceil(dataBytes)+1)\n\n val io = IO(new Bundle{\n val wd = Input(Bool())\n val lumop = Input(UInt(5.W))\n //input, CSR ctrl signals\n val vsew = Input(UInt(VSEW_SZ.W))\n val vlmul = Input(UInt(VLMUL_SZ.W))\n val vl = Input(UInt(XLEN.W)) //decimal\n //input, other ctrl signals\n val vm = Input(UInt(1.W))\n val sign = Input(Bool())\n val majFun = Input(UInt(MajFun_SZ.W))\n val nFields = Input(UInt(NFIELDS_SZ.W))\n //input, DCache response interface\n val respValid = Input(Bool())\n val respTag = Input(UInt(tagBits.W)) //7.W\n val respSize = Input(UInt(sizeBits.W))\n val respHasData = Input(Bool())\n val respData = Input(UInt(dataBits.W)) // XLEN.W\n //input, DCache status signals\n val mEnable = Input(Bool()) //DCache enable flag\n val mDone = Input(Bool()) //DCache data transfer complete flag\n val faultFirst = Input(Bool())\n val stopLoad = Input(Bool())\n val killm = Input(Bool())\n //input, result of last inst\n val vdvs3e = Input(new FullSEWVec)\n// val v0m = Input(new MLENVec)\n val v0e = Input(new FullSEW1wVec)\n \n //output\n val vRecvOver = Output(Bool())\n val vRecvOut = Output(UInt((VLEN*8).W))\n })\n\n\n //construct a FIFO buffer\n class bufferIO extends Bundle{\n val wen = Bool()\n val waddr = UInt(log2Ceil(VLEN).W)\n val wdata = UInt(XLEN.W)\n val raddr = UInt(log2Ceil(VLEN).W)\n val rdata = UInt(XLEN.W)\n }\n \n val elemNumWidth = log2Ceil(VLEN) + 1\n \n val vm = Wire(UInt(1.W))\n val vsew = Wire(UInt(VSEW_SZ.W))\n val vlmul = Wire(UInt(VLMUL_SZ.W))\n val vl = Wire(UInt(XLEN.W)) \n\n vm := Mux(io.lumop === UStrideWhole, 1.U, io.vm)\n vsew := Mux(io.lumop === UStrideWhole, 0.U, io.vsew)\n vlmul := Mux(io.lumop === UStrideWhole, 0.U, io.vlmul)\n vl := Mux(io.lumop === UStrideWhole, (VLEN/8).U, io.vl)\n\n val buf = Wire(new bufferIO)\n val dpram = Mem(VLEN, UInt(XLEN.W))\n val rcnt = RegInit(0.U((elemNumWidth-1).W)) \n\n val isLoad = Wire(Bool())\n val mEnable = Wire(Bool())\n val mDone = Wire(Bool())\n\n val extdData = Wire(UInt(XLEN.W))\n \n// val v0e = Wire(new FullSEW1wVec) // [TODO] can be simplified by using vwidth.io.v0e\n\n val recvData8 = Wire(UInt(8.W))\n val recvData16 = Wire(UInt(16.W))\n val recvData32 = Wire(UInt(32.W))\n val recvData64 = Wire(UInt(64.W))\n val recvOver = Wire(Bool())\n val recvOut = RegInit(0.U((VLEN*8).W)) //output register\n\n \n //--define a finite state machine-\n val s_idle :: s_write :: s_read :: s_done :: Nil = Enum(4)\n val state = RegInit(s_idle)\n \n //--for-SEGLS--------\n val readDone = Wire(Bool())\n val elemNum = RegInit(0.U(elemNumWidth.W))\n val maskIndex = Wire(UInt(log2Ceil(VLEN).W))\n\n\n //--segment-load-configuration----\n if(SEGLS){\n val vlmax = Wire(UInt((elemNumWidth).W))\n val eleOffset = Wire(UInt((log2Ceil(VLEN)+1).W))\n val elemCnt = RegInit(0.U((elemNumWidth-1).W))\n val maskCnt = RegInit(0.U((elemNumWidth-1).W)) \n val remainReg = RegInit(0.U(3.W))\n val isValid = Wire(Bool()) // see whether data from buffer should be written to receive reg or not\n\n vlmax := 1.U << (log2Ceil(VLEN).U + vlmul - vsew - 3.U)\n eleOffset := VLEN.U >> (vsew + 3.U - vlmul)\n readDone := remainReg === 0.U && elemCnt === 0.U\n isValid := rcnt - (eleOffset * remainReg) < vl\n\n val nFieldsReal = Wire(UInt(NFIELDS_SZ.W))\n nFieldsReal := Mux(io.majFun === IsAMO, 0.U, io.nFields)\n// elemNum := (vl * (nFieldsReal +& 1.U))(elemNumWidth-1, 0) //origin\n elemNum := (vlmax * (nFieldsReal +& 1.U))(elemNumWidth-1, 0) \n\n maskIndex := Mux(nFieldsReal === 0.U, buf.raddr, maskCnt)\n\n when(state === s_write){\n elemCnt := vlmax - 1.U\n maskCnt := vl - 1.U\n remainReg := nFieldsReal\n }\n when(state === s_read ){\n elemCnt := Mux(elemCnt > 0.U, elemCnt - 1.U, vlmax - 1.U)\n maskCnt := Mux(elemCnt >= vl, maskCnt, Mux((maskCnt > 0.U), maskCnt - 1.U, vl - 1.U))\n remainReg := Mux(elemCnt === 0.U, remainReg - 1.U, remainReg)\n }\n \n recvData8 := Mux(isValid, Mux(io.v0e.e8(maskIndex).toBool , buf.rdata(7,0) , io.vdvs3e.e8(buf.raddr) ), 0.U)\n recvData16 := Mux(isValid, Mux(io.v0e.e16(maskIndex).toBool, buf.rdata(15,0), io.vdvs3e.e16(buf.raddr)), 0.U)\n recvData32 := Mux(isValid, Mux(io.v0e.e32(maskIndex).toBool, buf.rdata(31,0), io.vdvs3e.e32(buf.raddr)), 0.U)\n if(XLEN == 64 && ELEN >= 64)\n recvData64 := Mux(isValid, Mux(io.v0e.e64(maskIndex).toBool, buf.rdata(63,0), io.vdvs3e.e64(buf.raddr)), 0.U)\n else\n recvData64 := 0.U\n }\n else{\n readDone := rcnt === 0.U\n elemNum := vl(elemNumWidth-1, 0)\n maskIndex := buf.raddr\n\n recvData8 := Mux(io.v0e.e8(maskIndex).toBool , buf.rdata(7,0) , io.vdvs3e.e8(buf.raddr) )\n recvData16 := Mux(io.v0e.e16(maskIndex).toBool, buf.rdata(15,0), io.vdvs3e.e16(buf.raddr))\n recvData32 := Mux(io.v0e.e32(maskIndex).toBool, buf.rdata(31,0), io.vdvs3e.e32(buf.raddr))\n if(XLEN == 64 && ELEN >= 64)\n recvData64 := Mux(io.v0e.e64(maskIndex).toBool, buf.rdata(63,0), io.vdvs3e.e64(buf.raddr))\n else\n recvData64 := 0.U\n }\n\n //--extend received data----------\n extdData := MuxCase(0.U, Array() \n ++ Array((io.respSize === 0.U) -> Mux(io.sign,\n Cat(Fill(XLEN-8, io.respData(7)), io.respData(7,0)),\n Cat(0.U((XLEN-8).W) , io.respData(7,0))),\n (io.respSize === 1.U) -> Mux(io.sign,\n Cat(Fill(XLEN-16, io.respData(15)), io.respData(15,0)),\n Cat(0.U((XLEN-16).W) , io.respData(15,0))))\n ++ (if(XLEN == 32)\n Array((io.respSize === 2.U) -> io.respData(31,0))\n else if(XLEN == 64 && ELEN >= 64) \n Array((io.respSize === 2.U) -> Mux(io.sign, \n Cat(Fill(XLEN-32, io.respData(31)), io.respData(31,0)), \n Cat(0.U((XLEN-32).W) , io.respData(31,0))),\n (io.respSize === 3.U) -> io.respData(63,0))\n else Nil))\n\n\n\n //--buffer initialization---------\n buf.wen := isLoad && io.respValid && io.respHasData && vl =/= 0.U && !io.stopLoad && !io.faultFirst\n buf.waddr := io.respTag\n buf.wdata := extdData\n buf.raddr := rcnt\n buf.rdata := 0.U\n recvOver := false.B\n\n isLoad := io.majFun === IsLoad || (io.majFun === IsAMO && io.wd)\n mEnable := isLoad && io.mEnable //valid only if current inst is 'load'\n mDone := isLoad && io.mDone //valid only if current inst is 'load'\n\n\n //--buffer controller-------------\n switch(state){\n is(s_idle){ \n when(io.killm || io.faultFirst)\n { state := s_idle }\n .elsewhen(io.majFun === IsAMO && !io.wd)\n { state := s_idle } \n .elsewhen(vl =/= 0.U && mEnable || (io.majFun === IsAMO && io.wd))\n", "right_context": " }\n is(s_write){ \n when(io.killm)\n { state := s_idle }\n .elsewhen(mDone || io.stopLoad) \n { state := s_read } \n }\n is(s_read){ \n when(io.killm)\n { state := s_idle }\n .elsewhen(readDone) \n { state := s_done } \n }\n is(s_done) { state := s_idle }\n }\n\n when(state === s_idle){\n recvOut := 0.U\n }\n when(state === s_write) { \n rcnt := elemNum - 1.U \n when(buf.wen) { dpram(buf.waddr) := buf.wdata } \n }\n when(state === s_read) { \n rcnt := Mux(rcnt === 0.U, elemNum - 1.U, rcnt - 1.U)\n buf.rdata := dpram(buf.raddr)\n \n recvOut := MuxCase(0.U, Array()\n ++ Array((vsew === 0.U) -> (recvOut << 8 | recvData8 ),\n (vsew === 1.U) -> (recvOut << 16 | recvData16),\n (vsew === 2.U) -> (recvOut << 32 | recvData32))\n ++ (if(XLEN == 64 && ELEN >= 64)\n Array((vsew === 3.U) -> (recvOut << 64 | recvData64))\n else Nil)) \n }\n when(state === s_done){\n recvOver := true.B\n recvOut := 0.U\n }\n\n\n //--output------------------------\n io.vRecvOver := recvOver\n io.vRecvOut := Mux(recvOver, recvOut, 0.U)\n \n}\n", "groundtruth": " { state := s_write } \n", "crossfile_context": ""}
{"task_id": "rocket_chip_vpu", "path": "rocket_chip_vpu/vpu/src/main/scala/VDmemSplit.scala", "left_context": "// See LICENSE.UCTECHIP for license details.\n// See LICENSE.SZU for license details.\n/************************************************************\n*\n* Filename : VDmemSplitSplit.scala\n* Author : liangzh\n* Revision : 2019/06/24\n* Company : UC TECH IP\n* Department : MAG\n* Description : split 8VLEN data to SEW or MLEN width data\n*\n* io.vs2Data : input[8VLEN-1:0], data, to be split\n* io.vdvs3Data : input[8VLEN-1:0], data, to be split\n* io.v0Mask : input[VLEN-1:0], data, to be split\n* io.vs2e : output bundle of vectors, data, split vs2Data into SEW width\n* io.vdvs3e : output bundle of vectors, data, split vdvs3Data into SEW width\n* io.v0m : output bundle of vectors, data, split v0Mask into MLEN width\n*\n************************************************************/\npackage vpu\n\nimport chisel3._\nimport chisel3.util._\n\nclass VDmemSplit(params: VPUParams) extends VModule(params) {\n val io = IO(new Bundle {\n val vs2Data = Input(UInt((8*VLEN).W))\n val vdvs3Data = Input(UInt((8*VLEN).W))\n val v0Mask = Input(UInt(VLEN.W))\n\n val vs2e = Output(new FullSEWVec)\n val vdvs3e = Output(new FullSEWVec)\n\n val v0m = Output(new MLENVec)\n })\n\n", "right_context": " for(i <- 0 until E512Depth) io.vs2e.e512(i) := io.vs2Data(512*(i+1)-1, 512*i)\n for(i <- 0 until E1024Depth) io.vs2e.e1024(i) := io.vs2Data(1024*(i+1)-1, 1024*i)\n//split vdvs3Data into SEW width vectors\n for(i <- 0 until E8Depth) io.vdvs3e.e8(i) := io.vdvs3Data(8*(i+1)-1, 8*i)\n for(i <- 0 until E16Depth) io.vdvs3e.e16(i) := io.vdvs3Data(16*(i+1)-1, 16*i)\n for(i <- 0 until E32Depth) io.vdvs3e.e32(i) := io.vdvs3Data(32*(i+1)-1, 32*i)\n for(i <- 0 until E64Depth) io.vdvs3e.e64(i) := io.vdvs3Data(64*(i+1)-1, 64*i)\n for(i <- 0 until E128Depth) io.vdvs3e.e128(i) := io.vdvs3Data(128*(i+1)-1, 128*i)\n for(i <- 0 until E256Depth) io.vdvs3e.e256(i) := io.vdvs3Data(256*(i+1)-1, 256*i)\n for(i <- 0 until E512Depth) io.vdvs3e.e512(i) := io.vdvs3Data(512*(i+1)-1, 512*i)\n for(i <- 0 until E1024Depth) io.vdvs3e.e1024(i) := io.vdvs3Data(1024*(i+1)-1, 1024*i)\n//split v0Mask into MLEN width vectors\n for(i <- 0 until m1Depth) io.v0m.m1(i) := io.v0Mask(i)\n for(i <- 0 until m2Depth) io.v0m.m2(i) := io.v0Mask(2*i)\n for(i <- 0 until m4Depth) io.v0m.m4(i) := io.v0Mask(4*i)\n for(i <- 0 until m8Depth) io.v0m.m8(i) := io.v0Mask(8*i)\n for(i <- 0 until m16Depth) io.v0m.m16(i) := io.v0Mask(16*i)\n for(i <- 0 until m32Depth) io.v0m.m32(i) := io.v0Mask(32*i)\n for(i <- 0 until m64Depth) io.v0m.m64(i) := io.v0Mask(64*i)\n for(i <- 0 until m128Depth) io.v0m.m128(i) := io.v0Mask(128*i)\n for(i <- 0 until m256Depth) io.v0m.m256(i) := io.v0Mask(256*i)\n for(i <- 0 until m512Depth) io.v0m.m512(i) := io.v0Mask(512*i)\n for(i <- 0 until m1024Depth) io.v0m.m1024(i) := io.v0Mask(1024*i)\n}\n", "groundtruth": "//split vs2Data into SEW width vectors\n for(i <- 0 until E8Depth) io.vs2e.e8(i) := io.vs2Data(8*(i+1)-1, 8*i)\n for(i <- 0 until E16Depth) io.vs2e.e16(i) := io.vs2Data(16*(i+1)-1, 16*i)\n for(i <- 0 until E32Depth) io.vs2e.e32(i) := io.vs2Data(32*(i+1)-1, 32*i)\n", "crossfile_context": ""}
{"task_id": "rocket_chip_vpu", "path": "rocket_chip_vpu/vpu/src/main/scala/VFDivSqrt.scala", "left_context": "// See LICENSE.UCTECHIP for license details.\n// See LICENSE.SZU for license details.\n/************************************************************\n*\n* Filename : VFDivSqrt.scala\n* Author : yexc\n* Revision : 2020/01/13\n* Company : UC TECH IP\n* Department : \n* Description : \n*\n* io.en : input, ...\n* io.din : input[width-1:0], ...\n* io.dout : output[width-1:0], ...\n*\n************************************************************/\npackage vpu\n\nimport chisel3._\nimport chisel3.util._\n\nimport vpu.DataGating._\nimport vpu.HardFloatHelper._\nimport vpu.Packing._\nimport vpu.util._\n\n//class VFDivSqrt(params: VPUParams)(implicit p: Parameters) extends VModule(params)(p) {\nclass VFDivSqrt(params: VPUParams) extends VModule(params) {\n class VFDUFn(sz_op: Int) extends Bundle {\n val rm = UInt(VPUConstants.FRM_SZ.W)\n val op = UInt(sz_op.W)\n\n def dgate(valid: Bool) = DataGating.dgate(valid, this.asUInt).asTypeOf(this.cloneType)\n", "right_context": " override def cloneType = new VFDUFn(sz_op).asInstanceOf[this.type]\n }\n\n class VFDivSqrtOperand extends Bundle {\n val fn = new VFDUFn(FDivFun_SZ)\n val vsrc1e = new FUCBVec\n val vsrc2e = new FUCBVec\n val v0en = new FSEW1wVec\n override def cloneType = new VFDivSqrtOperand().asInstanceOf[this.type]\n }\n\n class VFDivSqrtResult extends Bundle {\n val vFDivSqrtOut = new FUCBVec\n //val exc = UInt(VPUConstants.FFLAGS_SZ.W)\n val exc = new FFLAGSVec\n override def cloneType = new VFDivSqrtResult().asInstanceOf[this.type]\n }\n\n val io = IO(new Bundle {\n val vsew = Input(UInt(VSEW_SZ.W))\n val kill = Input(Bool())\n val req = Flipped(Decoupled(new VFDivSqrtOperand))\n val resp = Decoupled(new VFDivSqrtResult)\n })\n\n val fn = io.req.bits.fn\n\n val f16_vsrc1 = io.req.bits.vsrc1e.f16\n val f16_vsrc2 = io.req.bits.vsrc2e.f16\n val f16_en = io.req.bits.v0en.f16\n\n val f32_vsrc1 = io.req.bits.vsrc1e.f32\n val f32_vsrc2 = io.req.bits.vsrc2e.f32\n val f32_en = io.req.bits.v0en.f32\n\n val f64_vsrc1 = io.req.bits.vsrc1e.f64\n val f64_vsrc2 = io.req.bits.vsrc2e.f64\n val f64_en = io.req.bits.v0en.f64\n\n val f128_vsrc1 = io.req.bits.vsrc1e.f128\n val f128_vsrc2 = io.req.bits.vsrc2e.f128\n val f128_en = io.req.bits.v0en.f128\n\n val enableFlagPre = Wire(Bool())\n val enableFlagReg = RegInit(false.B)\n\n enableFlagPre := Mux(io.req.fire(), true.B, Mux(io.resp.fire(), false.B, enableFlagReg))\n enableFlagReg := enableFlagPre\n\n val results = \n List((FPS, f32_vsrc1, f32_vsrc2, f32_en, f32Depth, recode_sp _, ieee_sp _, (8, 24))) ++\n (F16).option((FPH, f16_vsrc1, f16_vsrc2, f16_en, f16Depth, recode_hp _, ieee_hp _, (5, 11))) ++\n (F64).option((FPD, f64_vsrc1, f64_vsrc2, f64_en, f64Depth, recode_dp _, ieee_dp _, (11, 53))) ++\n(F128).option((FPQ, f128_vsrc1,f128_vsrc2,f128_en,f128Depth,recode_qp _, ieee_qp _, (16, 112))) map {\n case (fp, vsrc1, vsrc2, v0en, fDepth, recode, ieee, (exp, sig)) => {\n val outData = Wire(Vec(fDepth, UInt((exp+sig+1).W)))\n val outValid = Wire(Vec(fDepth, Bool()))\n val inReady = Wire(Vec(fDepth, Bool()))\n val exc = Wire(Vec(fDepth, UInt(5.W)))\n val transValidPre = Wire(Vec(fDepth, Bool()))\n val transValidReg = RegInit(VecInit(Seq.fill(fDepth)(false.B)))\n for(i <- 0 until fDepth) \n {\n val divSqrt = Module(new hardfloat.DivSqrtRecFN_small(exp, sig, 0))\n val name = \"DivSqrt_f\" + (exp+sig).toString\n divSqrt.suggestName(name)\n val valid = (io.vsew === fp) && io.req.valid\n val lhs = MuxCase(0.U, Array(\n fn.op_is(FDivFun_Div) -> vsrc2(i),\n fn.op_is(FDivFun_RDiv) -> vsrc1(i),\n fn.op_is(FDivFun_Sqrt) -> vsrc2(i)\n ))\n val rhs = MuxCase(0.U, Array(\n fn.op_is(FDivFun_Div) -> vsrc1(i),\n fn.op_is(FDivFun_RDiv) -> vsrc2(i),\n fn.op_is(FDivFun_Sqrt) -> vsrc2(i)\n ))\n divSqrt.io.inValid := Pipe(true.B, (v0en(i) === 1.U) && valid, 1).bits\n divSqrt.io.sqrtOp := Pipe(true.B, fn.op_is(FDivFun_Sqrt), 1).bits\n divSqrt.io.a := (RegNext(lhs, 0.U))\n divSqrt.io.b := (RegNext(rhs, 0.U))\n divSqrt.io.roundingMode := RegNext(io.req.bits.fn.rm, 0.U)\n divSqrt.io.detectTininess := hardfloat.consts.tininess_afterRounding\n \n outValid(i) := MuxCase(false.B, Array(\n fn.op_is(FDivFun_Sqrt) -> divSqrt.io.outValid_sqrt,\n fn.op_is(FDivFun_Div, FDivFun_RDiv) -> divSqrt.io.outValid_div\n ))\n inReady(i) := divSqrt.io.inReady\n outData(i) := (divSqrt.io.out)\n exc(i) := divSqrt.io.exceptionFlags\n transValidPre(i) := Mux(io.resp.fire(), false.B,\n Mux(outValid(i) || (!(v0en(i) === 1.U) && valid && enableFlagPre), true.B, transValidReg(i)))\n transValidReg(i) := transValidPre(i)\n }\n \n //(outData, exc, outValid, inReady)\n (outData, exc, transValidReg, inReady)\n }\n }\n \n (F32, F16, F64, F128) match {\n case (true, false, false, false) => { // F32\n for(i <- 0 until f32Depth) io.resp.bits.vFDivSqrtOut.f32(i) := (results(0)._1)(i)\n //io.resp.bits.exc := results(0)._2.reduce(_|_)\n io.resp.bits.exc.exc32 := results(0)._2\n io.resp.valid := results(0)._3.reduce(_&&_)\n io.req.ready := results(0)._4.reduce(_&&_)\n }\n case (true, true, false, false) => { // F32, F16\n for(i <- 0 until f32Depth) io.resp.bits.vFDivSqrtOut.f32(i) := (results(0)._1)(i)\n for(i <- 0 until f16Depth) io.resp.bits.vFDivSqrtOut.f16(i) := (results(1)._1)(i)\n //io.resp.bits.exc := MuxCase(0.U, Array(\n // (io.vsew === FPS) -> results(0)._2.reduce(_|_),\n // (io.vsew === FPH) -> results(1)._2.reduce(_|_)\n //))\n io.resp.bits.exc.exc32 := results(0)._2\n io.resp.bits.exc.exc16 := results(1)._2\n io.resp.valid := MuxCase(false.B, Array(\n (io.vsew === FPS) -> results(0)._3.reduce(_&&_),\n (io.vsew === FPH) -> results(1)._3.reduce(_&&_)\n ))\n io.req.ready := MuxCase(false.B, Array(\n (io.vsew === FPS) -> results(0)._4.reduce(_&&_),\n (io.vsew === FPH) -> results(1)._4.reduce(_&&_)\n ))\n }\n case (true, false, true, false) => { // F32, F64\n //for(i <- 0 until f32Depth) io.resp.bits.vFDivSqrtOut.f32(i) := dgate(io.resp.valid, (results(0)._1)(i))\n //for(i <- 0 until f64Depth) io.resp.bits.vFDivSqrtOut.f64(i) := dgate(io.resp.valid, (results(1)._1)(i))\n for(i <- 0 until f32Depth) io.resp.bits.vFDivSqrtOut.f32(i) := (results(0)._1)(i)\n for(i <- 0 until f64Depth) io.resp.bits.vFDivSqrtOut.f64(i) := (results(1)._1)(i)\n //io.resp.bits.exc := MuxCase(0.U, Array(\n // (io.vsew === FPS) -> results(0)._2.reduce(_|_),\n // (io.vsew === FPD) -> results(1)._2.reduce(_|_)\n //))\n io.resp.bits.exc.exc32 := results(0)._2\n io.resp.bits.exc.exc64 := results(1)._2\n io.resp.valid := MuxCase(false.B, Array(\n (io.vsew === FPS) -> results(0)._3.reduce(_&&_),\n (io.vsew === FPD) -> results(1)._3.reduce(_&&_)\n ))\n io.req.ready := MuxCase(false.B, Array(\n (io.vsew === FPS) -> results(0)._4.reduce(_&&_),\n (io.vsew === FPD) -> results(1)._4.reduce(_&&_)\n ))\n }\n case (true, true, true, false) => { // F32, F16, F64\n for(i <- 0 until f32Depth) io.resp.bits.vFDivSqrtOut.f32(i) := (results(0)._1)(i)\n for(i <- 0 until f16Depth) io.resp.bits.vFDivSqrtOut.f16(i) := (results(1)._1)(i)\n for(i <- 0 until f64Depth) io.resp.bits.vFDivSqrtOut.f64(i) := (results(2)._1)(i)\n //io.resp.bits.exc := MuxCase(0.U, Array(\n // (io.vsew === FPS) -> results(0)._2.reduce(_|_),\n // (io.vsew === FPH) -> results(1)._2.reduce(_|_),\n // (io.vsew === FPD) -> results(2)._2.reduce(_|_)\n //))\n io.resp.bits.exc.exc32 := results(0)._2\n io.resp.bits.exc.exc16 := results(1)._2\n io.resp.bits.exc.exc64 := results(2)._2\n io.resp.valid := MuxCase(false.B, Array(\n (io.vsew === FPS) -> results(0)._3.reduce(_&&_),\n (io.vsew === FPH) -> results(1)._3.reduce(_&&_),\n (io.vsew === FPD) -> results(2)._3.reduce(_&&_)\n ))\n io.req.ready := MuxCase(false.B, Array(\n (io.vsew === FPS) -> results(0)._4.reduce(_&&_),\n (io.vsew === FPH) -> results(1)._4.reduce(_&&_),\n (io.vsew === FPD) -> results(2)._4.reduce(_&&_)\n ))\n }\n case (true, false, true, true) => { // F32, F64, F128\n for(i <- 0 until f32Depth) io.resp.bits.vFDivSqrtOut.f32(i) := (results(0)._1)(i)\n for(i <- 0 until f64Depth) io.resp.bits.vFDivSqrtOut.f64(i) := (results(1)._1)(i)\n for(i <- 0 until f128Depth) io.resp.bits.vFDivSqrtOut.f128(i) := (results(2)._1)(i)\n //io.resp.bits.exc := MuxCase(0.U, Array(\n // (io.vsew === FPS) -> results(0)._2.reduce(_|_),\n // (io.vsew === FPD) -> results(1)._2.reduce(_|_),\n // (io.vsew === FPQ) -> results(2)._2.reduce(_|_)\n //))\n io.resp.bits.exc.exc32 := results(0)._2\n io.resp.bits.exc.exc64 := results(1)._2\n io.resp.bits.exc.exc128 := results(2)._2\n io.resp.valid := MuxCase(false.B, Array(\n (io.vsew === FPS) -> results(0)._3.reduce(_&&_),\n (io.vsew === FPD) -> results(1)._3.reduce(_&&_),\n (io.vsew === FPQ) -> results(2)._3.reduce(_&&_)\n ))\n io.req.ready := MuxCase(false.B, Array(\n (io.vsew === FPS) -> results(0)._4.reduce(_&&_),\n (io.vsew === FPD) -> results(1)._4.reduce(_&&_),\n (io.vsew === FPQ) -> results(2)._4.reduce(_&&_)\n ))\n }\n case (true, true, true, true) => { // F32, F16, F64, F128\n for(i <- 0 until f32Depth) io.resp.bits.vFDivSqrtOut.f32(i) := (results(0)._1)(i)\n for(i <- 0 until f16Depth) io.resp.bits.vFDivSqrtOut.f16(i) := (results(1)._1)(i)\n for(i <- 0 until f64Depth) io.resp.bits.vFDivSqrtOut.f64(i) := (results(2)._1)(i)\n for(i <- 0 until f128Depth) io.resp.bits.vFDivSqrtOut.f128(i) := (results(3)._1)(i)\n //io.resp.bits.exc := MuxCase(0.U, Array(\n // (io.vsew === FPS) -> results(0)._2.reduce(_|_),\n // (io.vsew === FPH) -> results(1)._2.reduce(_|_),\n // (io.vsew === FPD) -> results(2)._2.reduce(_|_),\n // (io.vsew === FPQ) -> results(3)._2.reduce(_|_)\n //))\n io.resp.bits.exc.exc32 := results(0)._2\n io.resp.bits.exc.exc16 := results(1)._2\n io.resp.bits.exc.exc64 := results(2)._2\n io.resp.bits.exc.exc128 := results(3)._2\n io.resp.valid := MuxCase(false.B, Array(\n (io.vsew === FPS) -> results(0)._3.reduce(_&&_),\n (io.vsew === FPH) -> results(1)._3.reduce(_&&_),\n (io.vsew === FPD) -> results(2)._3.reduce(_&&_),\n (io.vsew === FPQ) -> results(3)._2.reduce(_|_)\n ))\n io.req.ready := MuxCase(false.B, Array(\n (io.vsew === FPS) -> results(0)._4.reduce(_&&_),\n (io.vsew === FPH) -> results(1)._4.reduce(_&&_),\n (io.vsew === FPD) -> results(2)._4.reduce(_&&_),\n (io.vsew === FPQ) -> results(3)._2.reduce(_|_)\n ))\n }\n case _ => {\n // do nothing\n }\n }\n\n}\n\n\n\n", "groundtruth": " def op_is(ops: UInt*) = ops.toList.map(x => {op === x}).reduceLeft(_ || _)\n", "crossfile_context": ""}
{"task_id": "rocket_chip_vpu", "path": "rocket_chip_vpu/vpu/src/main/scala/VFSignInject.scala", "left_context": "// See LICENSE.UCTECHIP for license details.\n// See LICENSE.SZU for license details.\n/************************************************************\n*\n* Filename : VFSignInject.scala\n* Author : liangzh\n* Revision : 2020/01/04\n* Company : UC TECH IP\n* Department : MAG\n* Description : floating-point sign-inject module\n*\n* io.vsrc1f : input, bundle of vectors, data, UCB relative, sign-inject operand 2\n* io.vsrc2f : input, bundle of vertors, data, UCB relative, sign-inject operand 1\n* io.fsgnjFun : input[FSgnJFun_SZ-1:0], control, function select\n* io.vFSgnJOut : output, bundle of vectors, data, UCB relative, sign-inject result\n*\n************************************************************/\npackage vpu\n\nimport chisel3._\nimport chisel3.util._\n\nclass VFSignInject(params: VPUParams) extends VModule(params) {\n val io = IO(new Bundle {\n val vsrc1f = Input(new FUCBVec)\n val vsrc2f = Input(new FUCBVec)\n val fsgnjFun = Input(UInt(FSgnJFun_SZ.W))\n val vFSgnJOut = Output(new FUCBVec)\n })\n\n", "right_context": " }\n for(i <- 0 until f64Depth) {\n io.vFSgnJOut.f64(i) := MuxCase(Cat(io.vsrc1f.f64(i)(64), io.vsrc2f.f64(i)(63,0)),\n Array((io.fsgnjFun === FSgnJFun_Not) -> Cat(~io.vsrc1f.f64(i)(64), io.vsrc2f.f64(i)(63,0)),\n (io.fsgnjFun === FSgnJFun_Xor) -> Cat(io.vsrc1f.f64(i)(64) ^ io.vsrc2f.f64(i)(64), io.vsrc2f.f64(i)(63,0))))\n }\n for(i <- 0 until f128Depth) {\n io.vFSgnJOut.f128(i) := MuxCase(Cat(io.vsrc1f.f128(i)(128), io.vsrc2f.f128(i)(127,0)),\n Array((io.fsgnjFun === FSgnJFun_Not) -> Cat(~io.vsrc1f.f128(i)(128), io.vsrc2f.f128(i)(127,0)),\n (io.fsgnjFun === FSgnJFun_Xor) -> Cat(io.vsrc1f.f128(i)(128) ^ io.vsrc2f.f128(i)(128), io.vsrc2f.f128(i)(127,0))))\n }\n}\n", "groundtruth": " for(i <- 0 until f16Depth) {\n io.vFSgnJOut.f16(i) := MuxCase(Cat(io.vsrc1f.f16(i)(16), io.vsrc2f.f16(i)(15,0)),\n Array((io.fsgnjFun === FSgnJFun_Not) -> Cat(~io.vsrc1f.f16(i)(16), io.vsrc2f.f16(i)(15,0)),\n (io.fsgnjFun === FSgnJFun_Xor) -> Cat(io.vsrc1f.f16(i)(16) ^ io.vsrc2f.f16(i)(16), io.vsrc2f.f16(i)(15,0))))\n }\n", "crossfile_context": ""}
{"task_id": "rocket_chip_vpu", "path": "rocket_chip_vpu/vpu/src/main/scala/VFWidthConvert.scala", "left_context": "// See LICENSE.UCTECHIP for license details.\n// See LICENSE.SZU for license details.\n/************************************************************\n*\n* Filename : VFWidthConvert.scala\n* Author : liangzh\n* Revision : 2020/01/09\n* Company : UC TECH IP\n* Department : MAG\n* Description : convert floating-point vector elements' width\n*\n* io.reqValid : input, control, request valid\n* io.isSrc12SEW : input, control, showing whether source 1 is double SEW width or not\n* io.isSrc22SEW : input, control, showing whether source 2 is double SEW width or not\n* io.isVd2SEW : input, control, showing whether destination is double SEW width or not\n* io.src1Typ : ipnut[Src1Typ_SZ-1:0], control, showing the type of source 1 is which type: vector, scalar or immediate\n* io.majFun : input[MajFun_SZ-1:0], control, showing which major function the inst is\n* io.fcvtFun : input[FCvtFun_SZ-1:0], control, showing function of a floating-point convert inst\n* io.frm : input[FRM_SZ-1:0], control, floating-point rounding mode\n* io.fromXData1 : input[XLEN-1:0], data, from rocket GPR data\n* io.fromFData : input[FLEN:0], data, from FPU floating-point registers data\n* io.vs1e : input, bundle of vectors, data, SEW relative, to be width convert source 1\n* io.vs2e : input, bundle of vectors, data, SEW relative, to be width convert source 2\n* io.vdvs3e : input, bundle of vectors, data, SEW relative, to be recode to UCB pattern destination\n* io.respValid : output, control, showing output data valid\n* io.vsrc1f : output, bundle of vectors, data, UCB relative, width converted source 1\n* io.vsrc2f : output, bundle of vectors, data, UCB relative, width converted source 2\n* io.vdvs3f : output, bundle of vectors, data, UCB relative, UCB recoded destination\n* io.vFtoFExc : output, bundle of vectors, data, elements all FFLAGS_SZ bits, fflags from width convert process\n*\n************************************************************/\npackage vpu\n\nimport chisel3._\nimport chisel3.util._\n\nclass VFWidthConvert(params: VPUParams) extends VModule(params) with HasFPUParameters {\n val io = IO(new Bundle {\n val reqValid = Input(Bool())\n val isSrc12SEW = Input(Bool())\n val isSrc22SEW = Input(Bool())\n val isVd2SEW = Input(Bool())\n val src1Typ = Input(UInt(Src1Typ_SZ.W))\n val majFun = Input(UInt(MajFun_SZ.W))\n val fcvtFun = Input(UInt(FCvtFun_SZ.W))\n val frm = Input(UInt(VPUConstants.FRM_SZ.W))\n\n val fromXData1 = Input(UInt(XLEN.W))\n val fromFData = Input(UInt((FLEN+1).W))\n val vs1e = Input(new SEWVec)\n val vs2e = Input(new SEWVec)\n val vdvs3e = Input(new SEWVec)\n\n val respValid = Output(new Bool())\n val vsrc1f = Output(new FUCBVec)\n val vsrc2f = Output(new FUCBVec)\n val vdvs3f = Output(new FUCBVec)\n val vFtoFExc = Output(new FFLAGSVec)\n })\n\n val isV1Origin = io.src1Typ === Src1_Vs && (!io.isVd2SEW || io.isSrc12SEW)\n val isV1to2SEW = io.src1Typ === Src1_Vs && io.isVd2SEW\n val isF1toSEW = io.src1Typ === Src1_Fs && !io.isVd2SEW\n val isF1to2SEW = io.src1Typ === Src1_Fs && io.isVd2SEW\n\n val isV2Origin = io.majFun === IsFCvt && (io.fcvtFun =/= FCvtFun_F2WF && io.fcvtFun =/= FCvtFun_F2NF) || \n io.majFun =/= IsFCvt && (io.isSrc22SEW || !io.isVd2SEW)\n val isV2to2SEW = io.majFun === IsFCvt && io.fcvtFun === FCvtFun_F2WF || \n io.majFun =/= IsFCvt && !io.isSrc22SEW && io.isVd2SEW\n val isV2toHSEW = io.majFun === IsFCvt && io.fcvtFun === FCvtFun_F2NF\n\n val vsrc1f = RegInit(0.U.asTypeOf(new FUCBVec))\n val vsrc2f = RegInit(0.U.asTypeOf(new FUCBVec))\n val vFtoFExc = RegInit(0.U.asTypeOf(new FFLAGSVec))\n val respValid = RegNext(io.reqValid, false.B)\n\n val qNaN16 = Cat(~(0.U(7.W)), 0.U(9.W))\n val qNaN32 = Cat(~(0.U(10.W)), 0.U(22.W))\n val qNaN64 = Cat(~(0.U(13.W)), 0.U(51.W))\n val qNaN128 = Cat(~(0.U(17.W)), 0.U(111.W))\n val ucb33 = unbox(io.fromFData, false.B, Some(FType.S))\n val ucb65 = unbox(io.fromFData, false.B, Some(FType.D))\n\n def F33ToH1: UInt = unbox(io.fromFData, false.B, Some(FType.H))\n def F65ToH1: UInt = unbox(io.fromFData, false.B, Some(FType.H))\n def F32ToH1: UInt = FType.H.recode(Mux(io.fromXData1(31,16).andR, io.fromXData1(15,0), qNaN16))\n def F64ToH1: UInt = FType.H.recode(Mux(io.fromXData1(63,16).andR, io.fromXData1(15,0), qNaN16))\n def FH1: UInt = if(!ZFINX && FLEN == 32) F33ToH1\n else if(!ZFINX && FLEN == 64) F65ToH1\n else if(ZFINX && XLEN == 32) F32ToH1\n else F64ToH1\n\n def F33ToS1: UInt = ucb33\n def F65ToS1: UInt = ucb33\n def F32ToS1: UInt = FType.S.recode(io.fromXData1)\n", "right_context": " def FS1: UInt = if(!ZFINX && FLEN == 32) F33ToS1\n else if(!ZFINX && FLEN == 64) F65ToS1\n else if(ZFINX && XLEN == 32) F32ToS1\n else F64ToS1\n\n def F33ToD1: UInt = box(ucb33, FType.D)\n def F65ToD1: UInt = ucb65\n def F32ToD1: UInt = FType.D.recode(Cat(~(0.U(32.W)), io.fromXData1))\n def F64ToD1: UInt = FType.D.recode(io.fromXData1)\n def FD1: UInt = if(!ZFINX && FLEN == 32) F33ToD1\n else if(!ZFINX && FLEN == 64) F65ToD1\n else if(ZFINX && XLEN == 32) F32ToD1\n else F64ToD1\n\n def F33ToQ1: UInt = box(ucb33, FType.Q)\n def F65ToQ1: UInt = box(ucb65, FType.Q)\n def F32ToQ1: UInt = FType.Q.recode(Cat(~(0.U(96.W)), io.fromXData1))\n def F64ToQ1: UInt = FType.Q.recode(Cat(~(0.U(64.W)), io.fromXData1))\n def FQ1: UInt = if(!ZFINX && FLEN == 32) F33ToQ1\n else if(!ZFINX && FLEN == 64) F65ToQ1\n else if(ZFINX && XLEN == 32) F32ToQ1\n else F64ToQ1\n\n def HToS(ucbH: UInt): UInt = {\n val htos = Module(new hardfloat.RecFNToRecFN(FType.H.exp, FType.H.sig, FType.S.exp, FType.S.sig))\n htos.io.in := ucbH\n htos.io.roundingMode := io.frm\n htos.io.detectTininess := hardfloat.consts.tininess_afterRounding\n htos.io.out\n }\n def SToD(ucbS: UInt): UInt = {\n val stod = Module(new hardfloat.RecFNToRecFN(FType.S.exp, FType.S.sig, FType.D.exp, FType.D.sig))\n stod.io.in := ucbS\n stod.io.roundingMode := io.frm\n stod.io.detectTininess := hardfloat.consts.tininess_afterRounding\n stod.io.out\n }\n def DToQ(ucbD: UInt): UInt = {\n val dtoq = Module(new hardfloat.RecFNToRecFN(FType.D.exp, FType.D.sig, FType.Q.exp, FType.Q.sig))\n dtoq.io.in := ucbD\n dtoq.io.roundingMode := io.frm\n dtoq.io.detectTininess := hardfloat.consts.tininess_afterRounding\n dtoq.io.out\n }\n def SToH(ucbS: UInt): UInt = {\n val stoh = Module(new hardfloat.RecFNToRecFN(FType.S.exp, FType.S.sig, FType.H.exp, FType.H.sig))\n stoh.io.in := ucbS\n stoh.io.roundingMode := io.frm\n stoh.io.detectTininess := hardfloat.consts.tininess_afterRounding\n Cat(stoh.io.out, stoh.io.exceptionFlags)\n }\n def DToS(ucbD: UInt): UInt = {\n val dtos = Module(new hardfloat.RecFNToRecFN(FType.D.exp, FType.D.sig, FType.S.exp, FType.S.sig))\n dtos.io.in := ucbD\n dtos.io.roundingMode := io.frm\n dtos.io.detectTininess := hardfloat.consts.tininess_afterRounding\n Cat(dtos.io.out, dtos.io.exceptionFlags)\n }\n def QToD(ucbQ: UInt): UInt = {\n val qtod = Module(new hardfloat.RecFNToRecFN(FType.Q.exp, FType.Q.sig, FType.D.exp, FType.D.sig))\n qtod.io.in := ucbQ\n qtod.io.roundingMode := io.frm\n qtod.io.detectTininess := hardfloat.consts.tininess_afterRounding\n Cat(qtod.io.out, qtod.io.exceptionFlags)\n }\n/////*convert vs1's width SEW to 2SEW and fs1's width to SEW for floating-point operation*////\n for(i <- 0 until f16Depth)\n vsrc1f.f16(i) := MuxCase(FType.H.qNaN, Array(isV1Origin -> FType.H.recode(io.vs1e.e16(i)),\n isF1toSEW -> FH1))\n\n for(i <- 0 until f32Depth)\n vsrc1f.f32(i) := MuxCase(FType.S.qNaN,\n Array(isV1Origin -> FType.S.recode(io.vs1e.e32(i)),\n isF1toSEW -> FS1)\n ++ (if(FSEW16) Array(isV1to2SEW -> HToS(FType.H.recode(io.vs1e.e16(i))),\n isF1to2SEW -> HToS(FH1))\n else Nil))\n\n for(i <- 0 until f64Depth)\n vsrc1f.f64(i) := MuxCase(FType.D.qNaN,\n Array(isV1Origin -> FType.D.recode(io.vs1e.e64(i)),\n isF1toSEW -> FD1,\n isV1to2SEW -> SToD(FType.S.recode(io.vs1e.e32(i))),\n isF1to2SEW -> SToD(FS1)))\n\n for(i <- 0 until f128Depth)\n vsrc1f.f128(i) := MuxCase(FType.Q.qNaN,\n Array(isV1Origin -> FType.Q.recode(io.vs1e.e128(i)),\n isF1toSEW -> FQ1,\n isV1to2SEW -> DToQ(FType.D.recode(io.vs1e.e64(i))),\n isF1to2SEW -> DToQ(FD1)))\n\n////////*convert vs2's width SEW to 2SEW or 2SEW to SEW for floating-point operation*/////////\n//half precision\n for(i <- 0 until f16Depth/2) {\n val fexc17 = MuxCase(Cat(FType.H.qNaN, 0.U(5.W)),\n Array(isV2Origin -> Cat(FType.H.recode(io.vs2e.e16(i)), 0.U(5.W)),\n isV2toHSEW -> SToH(FType.S.recode(io.vs2e.e32(i)))))\n vsrc2f.f16(i) := fexc17(21,5)\n vFtoFExc.exc16(i) := fexc17(4,0)\n }\n for(i <- f16Depth/2 until f16Depth) {\n vsrc2f.f16(i) := FType.H.recode(io.vs2e.e16(i))\n vFtoFExc.exc16(i) := 0.U(5.W)\n }\n//single precision\n for(i <- 0 until f32Depth/2) {\n val fexc33 = MuxCase(Cat(FType.S.qNaN, 0.U(5.W)), \n Array(isV2Origin -> Cat(FType.S.recode(io.vs2e.e32(i)), 0.U(5.W)))\n ++ (if(FSEW16) Array(isV2to2SEW -> Cat(HToS(FType.H.recode(io.vs2e.e16(i))), 0.U(5.W))) else Nil)\n ++ (if(FSEWMAX >= 64) Array(isV2toHSEW -> DToS(FType.D.recode(io.vs2e.e64(i)))) else Nil))\n vsrc2f.f32(i) := fexc33(37,5)\n vFtoFExc.exc32(i) := fexc33(4,0)\n }\n for(i <- f32Depth/2 until f32Depth) {\n vsrc2f.f32(i) := MuxCase(FType.S.qNaN,\n Array(isV2Origin -> FType.S.recode(io.vs2e.e32(i)))\n ++ (if(FSEW16) Array(isV2to2SEW -> HToS(FType.H.recode(io.vs2e.e16(i)))) else Nil))\n vFtoFExc.exc32(i) := 0.U(5.W)\n }\n//double precision\n for(i <- 0 until f64Depth/2) {\n val fexc65 = MuxCase(Cat(FType.D.qNaN, 0.U(5.W)),\n Array(isV2Origin -> Cat(FType.D.recode(io.vs2e.e64(i)), 0.U(5.W)),\n isV2to2SEW -> Cat(SToD(FType.S.recode(io.vs2e.e32(i))), 0.U(5.W)))\n ++ (if(FSEWMAX == 128) Array(isV2toHSEW -> QToD(FType.Q.recode(io.vs2e.e128(i)))) else Nil))\n vsrc2f.f64(i) := fexc65(68,5)\n vFtoFExc.exc64(i) := fexc65(4,0)\n }\n for(i <- f64Depth/2 until f64Depth) {\n vsrc2f.f64(i) := MuxCase(FType.D.qNaN,\n Array(isV2Origin -> FType.D.recode(io.vs2e.e64(i)),\n isV2to2SEW -> SToD(FType.S.recode(io.vs2e.e32(i)))))\n vFtoFExc.exc64(i) := 0.U(5.W)\n }\n//quadruple precision\n for(i <- 0 until f128Depth) {\n vsrc2f.f128(i) := MuxCase(FType.Q.qNaN,\n Array(isV2Origin -> FType.Q.recode(io.vs2e.e128(i)),\n isV2to2SEW -> DToQ(FType.D.recode(io.vs2e.e64(i)))))\n vFtoFExc.exc128(i) := 0.U(5.W)\n }\n\n\n io.vsrc1f := vsrc1f\n io.vsrc2f := vsrc2f\n io.vFtoFExc := vFtoFExc\n io.respValid := respValid\n for(i <- 0 until f16Depth) io.vdvs3f.f16(i) := FType.H.recode(io.vdvs3e.e16(i))\n for(i <- 0 until f32Depth) io.vdvs3f.f32(i) := FType.S.recode(io.vdvs3e.e32(i))\n for(i <- 0 until f64Depth) io.vdvs3f.f64(i) := FType.D.recode(io.vdvs3e.e64(i))\n for(i <- 0 until f128Depth) io.vdvs3f.f128(i) := FType.Q.recode(io.vdvs3e.e128(i))\n\n \n}\n", "groundtruth": " def F64ToS1: UInt = FType.S.recode(Mux(io.fromXData1(63,32).andR, io.fromXData1(31,0), qNaN32))\n", "crossfile_context": ""}
{"task_id": "rocket_chip_vpu", "path": "rocket_chip_vpu/vpu/src/main/scala/VPUIO.scala", "left_context": "// See LICENSE.UCTECHIP for license details.\n// See LICENSE.SZU for license details.\n/************************************************************\n*\n* Filename : VPUIO.scala\n* Author : liangzh\n* Revision : 2019/04/26\n* Company : UC TECH IP\n* Department : MAG\n* Description : io port for top module VPU\n*\n* io.core.resp.toXData : output[XLEN-1:0], data, result from VPU to write in Rocket GPR\n* io.core.resp.rd : output[4:0], data, address of writing result to GPR\n*\n* io.core.req.valid : input, control, showing inst or data valid\n* io.core.req.ready : output, control, showing vpu is ready to receive an inst or data\n* io.core.req.bits.inst : input[31:0], control, vector instruction\n* io.core.fromXData1 : input[XLEN-1:0], data, from GPR, corresponds to rs1\n* io.core.fromXData2 : input[XLEN-1:0], data, from GPR, corresponds to rs2\n*\n* io.core.fflags_ready : output, control, showing whether CSR fflags is ready to be read\n* io.core.vcsr_fflags.valid : output, control, floating-point fflags output valid\n* io.core.vcsr_fflags.bits : output[FFLAGS_SZ-1:0], data, fflags\n* io.core.vcsr_frm : input[FRM_SZ-1:0], data, floating-point rounding mode\n* io.core.vxsat_ready : output, control, showing whether CSR vxsat is ready to be read\n* io.core.vcsr_vxsat.valid : output, control, fixed-point overflow flag output valid\n* io.core.vcsr_vxsat.bits : output[XSAT_SZ-1:0], data, fixed-point overflow flag\n* io.core.vcsr_vxrm : input[XRM_SZ-1:0], data, fixed-point rounding mode\n* io.core.vcsr_vstart : output[log2Ceil(VLEN)-1:0], data, value to write CSR vstart\n* io.core.vcsr_vl : output[XLEN-1:0], data, value to write CSR vl\n* io.core.vcsr_vtype : output[XLEN-1:0], data, value to write CSR vtype\n*\n* io.core.ctrl_killx : input, control, kill the vector instruction executed at EXE stage\n* \tio.core.ctrl_killm : input, control, kill the vector instruction executed at MEM stage\n* io.core.ctrl_killw : input, control, kill the vector instruction executed at WB stage\n* io.core.eret : input, control, take the trap finish\n* io.core.vxcpt_precise : output, control, precise exception signal generated at VPU, it connect to WB stage\n* io.core.vxcpt_imprecise : output, control, imprecise exception signal generated at VPU, it connect to ID stage\n* io.core.vxcpt_imprecise_resp : input, control, inform VPU that exception has been received\n* io.core.vcause : output[XLEN-1:0], data, exception cause\n* io.core.vmtval : output[XLEN-1:0], data, \n* io.core.vnack : output, control, imform Rocket that a vector inst has not been executed\n* io.core.dcache_blocked : output, control, showing VPU is occupying DCache\n*\n* io.fpu.req.fromFData : input[FLEN-1:0], data, from floating-point registers, corresponds to rs1\n* io.fpu.req.rs1 : output[4:0], data, address for reading rs1 from floating-point registers\n*\n* io.fpu.resp.valid : output, control, showing address and data valid\n* io.fpu.resp.ready : input, control, showing ready to receive address and data\n* io.fpu.resp.bits.toFData : output[FLEN-1:0], data, result from VPU to FPU\n* io.fpu.resp.bits.rd : output[4:0], data, address of writing result to floating-point registers\n*\n* io.respValid : input, control, showing DCache response valid\n* io.respTag : input[6:0], control, return tag of request for in order receive\n* io.respSize : input[2:0], control, data width\n* io.respHasData : input, control, showing response has data\n* io.respData : input[XLEN-1:0], data, response data\n* io.respS2Xcpt : input HellaCacheExceptions, data, response exception information\n*\n* io.reqReady : input, control, showing DCache is ready to receive a request\n* io.s2Nack : input, control, not-acknowledge request\n* io.reqValid : output, control, showing request valid\n* io.reqAddr : output[XLEN-1:0], control, address of memory data\n* io.reqTag : output[6:0], control, tag of request for in order receive\n* io.reqCmd : output[4:0], control, showing load or store action\n* io.reqSize : output[2:0], control, data width\n* io.s1Data : output[XLEN-1:0], data, data to store in memory\n* io.s1Kill : output, control, kill s1 stage of DCache\n*\n************************************************************/\npackage vpu\n\nimport chisel3._\nimport chisel3.util._\n\n////////////////////////////////////VPU-Rocket//////////////////////////////////\n//response signals from VPU to Rocket\nclass VPUCoreResponse(val XLEN: Int) extends Bundle {\n val toXData = UInt(XLEN.W)\n val rd = UInt(5.W)\n\n override def cloneType = new VPUCoreResponse(XLEN).asInstanceOf[this.type]\n}\n//request signals from Rocket to VPU\nclass VPUCoreRequest extends Bundle {\n val inst = UInt(32.W)\n}\n\n\n//VPU-Rocket communication IO\nclass VPUCoreIO(val VLEN: Int, val XLEN: Int) extends Bundle {\n val resp = Output(new VPUCoreResponse(XLEN))\n val req = Flipped(Decoupled(new VPUCoreRequest))\n val fromXData1 = Input(UInt(XLEN.W))\n val fromXData2 = Input(UInt(XLEN.W))\n\n val fflags_ready = Output(Bool())\n val vcsr_fflags = Valid(UInt(VPUConstants.FFLAGS_SZ.W))\n val vcsr_frm = Input(UInt(VPUConstants.FRM_SZ.W))\n val vxsat_ready = Output(Bool())\n val vcsr_vxsat = Valid(UInt(VPUConstants.XSAT_SZ.W))\n val vcsr_vxrm = Input(UInt(VPUConstants.XRM_SZ.W))\n val vcsr_vstart = Output(UInt(log2Ceil(VLEN).W))\n val vcsr_vl = Output(UInt(XLEN.W))\n val vcsr_vtype = Output(UInt(XLEN.W))\n\n val ctrl_killx = Input(Bool())\n val ctrl_killm = Input(Bool())\n val ctrl_killw = Input(Bool())\n\n val eret = Input(Bool())\n val vxcpt_precise = Output(Bool())\n val vxcpt_imprecise = Output(Bool())\n val vxcpt_imprecise_resp = Input(Bool())\n val vcause = Output(UInt(XLEN.W))\n val vmtval = Output(UInt(XLEN.W))\n val vnack = Output(Bool())\n val dcache_blocked = Output(Bool())\n\n override def cloneType = new VPUCoreIO(VLEN, XLEN).asInstanceOf[this.type]\n}\n\n\n\n////////////////////////////////////VPU-FPU/////////////////////////////////////\n//request signals from VPU to FPU\nclass VPUFPUResponse(val FLEN: Int) extends Bundle {\n val toFData = UInt((FLEN+1).W)\n val rd = UInt(5.W)\n\n", "right_context": "}\n//response signals from FPU to VPU\nclass VPUFPURequest(val FLEN: Int) extends Bundle {\n val fromFData = Input(UInt((FLEN+1).W))\n val rs1 = Output(UInt(5.W))\n\n override def cloneType = new VPUFPURequest(FLEN).asInstanceOf[this.type]\n}\n\n\n//VPU-FPU communication IO\nclass VPUFPUIO(val FLEN: Int) extends Bundle {\n val req = new VPUFPURequest(FLEN)\n val resp = Decoupled(new VPUFPUResponse(FLEN))\n\n override def cloneType = new VPUFPUIO(FLEN).asInstanceOf[this.type]\n}\n\n\n\n/////////////////////////////////Rocket HellaCache IO///////////////////////////\nclass AlignmentExceptions extends Bundle {\n\tval ld = Bool()\n\tval st = Bool()\n}\n\nclass HellaCacheExceptions extends Bundle {\n\tval ma = new AlignmentExceptions\n\tval pf = new AlignmentExceptions\n\tval ae = new AlignmentExceptions\n}\n\n\n\n////////////////////////////////////VPU IO//////////////////////////////////////\nclass VPUIO(VLEN: Int, XLEN: Int, FLEN: Int, tagBits: Int, addrBits: Int) extends Bundle {\n val dataBits = XLEN max FLEN\n val dataBytes = dataBits/8\n val sizeBits = log2Ceil(log2Ceil(dataBytes)+1)\n\n val core = new VPUCoreIO(VLEN, XLEN)\n val fpu = new VPUFPUIO(FLEN)\n //temporary input\n val reqReady = Input(Bool())\n val s2Nack = Input(UInt(1.W))\n val respValid = Input(Bool())\n val respTag = Input(UInt(tagBits.W))\n val respSize = Input(UInt(sizeBits.W))\n val respHasData = Input(Bool())\n val respData = Input(UInt(dataBits.W))\n val respS2Xcpt = Input(new HellaCacheExceptions)\n //temporary output\n val reqValid = Output(Bool())\n val reqAddr = Output(UInt(addrBits.W))\n val reqTag = Output(UInt(tagBits.W))\n val reqCmd = Output(UInt(5.W))\n val reqSize = Output(UInt(sizeBits.W))\n val s1Kill = Output(Bool())\n val s1Data = Output(UInt(dataBits.W))\n\n override def cloneType = new VPUIO(VLEN, XLEN, FLEN, tagBits, addrBits).asInstanceOf[this.type]\n}\n\n", "groundtruth": " override def cloneType = new VPUFPUResponse(FLEN).asInstanceOf[this.type]\n", "crossfile_context": ""}
{"task_id": "rocket_chip_vpu", "path": "rocket_chip_vpu/vpu/src/main/scala/VPU_64V64E1L.scala", "left_context": "// See LICENSE.UCTECHIP for license details.\n// See LICENSE.SZU for license details.\n/************************************************************\n*\n* Filename : VPU_64V64E1L.scala\n* Author : liangzh\n* Revision : 2020/04/09\n* Company : UC TECH IP\n* Department : MAG\n* Description : top module of VPU for LMULMAX=1\n*\n************************************************************/\npackage vpu\n\nimport chisel3._\nimport chisel3.util._\n\nclass VPU_64V64E1L(params: VPUParams, tagBits: Int, addrBits: Int) extends VModule(params) {\n\n require(isPow2(VLEN) && VLEN >= 32)\n require(isPow2(ELEN) && ELEN >= 32 && ELEN <= 1024)\n require(isPow2(SELEN) && SELEN >= 1 && SELEN <= 8)\n require(isPow2(XLEN) && XLEN >= 32 && XLEN <= 64)\n require(isPow2(FLEN) && FLEN >= 32 && FLEN <= 64)\n require(isPow2(FSEWMAX) && FSEWMAX >= 32 && FSEWMAX <= 128)\n require(VLEN == ELEN && VLEN >= XLEN && VLEN >= FLEN)\n require(ELEN >= XLEN && ELEN >= FLEN && ELEN >= FSEWMAX)\n require(LMULMAX == 1)\n require(SELEN == 8) //TODO release SELEN\n\n\n val io = IO(new VPUIO(VLEN, XLEN, FLEN, tagBits, addrBits))\n /////////////////simplify input signals' name/////////////////\n val instReady = Wire(Bool())\n val coreFire = io.core.req.valid && instReady\n //for killing process\n val killx = io.core.ctrl_killx\n val killm = io.core.ctrl_killm\n val killw = io.core.ctrl_killw\n //from Rocket Data -- VEXE state valid\n val fromXData1 = io.core.fromXData1\n val fromXData2 = io.core.fromXData2\n val fromFData = io.fpu.req.fromFData\n /////////////////simplify input signals' name/////////////////\n\n /////////////////////instantiate modules//////////////////////\n val vdecode = Module(new VDecode(params))\n val vexcp = Module(new VDecodeExcp(params))\n val vcsr = Module(new VCSR(params))\n val vsplit = Module(new VSplit(params))\n val vm2e = Module(new VMLENtoSEW(params))\n val vwidth = Module(new VWidthConvert(params))\n val valc = Module(new VAllocate(params))\n val vadd = Module(new VFullAdder(params))\n val vbit = Module(new VBitwise(params))\n val vshift = Module(new VShift(params))\n val vcmp = Module(new VCompare(params))\n val vpopc = Module(new VPopc(params))\n val vmidx = Module(new VMinIndex(params))\n val viota = Module(new VIota(params))\n val vidx = Module(new VIndex(params))\n val vmerge = Module(new VMerge(params))\n val vmuldiv = Module(new VMulDiv(params))\n val vred = Module(new VReduction(params))\n val vmv = Module(new VScalarMove(params))\n val vslide = Module(new VSlide(params))\n val vrgather = Module(new VRGather(params))\n val vcompress = Module(new VCompress(params))\n val vfwidth = Module(new VFWidthConvert(params))\n val vfma = Module(new VFMA(params))\n val vfdiv = Module(new VFDivSqrt(params))\n val vf2i = Module(new VFIConvert(params))\n val vi2f = Module(new VIFConvert(params))\n val vfcmp = Module(new VFCompare(params))\n val vfclass = Module(new VFClass(params))\n val vfsgnj = Module(new VFSignInject(params))\n val vfun1 = Module(new VFunSelFront(params))\n val vfun2 = Module(new VFunSelBack(params))\n val vmask = Module(new VMaskOut(params))\n val vdmemwidth = Module(new VDmemWidthConvert(params))\n val vdmemreq = Module(new VDmemRequest(params, tagBits, addrBits))\n val vdmemresp = Module(new VDmemResp(params, tagBits, addrBits))\n /////////////////////instantiate modules//////////////////////\n\n //////////////////////define registers////////////////////////\n //registers for VEXE stage\n val exe_reg_enable = RegInit(false.B)\n val exe_reg_fromXData1 = RegInit(0.U(XLEN.W))\n val exe_reg_fromXData2 = RegInit(0.U(XLEN.W))\n val exe_reg_fromFData = RegInit(0.U((FLEN+1).W))\n val exe_reg_ctrlSigs = RegInit(0.U.asTypeOf(new VPUCtrlSigs))\n val exe_reg_vs1Data = RegInit(0.U((8*VLEN).W))\n val exe_reg_vs2Data = RegInit(0.U((8*VLEN).W))\n val exe_reg_vdvs3Data = RegInit(0.U((8*VLEN).W))\n val exe_reg_v0Mask = RegInit(0.U(VLEN.W))\n //registers for relay\n val relay_reg_Data0 = RegInit(0.U(ELEN.W))\n val relay_reg_Data1 = RegInit(0.U(ELEN.W))\n val relay_reg_Data2 = RegInit(0.U(ELEN.W))\n val relay_reg_Data3 = RegInit(0.U(ELEN.W))\n val relay_reg_Data4 = RegInit(0.U(ELEN.W))\n val relay_reg_Data5 = RegInit(0.U(ELEN.W))\n val relay_reg_Data6 = RegInit(0.U(ELEN.W))\n val relay_reg_Data7 = RegInit(0.U(ELEN.W))\n val relay_reg_vxsat = RegInit(0.U(VPUConstants.XSAT_SZ.W))\n val relay_reg_fflags = RegInit(0.U(VPUConstants.FFLAGS_SZ.W))\n //registes for VWB stage\n val exe_enable = Wire(Bool())\n val wb_reg_enable = RegNext(exe_enable, false.B)\n val wb_reg_ctrlSigs = RegEnable(exe_reg_ctrlSigs, 0.U.asTypeOf(new VPUCtrlSigs), exe_enable)\n val wb_reg_veOut = RegEnable(vmask.io.veOut, 0.U((8*VLEN).W), exe_enable)\n val wb_reg_vmOut = RegEnable(vmask.io.vmOut, 0.U(VLEN.W), exe_enable)\n val wb_reg_scalarXOut = RegEnable(vfun2.io.scalarXOut, 0.U(XLEN.W), exe_enable)\n val wb_reg_vxsat = RegEnable(relay_reg_vxsat, 0.U(VPUConstants.XSAT_SZ.W), exe_enable)\n val wb_reg_fflags = RegEnable(relay_reg_fflags, 0.U(VPUConstants.FFLAGS_SZ.W), exe_enable)\n //registers for upload illegal insts\n val illInst = Wire(Bool())\n val llInst = Wire(Bool())\n val upload_reg_illInst0 = RegNext(illInst, false.B)\n val upload_reg_illInst1 = RegNext(upload_reg_illInst0 && !killx, false.B)\n val upload_reg_illInst2 = RegNext(upload_reg_illInst1 && !killm, false.B)\n val upload_reg_inst0 = RegEnable(io.core.req.bits.inst, 0.U(32.W), illInst)\n val upload_reg_inst1 = RegEnable(upload_reg_inst0, 0.U(32.W), upload_reg_illInst0 && !killx)\n val upload_reg_inst2 = RegEnable(upload_reg_inst1, 0.U(32.W), upload_reg_illInst1 && !killm)\n //registers for kill vector insts\n val eInst = exe_reg_ctrlSigs.isCSRInst || exe_reg_ctrlSigs.isALInst\n val ePipem = RegNext(exe_reg_enable && eInst && !killx, false.B)\n val ePipew = RegNext(ePipem && !killm, false.B)\n val mInst = exe_reg_ctrlSigs.isLdInst || exe_reg_ctrlSigs.isStInst || exe_reg_ctrlSigs.isAMOInst\n val mPipem = RegNext(exe_reg_enable && mInst && !killx, false.B)\n val mPipew = RegNext(mPipem && !killm, false.B)\n //status for main FSM\n def idle = 0.U(6.W)\n def inVLoad = 1.U(6.W)\n def inVStore = 2.U(6.W)\n def inExpt = 3.U(6.W)\n def inOCFull = 4.U(6.W)\n def inMCFull = 5.U(6.W)\n def inOCPart0 = 6.U(6.W)\n def inOCPart1 = 7.U(6.W)\n def inOCPart2 = 8.U(6.W)\n def inOCPart3 = 9.U(6.W)\n def inOCPart4 = 10.U(6.W)\n def inOCPart5 = 11.U(6.W)\n def inOCPart6 = 12.U(6.W)\n def inOCPart7 = 13.U(6.W)\n def inMCWait0 = 14.U(6.W)\n def inMCWait1 = 15.U(6.W)\n def inMCWait2 = 16.U(6.W)\n def inMCPart0w = 17.U(6.W)\n def inMCPart1p = 18.U(6.W)\n def inMCPart1w = 19.U(6.W)\n def inMCPart2p = 20.U(6.W)\n def inMCPart2w = 21.U(6.W)\n def inMCPart3p = 22.U(6.W)\n", "right_context": " def inMCPart4p = 24.U(6.W)\n def inMCPart4w = 25.U(6.W)\n def inMCPart5p = 26.U(6.W)\n def inMCPart5w = 27.U(6.W)\n def inMCPart6p = 28.U(6.W)\n def inMCPart6w = 29.U(6.W)\n def inMCPart7p = 30.U(6.W)\n def inMCPart7w = 31.U(6.W)\n def finish = 32.U(6.W)\n val vState = RegInit(idle)\n //////////////////////define registers////////////////////////\n\n //////////////////////important signals//////////////////////\n //simplify name\n val iSigs = vdecode.io.sigs\n val eSigs = exe_reg_ctrlSigs\n val wSigs = wb_reg_ctrlSigs\n //from vdecode module\n lazy val isLdInst = vdecode.io.sigs.isLdInst || vdecode.io.sigs.isAMOInst && iSigs.funct6(0)\n lazy val isStInst = vdecode.io.sigs.isStInst || vdecode.io.sigs.isAMOInst && !iSigs.funct6(0)\n //one cycle full vector operation AL insts\n lazy val isOCFullInst = IsPopc <= iSigs.majFun && iSigs.majFun <= IsMIdx || \n IsIdx <= iSigs.majFun && iSigs.majFun <= IsMBit || \n IsMv <= iSigs.majFun && iSigs.majFun <= IsSlide1 || \n iSigs.majFun === IsFMv && iSigs.isScalarXOut || \n iSigs.majFun === IsCopy\n //multiply cycles full vector operation AL insts\n lazy val isMCFullInst = iSigs.majFun === IsCSR || iSigs.majFun === IsIota || iSigs.majFun === IsZip || \n iSigs.majFun === IsFMv && iSigs.isSEWOut\n //one cycle part vector operation AL insts\n lazy val isOCPartInst = iSigs.majFun <= IsMerge || iSigs.majFun === IsGather\n //multiply cycles part vector operation AL insts\n lazy val isMCPartInst = iSigs.majFun === IsMulDiv || iSigs.majFun === IsMulAdd || iSigs.majFun === IsRed || \n IsFMA <= iSigs.majFun && iSigs.majFun <= IsFMerge || \n IsFDiv <= iSigs.majFun && iSigs.majFun <= IsFRed\n ////////////////////////////////////////////////////////\n lazy val inOCFullState = RegEnable(isOCFullInst || iSigs.majFun === IsCSR, false.B, llInst)\n lazy val inMCFullState = eSigs.majFun === IsIota || eSigs.majFun === IsZip || \n eSigs.majFun === IsFMv && eSigs.isSEWOut\n lazy val inRedState = eSigs.majFun === IsRed || eSigs.majFun === IsFRed //for overwrite relay_reg_Data0\n lazy val inMulDivState = eSigs.majFun === IsMulDiv //for vxsat\n lazy val inShiftState = eSigs.majFun === IsShift //for vxsat\n\n ////////////////////////////////////////////////////////\n //multiply cycles part vector operation valid\n def isMCReqValid = vState === inMCWait2 && !killw || vState === inMCPart1p || \n vState === inMCPart2p || vState === inMCPart3p || \n vState === inMCPart4p || vState === inMCPart5p || \n vState === inMCPart6p || vState === inMCPart7p\n def isMCFPRespValid = vfma.io.resp.valid || vfdiv.io.resp.valid || \n vfcmp.io.resp.valid || vi2f.io.resp.valid || vf2i.io.resp.valid || \n vfwidth.io.respValid && (eSigs.majFun === IsFClass || eSigs.majFun === IsFSgnJ || \n eSigs.majFun === IsFCvt && eSigs.src1Field(2,0) >= 4.U(3.W) || \n eSigs.majFun === IsFMerge)\n def isMCRespValid = vmuldiv.io.resp.valid || vred.io.vRedOut.valid || isMCFPRespValid\n ////////////////////////////////////////////////////////\n //from vdmemreq and vdmemresp modules \n lazy val faultFirst = vdmemreq.io.faultFirst\n lazy val vSendOver = vdmemreq.io.done && eSigs.majFun === IsStore || \n vdmemreq.io.done && eSigs.majFun === IsAMO && !eSigs.funct6(0)\n lazy val vRecvOver = vdmemresp.io.vRecvOver && eSigs.majFun === IsLoad || \n vdmemresp.io.vRecvOver && eSigs.majFun === IsAMO && eSigs.funct6(0)\n\n\n //for redirection\n// def needCSR = vState === inOCFull && coreFire && eSigs.majFun === IsCSR\n def needEXEVs1 = vState === inOCFull && coreFire && eSigs.dstField === iSigs.src1Field && !eSigs.isScalarXOut\n def needEXEVs2 = vState === inOCFull && coreFire && eSigs.dstField === iSigs.src2Field && !eSigs.isScalarXOut\n def needEXEVd = vState === inOCFull && coreFire && eSigs.dstField === iSigs.dstField && !eSigs.isScalarXOut\n def needEXEV0 = vState === inOCFull && coreFire && eSigs.dstField === 0.U(5.W) && !eSigs.isScalarXOut\n def needWBVs1 = coreFire && wb_reg_enable && wSigs.dstField === iSigs.src1Field && !wSigs.isScalarXOut\n def needWBVs2 = coreFire && wb_reg_enable && wSigs.dstField === iSigs.src2Field && !wSigs.isScalarXOut\n def needWBVd = coreFire && wb_reg_enable && wSigs.dstField === iSigs.dstField && !wSigs.isScalarXOut\n def needWBV0 = coreFire && wb_reg_enable && wSigs.dstField === 0.U(5.W) && !iSigs.vm.asBool && !wSigs.isScalarXOut\n\n //vstart enable and value\n val vstartEn = exe_enable || vRecvOver || vSendOver || vdmemreq.io.mem_xcpt\n val vstartIn = MuxCase(0.U(log2Ceil(VLEN).W),\n Array(vdmemreq.io.mem_xcpt -> vdmemreq.io.mem_vstart))\n\n //ignore some operation that elements cannot be divided into sub-elements\n def noDivInst = eSigs.majFun === IsMBit || eSigs.majFun === IsPopc || eSigs.majFun === IsFirst || \n eSigs.majFun === IsMIdx || eSigs.majFun === IsIota || eSigs.majFun === IsIdx || \n eSigs.majFun === IsSlide || eSigs.majFun === IsSlide1 || eSigs.majFun === IsMv || \n eSigs.majFun === IsFMv || eSigs.majFun === IsZip || eSigs.majFun === IsCmp || \n eSigs.majFun === IsFCmp || eSigs.majFun === IsAdd && \n (eSigs.addFun === AddFun_Adc || eSigs.addFun === AddFun_Sbc || eSigs.isMLENOut) || \n eSigs.majFun === IsRed && eSigs.funct6(4,0) === RedFun_Sum\n val vediv = (if(EDIV) Mux(noDivInst, 0.U, vcsr.io.vediv) else 0.U(2.W))\n\n val vxsat = MuxCase(vadd.io.vAddSat, Array()\n ++ (if(SATMUL) Array(inMulDivState -> vmuldiv.io.vMulSat) else Nil)\n ++ (if(NCLIP) Array(inShiftState -> vshift.io.vShiftSat) else Nil))\n\n\n illInst := coreFire && vexcp.io.excpFlag\n llInst := coreFire && !vexcp.io.excpFlag\n instReady := vState === idle || vState === inOCFull\n exe_enable := MuxCase(vState === finish,\n Array(inOCFullState -> (exe_reg_enable && eInst && !killx),\n inMCFullState -> (viota.io.resp.valid || vcompress.io.respValid || \n eSigs.majFun === IsFMv && eSigs.isSEWOut)))\n\n val inStep = Wire(Vec(7, Bool()))\n inStep(0) := vState === inOCPart1 || vState === inMCPart1p || vState === inMCPart1w\n inStep(1) := vState === inOCPart2 || vState === inMCPart2p || vState === inMCPart2w\n inStep(2) := vState === inOCPart3 || vState === inMCPart3p || vState === inMCPart3w\n inStep(3) := vState === inOCPart4 || vState === inMCPart4p || vState === inMCPart4w\n inStep(4) := vState === inOCPart5 || vState === inMCPart5p || vState === inMCPart5w\n inStep(5) := vState === inOCPart6 || vState === inMCPart6p || vState === inMCPart6w\n inStep(6) := vState === inOCPart7 || vState === inMCPart7p || vState === inMCPart7w\n //////////////////////important signals//////////////////////\n\n ///////////////////wire signals to output/////////////////////\n io.reqValid := vdmemreq.io.reqValid\n io.reqAddr := vdmemreq.io.reqAddr\n io.reqTag := vdmemreq.io.reqTag\n io.reqCmd := vdmemreq.io.reqCmd\n io.reqSize := vdmemreq.io.reqSize\n io.s1Kill := vdmemreq.io.s1Kill\n io.s1Data := vdmemreq.io.s1Data\n\n io.core.req.ready := true.B\n io.core.resp.toXData := Mux(wSigs.majFun === IsCSR, vcsr.io.mem_reg_vl, wb_reg_scalarXOut)\n io.core.resp.rd := wSigs.dstField\n io.core.fflags_ready := !(inMCWait0 <= vState && vState <= finish && eSigs.wflags || wb_reg_enable && wSigs.wflags)\n io.core.vcsr_fflags.valid := wb_reg_enable && wSigs.wflags\n io.core.vcsr_fflags.bits := wb_reg_fflags\n io.core.vxsat_ready := !(inOCPart0 <= vState && vState <= finish && eSigs.isSAT || wb_reg_enable && wSigs.isSAT)\n io.core.vcsr_vxsat.valid := wb_reg_enable && wSigs.isSAT\n io.core.vcsr_vxsat.bits := wb_reg_vxsat\n io.core.vcsr_vstart := vcsr.io.vstart\n io.core.vcsr_vl := vcsr.io.mem_reg_vl //TODO see whether data conflict or not\n io.core.vcsr_vtype := vcsr.io.mem_reg_vtype //TODO see whether data conflict or not\n io.core.vxcpt_precise := faultFirst || upload_reg_illInst2 && !killw\n io.core.vxcpt_imprecise := vdmemreq.io.mem_xcpt\n io.core.vcause := Mux(faultFirst || vdmemreq.io.mem_xcpt, vdmemreq.io.mem_cause, 2.U)\n io.core.vmtval := Mux(faultFirst || vdmemreq.io.mem_xcpt, vdmemreq.io.mem_mtval, upload_reg_inst2)\n io.core.vnack := RegNext(RegNext(io.core.req.fire() && !instReady, false.B) && !killx || \n vdmemreq.io.replay, false.B) && !killm\n io.core.dcache_blocked := vState === inVLoad || vState === inVStore\n\n val fpuResp = Wire(Flipped(Decoupled(new VPUFPUResponse(FLEN))))\n fpuResp.valid := exe_reg_enable && eSigs.isScalarXOut && eSigs.majFun === IsFMv\n fpuResp.bits.toFData := vfun2.io.scalarFOut\n fpuResp.bits.rd := eSigs.dstField\n io.fpu.resp <> Queue(enq = fpuResp, entries = 2)\n io.fpu.req.rs1 := eSigs.src1Field\n ///////////////////wire signals to output/////////////////////\n\n\n//////////////////////////////////////////decode state//////////////////////////////////////\n\n vdecode.io.inst := io.core.req.bits.inst\n\n// vexcp.io.vill := Mux(needCSR, vcsr.io.villNext, vcsr.io.vill)\n// vexcp.io.vediv := Mux(needCSR, vcsr.io.vedivNext, vcsr.io.vediv)\n// vexcp.io.vsew := Mux(needCSR, vcsr.io.vsewNext, vcsr.io.vsew)\n// vexcp.io.vlmul := Mux(needCSR, vcsr.io.vlmulNext, vcsr.io.vlmul)\n vexcp.io.coreFire := coreFire\n vexcp.io.vill := vcsr.io.vill\n vexcp.io.vediv := vcsr.io.vediv\n vexcp.io.vsew := vcsr.io.vsew\n vexcp.io.vlmul := vcsr.io.vlmul\n vexcp.io.vstart := vcsr.io.vstart\n vexcp.io.src1Field := iSigs.src1Field\n vexcp.io.src2Field := iSigs.src2Field\n vexcp.io.dstField := iSigs.dstField\n vexcp.io.isALInst := iSigs.isALInst\n vexcp.io.isLdInst := iSigs.isLdInst\n vexcp.io.isStInst := iSigs.isStInst\n vexcp.io.isAMOInst := iSigs.isAMOInst\n vexcp.io.isSrc12SEW := iSigs.isSrc12SEW\n vexcp.io.isSrc22SEW := iSigs.isSrc22SEW\n vexcp.io.isVd2SEW := iSigs.isVd2SEW\n vexcp.io.isSEWOut := iSigs.isSEWOut\n vexcp.io.isMLENOut := iSigs.isMLENOut\n vexcp.io.src1Typ := iSigs.src1Typ\n vexcp.io.majFun := iSigs.majFun\n vexcp.io.mulFun := iSigs.mulFun\n vexcp.io.slideFun := iSigs.funct6(0)\n vexcp.io.nFields := iSigs.funct6(5,3)\n vexcp.io.addrMode := iSigs.funct6(1,0)\n vexcp.io.ldstWidth := iSigs.ldstWidth\n vexcp.io.vm := iSigs.vm\n vexcp.io.isFullMul := iSigs.isFullMul\n\n/////////////////////read regfile///////////////////////////\n\n val vRegFile = Mem(32, UInt(VLEN.W))\n\n //read source 1, source 2, destination 8 registers, and mask single register\n val v0 = vRegFile(0.U)\n val vs1 = for(i <- 0 until 8) yield vRegFile(iSigs.src1Field + i.U)\n val vs2 = for(i <- 0 until 8) yield vRegFile(iSigs.src2Field + i.U)\n val vdvs3 = for(i <- 0 until 8) yield vRegFile(iSigs.dstField + i.U)\n //8 vectors a set\n val vs1Full = Cat(vs1.reverse)\n val vs2Full = Cat(vs2.reverse)\n val vdvs3Full = Cat(vdvs3.reverse)\n\n//////////////////////////////////////////decode state//////////////////////////////////////\n\n\n//////////////////////////////////////exe regs assignment///////////////////////////////////\n\n exe_reg_enable := llInst\n\n when(llInst) {\n exe_reg_ctrlSigs := iSigs\n exe_reg_vs1Data := Mux(needWBVs1, wb_reg_veOut, Mux(needEXEVs1, vmask.io.veOut, vs1Full))\n exe_reg_vs2Data := Mux(needWBVs2, wb_reg_veOut, Mux(needEXEVs2, vmask.io.veOut, vs2Full))\n exe_reg_vdvs3Data := Mux(needWBVd, wb_reg_veOut, Mux(needEXEVd, vmask.io.veOut, vdvs3Full))\n exe_reg_v0Mask := Mux(needWBV0, wb_reg_vmOut, Mux(needEXEV0, vmask.io.vmOut, v0))\n }\n when(exe_reg_enable) {\n exe_reg_fromXData1 := fromXData1\n exe_reg_fromXData2 := fromXData2\n }\n when(vState === inMCWait1) {\n exe_reg_fromFData := fromFData\n }\n\n\n when(vState === inOCPart0 || vState === inMCPart0w && isMCRespValid || inRedState) { relay_reg_Data0 := vfun1.io.vSEWData }\n when((vState === inOCPart1 || vState === inMCPart1w && isMCRespValid) && !inRedState) { relay_reg_Data1 := vfun1.io.vSEWData }\n when((vState === inOCPart2 || vState === inMCPart2w && isMCRespValid) && !inRedState) { relay_reg_Data2 := vfun1.io.vSEWData }\n when((vState === inOCPart3 || vState === inMCPart3w && isMCRespValid) && !inRedState) { relay_reg_Data3 := vfun1.io.vSEWData }\n when((vState === inOCPart4 || vState === inMCPart4w && isMCRespValid) && !inRedState) { relay_reg_Data4 := vfun1.io.vSEWData }\n when((vState === inOCPart5 || vState === inMCPart5w && isMCRespValid) && !inRedState) { relay_reg_Data5 := vfun1.io.vSEWData }\n when((vState === inOCPart6 || vState === inMCPart6w && isMCRespValid) && !inRedState) { relay_reg_Data6 := vfun1.io.vSEWData }\n when((vState === inOCPart7 || vState === inMCPart7w && isMCRespValid) && !inRedState) { relay_reg_Data7 := vfun1.io.vSEWData }\n\n when(vState === finish) {\n relay_reg_vxsat := 0.U(VPUConstants.XSAT_SZ)\n }.elsewhen(eSigs.majFun === IsAdd || eSigs.majFun === IsShift || eSigs.majFun === IsMulDiv && vmuldiv.io.resp.valid) {\n relay_reg_vxsat := relay_reg_vxsat | vxsat\n }\n\n when(vState === finish) {\n relay_reg_fflags := 0.U(VPUConstants.FFLAGS_SZ.W)\n }.elsewhen(isMCFPRespValid) {\n relay_reg_fflags := relay_reg_fflags | vfun1.io.fflags\n }\n\n//////////////////////////////////////exe regs assignment///////////////////////////////////\n\n\n//////////////////////////////////////////execute state/////////////////////////////////////\n\n vcsr.io.vstartEn := vstartEn\n vcsr.io.vstartIn := vstartIn\n vcsr.io.reducevlEn := vdmemreq.io.mem_vl_valid\n vcsr.io.reducedvl := vdmemreq.io.mem_vl\n vcsr.io.enable := eSigs.majFun === IsCSR && exe_reg_enable && !killx\n vcsr.io.killm := ePipem && killm\n vcsr.io.src1Field := eSigs.src1Field\n vcsr.io.dstField := eSigs.dstField\n vcsr.io.fromXData1 := fromXData1\n vcsr.io.fromXData2 := fromXData2\n vcsr.io.vtypei := Cat(eSigs.funct6(4,0), eSigs.vm, eSigs.src2Field)\n vcsr.io.csrType := eSigs.funct6(5)\n\n vsplit.io.vs1Data := exe_reg_vs1Data\n vsplit.io.vs2Data := exe_reg_vs2Data\n vsplit.io.vdvs3Data := exe_reg_vdvs3Data\n vsplit.io.v0Mask := exe_reg_v0Mask\n vsplit.io.isSrc12SEW := eSigs.isSrc12SEW\n vsplit.io.isSrc22SEW := eSigs.isSrc22SEW\n vsplit.io.isVd2SEW := eSigs.isVd2SEW\n vsplit.io.isFullMul := eSigs.isFullMul\n vsplit.io.inStep := inStep\n\n vm2e.io.isUnmasked := eSigs.isUnmasked\n vm2e.io.isVd2SEW := eSigs.isVd2SEW\n vm2e.io.addFun := eSigs.addFun\n vm2e.io.isFullMul := eSigs.isFullMul\n vm2e.io.vediv := vediv\n vm2e.io.vsew := vcsr.io.vsew\n vm2e.io.vlmul := vcsr.io.vlmul\n vm2e.io.vl := vcsr.io.vl\n vm2e.io.vstart := vcsr.io.vstart\n vm2e.io.vm := eSigs.vm\n vm2e.io.v0m := vsplit.io.v0m\n vm2e.io.vs1m := vsplit.io.vs1m\n\n vwidth.io.isSrc22SEW := eSigs.isSrc22SEW\n vwidth.io.isVd2SEW := eSigs.isVd2SEW\n vwidth.io.sign := eSigs.sign\n vwidth.io.src1Typ := eSigs.src1Typ\n vwidth.io.majFun := eSigs.majFun\n vwidth.io.vm := eSigs.vm\n vwidth.io.vlmul := vcsr.io.vlmul\n vwidth.io.fromXData1 := Mux(exe_reg_enable, fromXData1, exe_reg_fromXData1)\n vwidth.io.src1Field := eSigs.src1Field\n vwidth.io.vs1e := vsplit.io.vs1e\n vwidth.io.vs2e := vsplit.io.vs2e\n\n valc.io.vm2e_io_carryIn := vm2e.io.carryIn\n valc.io.vm2e_io_v0merge := vm2e.io.v0merge\n valc.io.vm2e_io_v0mul := vm2e.io.v0mul\n valc.io.vm2e_io_v0maske := vm2e.io.v0maske\n valc.io.vm2e_io_v0fen := vm2e.io.v0fen\n valc.io.isFullMul := eSigs.isFullMul\n valc.io.isSrc22SEW := eSigs.isSrc22SEW\n valc.io.isVd2SEW := eSigs.isVd2SEW\n valc.io.inStep := inStep\n\n//--------------------------------------------fix point modules---------------------------------------//\n val vadd_io_vsrc1e = (if(MULADD || QMULADD) \n Mux(eSigs.majFun === IsMulAdd, vmuldiv.io.resp.bits.vMulDivOut, vwidth.io.vsrc1e)\n else \n vwidth.io.vsrc1e)\n val vadd_io_vsrc2e = (if(MULADD) \n Mux(eSigs.majFun === IsMulAdd && eSigs.prodAddWhat === Add_Vd, vsplit.io.vdvs3e, vwidth.io.vsrc2e)\n else \n vwidth.io.vsrc2e)\n vadd.io.vsrc1e := vadd_io_vsrc1e\n vadd.io.vsrc2e := vadd_io_vsrc2e\n vadd.io.carryIn := valc.io.carryIn\n vadd.io.addFun := eSigs.addFun\n vadd.io.sign := eSigs.sign\n vadd.io.vsew := vcsr.io.vsew - vediv\n vadd.io.vxrm := io.core.vcsr_vxrm\n vadd.io.isRND := eSigs.isRND\n vadd.io.isSAT := eSigs.isSAT\n\n vbit.io.vsrc1e := vwidth.io.vsrc1e\n vbit.io.vsrc2e := vwidth.io.vsrc2e\n vbit.io.bitFun := eSigs.funct6(2,0)\n\n vshift.io.vsrc1t := vwidth.io.vsrc1t\n vshift.io.vsrc2e := vwidth.io.vsrc2e\n vshift.io.shiftFun := eSigs.shiftFun\n vshift.io.isSrc22SEW := eSigs.isSrc22SEW\n vshift.io.vxrm := io.core.vcsr_vxrm\n vshift.io.isRND := eSigs.isRND\n vshift.io.isSAT := eSigs.isSAT\n vshift.io.sign := eSigs.sign\n vshift.io.vsew := vcsr.io.vsew - vediv\n\n vcmp.io.vsrc1e := vwidth.io.vsrc1e\n vcmp.io.vsrc2e := vwidth.io.vsrc2e\n vcmp.io.cmpFun := eSigs.cmpFun\n vcmp.io.sign := eSigs.sign\n vcmp.io.vlmul := vcsr.io.vlmul\n\n vmerge.io.v0merge := valc.io.v0merge\n vmerge.io.vsrc1e := vwidth.io.vsrc1e\n vmerge.io.vsrc2e := vwidth.io.vsrc2e\n vmerge.io.vsrc1f := vfwidth.io.vsrc1f\n vmerge.io.vsrc2f := vfwidth.io.vsrc2f\n\n val vmuldiv_io_vsrc2e = (if(MULADD || QMULADD)\n Mux(eSigs.majFun === IsMulAdd && eSigs.prodAddWhat === Add_Vs2, \n vsplit.io.vdvs3e, vwidth.io.vsrc2e)\n else \n vwidth.io.vsrc2e)\n vmuldiv.io.kill := false.B\n vmuldiv.io.vsew := vcsr.io.vsew - vediv\n vmuldiv.io.isVd2SEW := eSigs.isVd2SEW\n vmuldiv.io.isFullMul := eSigs.isFullMul\n vmuldiv.io.sign := eSigs.sign\n vmuldiv.io.vxrm := io.core.vcsr_vxrm\n vmuldiv.io.isRND := eSigs.isRND\n vmuldiv.io.isSAT := eSigs.isSAT\n vmuldiv.io.req.valid := isMCReqValid && (eSigs.majFun === IsMulDiv || eSigs.majFun === IsMulAdd)\n vmuldiv.io.req.bits.fn := eSigs.mulFun\n vmuldiv.io.req.bits.dw := 1.U(1.W)\n vmuldiv.io.req.bits.vsrc1e := vwidth.io.vsrc1e\n vmuldiv.io.req.bits.vsrc2e := vmuldiv_io_vsrc2e\n vmuldiv.io.req.bits.v0en := valc.io.v0mul\n vmuldiv.io.resp.ready := true.B\n\n vred.io.vsew := vcsr.io.vsew\n vred.io.redFun := eSigs.funct6(4,0)\n vred.io.enable := isMCReqValid && eSigs.majFun === IsRed\n vred.io.firstELEN := vState === inMCWait2 && !killw\n vred.io.vsrc1e := vwidth.io.vsrc1e\n vred.io.vsrc2e := vwidth.io.vsrc2e\n vred.io.vdvs3e := vsplit.io.vdvs3e\n vred.io.v0e := valc.io.v0en\n\n vrgather.io.vediv := vediv\n vrgather.io.vsew := vcsr.io.vsew\n vrgather.io.vlmul := vcsr.io.vlmul\n vrgather.io.src1Typ := eSigs.src1Typ\n vrgather.io.fromXData1 := Mux(exe_reg_enable, fromXData1, exe_reg_fromXData1)\n vrgather.io.vsrc1e := vwidth.io.vsrc1e\n vrgather.io.vsrc2e := vsplit.io.vs2E\n//--------------------------------------------fix-point modules---------------------------------------//\n\n//-----------------------------------------floating-point modules-------------------------------------//\n vfwidth.io.reqValid := isMCReqValid\n vfwidth.io.isSrc12SEW := eSigs.isSrc12SEW\n vfwidth.io.isSrc22SEW := eSigs.isSrc22SEW\n vfwidth.io.isVd2SEW := eSigs.isVd2SEW\n vfwidth.io.src1Typ := eSigs.src1Typ\n vfwidth.io.majFun := eSigs.majFun\n vfwidth.io.fcvtFun := eSigs.src1Field\n vfwidth.io.frm := io.core.vcsr_frm\n vfwidth.io.fromXData1 := Mux(exe_reg_enable, fromXData1, exe_reg_fromXData1)\n vfwidth.io.fromFData := exe_reg_fromFData //using fp scalar insts are treat as multi cycle insts\n vfwidth.io.vs1e := vsplit.io.vs1e\n vfwidth.io.vs2e := vsplit.io.vs2e\n vfwidth.io.vdvs3e := vsplit.io.vdvs3e\n\n val isFMAReq = eSigs.majFun === IsFMA || \n eSigs.majFun === IsFRed && \n (eSigs.funct6(4,0) === RedFun_FSum || \n eSigs.funct6(4,0) === RedFun_FOSum || \n eSigs.funct6(4,0) === RedFun_FWSum || \n eSigs.funct6(4,0) === RedFun_FWOSum)\n vfma.io.kill := false.B\n vfma.io.vsew := vcsr.io.vsew - vediv\n vfma.io.isVd2SEW := eSigs.isVd2SEW\n vfma.io.prodAddWhat := eSigs.prodAddWhat\n vfma.io.redsum := eSigs.majFun === IsFRed\n vfma.io.firstElen := vfwidth.io.respValid && vState === inMCPart0w\n vfma.io.req.valid := vfwidth.io.respValid && isFMAReq\n vfma.io.req.bits.fn.op := eSigs.fmaFun\n vfma.io.req.bits.fn.rm := io.core.vcsr_frm\n vfma.io.req.bits.vsrc1e := vfwidth.io.vsrc1f\n vfma.io.req.bits.vsrc2e := vfwidth.io.vsrc2f\n vfma.io.req.bits.vdvs3 := vfwidth.io.vdvs3f\n vfma.io.req.bits.v0en := valc.io.v0fen\n\n vfdiv.io.kill := false.B\n vfdiv.io.vsew := vcsr.io.vsew - vediv\n vfdiv.io.req.valid := vfwidth.io.respValid && (eSigs.majFun === IsFDiv)\n vfdiv.io.req.bits.fn.op := eSigs.funct6(1,0)\n vfdiv.io.req.bits.fn.rm := io.core.vcsr_frm\n vfdiv.io.req.bits.vsrc1e := vfwidth.io.vsrc1f\n vfdiv.io.req.bits.vsrc2e := vfwidth.io.vsrc2f\n vfdiv.io.req.bits.v0en := valc.io.v0fen\n vfdiv.io.resp.ready := true.B\n\n val isFtoIReq = eSigs.majFun === IsFCvt && eSigs.src1Field(2,0) <= 1.U(3.W)\n vf2i.io.req.valid := vfwidth.io.respValid && isFtoIReq\n vf2i.io.vsew := vcsr.io.vsew - vediv\n vf2i.io.req.bits.fn.op := eSigs.src1Field\n vf2i.io.req.bits.fn.rm := io.core.vcsr_frm\n vf2i.io.req.bits.vsrc2e := vfwidth.io.vsrc2f\n\n val isItoFReq = eSigs.majFun === IsFCvt && \n (1.U(3.W) < eSigs.src1Field(2,0) && eSigs.src1Field(2,0) < 4.U(3.W))\n vi2f.io.req.valid := vfwidth.io.respValid && isItoFReq\n vi2f.io.vsew := vcsr.io.vsew - vediv\n vi2f.io.req.bits.fn.op := eSigs.src1Field\n vi2f.io.req.bits.fn.rm := io.core.vcsr_frm\n vi2f.io.req.bits.vsrc2e := vwidth.io.vsrc2e\n vi2f.io.req.bits.v0en := valc.io.v0fen\n\n val isFCmpReq = eSigs.majFun === IsFCmp || \n eSigs.majFun === IsFRed && \n (eSigs.funct6(4,0) === RedFun_FMin || \n eSigs.funct6(4,0) === RedFun_FMax)\n vfcmp.io.req.valid := vfwidth.io.respValid && isFCmpReq\n vfcmp.io.req.bits.fn.op := eSigs.cmpFun\n vfcmp.io.req.bits.fn.rm := io.core.vcsr_frm\n vfcmp.io.vsew := vcsr.io.vsew\n vfcmp.io.vlmul := vcsr.io.vlmul\n vfcmp.io.redsum := eSigs.majFun === IsFRed\n vfcmp.io.firstElen := vfwidth.io.respValid && vState === inMCPart0w\n vfcmp.io.req.bits.vsrc1e := vfwidth.io.vsrc1f\n vfcmp.io.req.bits.vsrc2e := vfwidth.io.vsrc2f\n vfcmp.io.req.bits.v0en := valc.io.v0fen\n\n vfclass.io.vsrc2f := vfwidth.io.vsrc2f\n\n vfsgnj.io.vsrc1f := vfwidth.io.vsrc1f\n vfsgnj.io.vsrc2f := vfwidth.io.vsrc2f\n vfsgnj.io.fsgnjFun := eSigs.funct6(1,0)\n\n vfun1.io.isSEWOut := eSigs.isSEWOut\n vfun1.io.isMLENOut := eSigs.isMLENOut\n vfun1.io.isVd2SEW := eSigs.isVd2SEW\n vfun1.io.majFun := eSigs.majFun\n vfun1.io.fcvtFun := eSigs.src1Field\n vfun1.io.isFullMul := eSigs.isFullMul\n vfun1.io.isFMAReq := isFMAReq\n vfun1.io.isFCmpReq := isFCmpReq\n vfun1.io.vsew := vcsr.io.vsew - vediv\n vfun1.io.vAddCarry := vadd.io.vAddCarry\n vfun1.io.vAddSum := vadd.io.vAddSum\n vfun1.io.vBitwise := vbit.io.vBitwise\n vfun1.io.vShiftOut := vshift.io.vShiftOut\n vfun1.io.vCmpOut := vcmp.io.vCmpOut\n vfun1.io.vMinMaxOut := vcmp.io.vMinMaxOut\n vfun1.io.vMergeOut := vmerge.io.vMergeOut\n vfun1.io.vMulDivOut := vmuldiv.io.resp.bits.vMulDivOut\n vfun1.io.vRedOut := vred.io.vRedOut.bits\n vfun1.io.vRGatherOut := vrgather.io.vRGatherOut\n vfun1.io.vFClassOut := vfclass.io.vFClassOut\n vfun1.io.vFtoIOut := vf2i.io.resp.bits.vFPToIntOut\n vfun1.io.vItoFOut := vi2f.io.resp.bits.vIntToFPOut\n vfun1.io.vsrc2f := vfwidth.io.vsrc2f\n vfun1.io.vFMAOut := vfma.io.resp.bits.vFMAOut\n vfun1.io.vFDivOut := vfdiv.io.resp.bits.vFDivSqrtOut\n vfun1.io.vFCmpOut := vfcmp.io.resp.bits.vFCmpOut\n vfun1.io.vFMinMaxOut := vfcmp.io.resp.bits.vFMinMaxCmpOut\n vfun1.io.vFMergeOut := vmerge.io.vFMergeOut\n vfun1.io.vFSgnJOut := vfsgnj.io.vFSgnJOut\n vfun1.io.v0fen := valc.io.v0fexc\n vfun1.io.vFMAExc := vfma.io.resp.bits.exc\n vfun1.io.vFDivExc := vfdiv.io.resp.bits.exc\n vfun1.io.vFCmpExc := vfcmp.io.resp.bits.exc\n vfun1.io.vItoFExc := vi2f.io.resp.bits.exc\n vfun1.io.vFtoIExc := vf2i.io.resp.bits.exc\n vfun1.io.vFtoFExc := vfwidth.io.vFtoFExc\n\n vpopc.io.vs2m := vsplit.io.vs2m\n vpopc.io.v0m := vsplit.io.v0m\n vpopc.io.vsew := vcsr.io.vsew\n vpopc.io.vlmul := vcsr.io.vlmul\n vpopc.io.vm := eSigs.vm\n\n vmidx.io.vsew := vcsr.io.vsew\n vmidx.io.vlmul := vcsr.io.vlmul\n vmidx.io.vm := eSigs.vm\n vmidx.io.minIdxFun := eSigs.src1Field(1,0)\n vmidx.io.vs2m := vsplit.io.vs2m\n vmidx.io.v0m := vsplit.io.v0m\n\n viota.io.req.valid := eSigs.majFun === IsIota && vState === inMCFull\n viota.io.req.bits.vs2 := exe_reg_vs2Data(VLEN-1,0)\n viota.io.req.bits.v0 := exe_reg_v0Mask\n viota.io.resp.ready := true.B\n viota.io.vsew := vcsr.io.vsew\n viota.io.vlmul := vcsr.io.vlmul\n viota.io.vm := eSigs.vm\n\n vmv.io.fromXData1 := fromXData1\n vmv.io.fromFData := exe_reg_fromFData\n vmv.io.vs2E := vsplit.io.vs2E\n vmv.io.vdvs3E := vsplit.io.vdvs3E\n vmv.io.vsew := vcsr.io.vsew\n\n vslide.io.vsrc1e := vwidth.io.vsrc1e\n vslide.io.vs2Data := exe_reg_vs2Data\n vslide.io.vl := vcsr.io.vl\n vslide.io.vsew := vcsr.io.vsew\n vslide.io.vlmul := vcsr.io.vlmul\n vslide.io.majFun := eSigs.majFun\n vslide.io.slideFun := eSigs.funct6(0)\n\n vcompress.io.vs1m := vm2e.io.vs1zipm\n vcompress.io.vs2e := vsplit.io.vs2E\n vcompress.io.vdvs3e := vsplit.io.vdvs3E\n vcompress.io.enable := eSigs.majFun === IsZip && vState === inMCFull\n vcompress.io.kill := false.B //TODO release value\n vcompress.io.vsew := vcsr.io.vsew\n vcompress.io.vlmul := vcsr.io.vlmul\n\n val vSEWFullData = Cat(relay_reg_Data7, relay_reg_Data6, relay_reg_Data5, relay_reg_Data4, \n relay_reg_Data3, relay_reg_Data2, relay_reg_Data1, relay_reg_Data0)\n val vSEWHalfData = Cat(relay_reg_Data7(ELEN/2-1,0), relay_reg_Data6(ELEN/2-1,0), relay_reg_Data5(ELEN/2-1,0), \n relay_reg_Data4(ELEN/2-1,0), relay_reg_Data3(ELEN/2-1,0), relay_reg_Data2(ELEN/2-1,0), \n relay_reg_Data1(ELEN/2-1,0), relay_reg_Data0(ELEN/2-1,0))\n vfun2.io.majFun := eSigs.majFun\n vfun2.io.vlmul := vcsr.io.vlmul\n vfun2.io.vSEWData := Mux(!eSigs.isSrc12SEW && eSigs.isSrc22SEW && !eSigs.isVd2SEW, vSEWHalfData, vSEWFullData)\n vfun2.io.vIotaOut := viota.io.resp.bits.vIotaOut\n vfun2.io.vIndexOut := vidx.io.vIndexOut\n vfun2.io.vSlideOut := vslide.io.vSlideOut\n vfun2.io.vCompressOut := vcompress.io.vCompressOut\n vfun2.io.vFromXOut := vmv.io.vFromXOut\n vfun2.io.vFromFOut := vmv.io.vFromFOut\n vfun2.io.vMSetOut := vmidx.io.vMSetOut\n vfun2.io.vMBitwise := vbit.io.vMBitwise\n vfun2.io.vPopcOut := vpopc.io.vPopcOut\n vfun2.io.vMinIndex := vmidx.io.vMinIndex.asUInt\n vfun2.io.vXToXData := vmv.io.vXToXData\n vfun2.io.vFToXData := vmv.io.vFToXData\n vfun2.io.vFToFData := vmv.io.vFToFData\n\n vmask.io.vsrc1e := vwidth.io.vsrc1e\n vmask.io.v0maske := vm2e.io.v0maske\n vmask.io.vSEWOut := vfun2.io.vSEWOut\n vmask.io.vdvs3e := vsplit.io.vdvs3E\n vmask.io.v0maskm := vm2e.io.v0maskm\n vmask.io.vMLENOut := vfun2.io.vMLENOut\n vmask.io.vdm := vsplit.io.vdm\n vmask.io.vs2Data := exe_reg_vs2Data\n vmask.io.majFun := eSigs.majFun\n vmask.io.isFullMul := eSigs.isFullMul\n vmask.io.slideFun := eSigs.funct6(0)\n vmask.io.isVd2SEW := eSigs.isVd2SEW\n vmask.io.vediv := vediv\n vmask.io.vsew := vcsr.io.vsew\n vmask.io.vlmul := vcsr.io.vlmul\n\n//////////////////////////////////////////execute state/////////////////////////////////////\n\n\n/////////////////////////////////////////mem state//////////////////////////////////////////\n\n vdmemwidth.io.vsew := vcsr.io.vsew\n vdmemwidth.io.vs2e := vsplit.io.vs2E\n\n vdmemreq.io.fromXData1 := Mux(exe_reg_enable, fromXData1, exe_reg_fromXData1)\n vdmemreq.io.fromXData2 := Mux(exe_reg_enable, fromXData2, exe_reg_fromXData2)\n vdmemreq.io.vs2toXlen := vdmemwidth.io.vs2toXlen\n vdmemreq.io.vdvs3e8 := vsplit.io.vdvs3E.e8\n vdmemreq.io.vdvs3e16 := vsplit.io.vdvs3E.e16\n vdmemreq.io.vdvs3e32 := vsplit.io.vdvs3E.e32\n vdmemreq.io.vdvs3e64 := vsplit.io.vdvs3E.e64\n vdmemreq.io.v0m1 := vsplit.io.v0m.m1\n vdmemreq.io.v0m2 := vsplit.io.v0m.m2\n vdmemreq.io.v0m4 := vsplit.io.v0m.m4\n vdmemreq.io.v0m8 := vsplit.io.v0m.m8\n vdmemreq.io.v0m16 := vsplit.io.v0m.m16\n vdmemreq.io.v0m32 := vsplit.io.v0m.m32\n vdmemreq.io.v0m64 := vsplit.io.v0m.m64\n vdmemreq.io.vm := eSigs.vm\n vdmemreq.io.vsew := vcsr.io.vsew\n vdmemreq.io.vlmul := vcsr.io.vlmul\n vdmemreq.io.vl := vcsr.io.vl\n vdmemreq.io.majFun := eSigs.majFun\n vdmemreq.io.addrMode := eSigs.funct6(1,0)\n vdmemreq.io.ldstWidth := eSigs.ldstWidth\n vdmemreq.io.nFields := eSigs.funct6(5,3)\n vdmemreq.io.lumop := eSigs.src2Field\n vdmemreq.io.amoop := eSigs.funct6(5,1)\n vdmemreq.io.reqReady := io.reqReady\n vdmemreq.io.s2Nack := io.s2Nack\n vdmemreq.io.enable := mPipew && !killw && vcsr.io.vl =/= 0.U(XLEN.W)\n vdmemreq.io.respValid := io.respValid\n vdmemreq.io.respTag := io.respTag\n vdmemreq.io.killm := false.B\n vdmemreq.io.eret := io.core.eret\n vdmemreq.io.respS2Xcpt := io.respS2Xcpt\n vdmemreq.io.mem_xcpt_resp:= io.core.vxcpt_imprecise_resp\n vdmemreq.io.killx := false.B\n vdmemreq.io.killw := false.B\n vdmemreq.io.wd := eSigs.funct6(0)\n \n vdmemresp.io.lumop := eSigs.src2Field\n vdmemresp.io.vsew := vcsr.io.vsew\n vdmemresp.io.vlmul := vcsr.io.vlmul\n vdmemresp.io.vl := vcsr.io.vl\n vdmemresp.io.mEnable := mPipew && !killw && vcsr.io.vl =/= 0.U(XLEN.W)\n vdmemresp.io.wd := eSigs.funct6(0)\n vdmemresp.io.vm := eSigs.vm\n vdmemresp.io.sign := eSigs.sign\n vdmemresp.io.majFun := eSigs.majFun\n vdmemresp.io.nFields := eSigs.funct6(5,3)\n vdmemresp.io.stopLoad := vdmemreq.io.stopLoad\n vdmemresp.io.killm := false.B\n vdmemresp.io.faultFirst := faultFirst\n vdmemresp.io.mDone := vdmemreq.io.done\n vdmemresp.io.respValid := io.respValid\n vdmemresp.io.respTag := io.respTag\n vdmemresp.io.respSize := io.respSize\n vdmemresp.io.respHasData := io.respHasData\n vdmemresp.io.respData := io.respData\n vdmemresp.io.vdvs3e := vsplit.io.vdvs3E\n vdmemresp.io.v0e := vm2e.io.v0merge\n// vdmemresp.io.v0m := vsplit.io.v0m\n\n\n/////////////////////////////////////////mem state//////////////////////////////////////////\n\n//////////////////////////////////////////wb state//////////////////////////////////////////\n\n val alwben = vcsr.io.vl =/= 0.U(XLEN.W) && vcsr.io.vstart < vcsr.io.vl && \n wSigs.majFun =/= IsCopy && wb_reg_enable\n val ldwben = vcsr.io.vl =/= 0.U(XLEN.W) && vcsr.io.vstart < vcsr.io.vl && vRecvOver && vState === inVLoad\n val cpwben = (if(COPY) wSigs.majFun === IsCopy && wb_reg_enable else false.B)\n\n val veIn = Wire(UInt((8*VLEN).W))\n val isVeOut = (alwben || cpwben) && wSigs.isSEWOut\n val isVmOut = alwben && wSigs.isMLENOut\n val isVRecv = ldwben && eSigs.isSEWOut\n// && (mem_reg_ctrlSigs.majFun === IsLoad || mem_reg_ctrlSigs.majFun === IsAMO)\n\n val wbvlmul = (vcsr.io.vlmul + wSigs.isVd2SEW + wSigs.isFullMul) & 3.U(2.W)\n\n lazy val alwen1 = alwben && (wSigs.isSEWOut || wSigs.isMLENOut)\n lazy val alwen2 = alwben && wSigs.isSEWOut && wbvlmul >= DoubReg\n lazy val alwen3 = alwben && wSigs.isSEWOut && wbvlmul >= QuadReg\n lazy val alwen4 = alwben && wSigs.isSEWOut && wbvlmul >= QuadReg\n lazy val alwen5 = alwben && wSigs.isSEWOut && wbvlmul === OctuReg\n lazy val alwen6 = alwben && wSigs.isSEWOut && wbvlmul === OctuReg\n lazy val alwen7 = alwben && wSigs.isSEWOut && wbvlmul === OctuReg\n lazy val alwen8 = alwben && wSigs.isSEWOut && wbvlmul === OctuReg\n\n val nFields = ((eSigs.funct6(5,3) +& 1.U(3.W)) << vcsr.io.vlmul)(3,0)\n lazy val ldwen1 = ldwben && eSigs.isSEWOut\n lazy val ldwen2 = ldwben && eSigs.isSEWOut && (vcsr.io.vlmul >= DoubReg || nFields >= 2.U(4.W))\n lazy val ldwen3 = ldwben && eSigs.isSEWOut && (vcsr.io.vlmul >= QuadReg || nFields >= 3.U(4.W))\n lazy val ldwen4 = ldwben && eSigs.isSEWOut && (vcsr.io.vlmul >= QuadReg || nFields >= 4.U(4.W))\n lazy val ldwen5 = ldwben && eSigs.isSEWOut && (vcsr.io.vlmul === OctuReg || nFields >= 5.U(4.W))\n lazy val ldwen6 = ldwben && eSigs.isSEWOut && (vcsr.io.vlmul === OctuReg || nFields >= 6.U(4.W))\n lazy val ldwen7 = ldwben && eSigs.isSEWOut && (vcsr.io.vlmul === OctuReg || nFields >= 7.U(4.W))\n lazy val ldwen8 = ldwben && eSigs.isSEWOut && (vcsr.io.vlmul === OctuReg || nFields === 8.U(4.W))\n\n lazy val cpwen1 = cpwben\n lazy val cpwen2 = cpwben && wSigs.src1Field >= TwoField\n lazy val cpwen3 = cpwben && wSigs.src1Field >= FouField\n lazy val cpwen4 = cpwben && wSigs.src1Field >= FouField\n lazy val cpwen5 = cpwben && wSigs.src1Field === EigField\n lazy val cpwen6 = cpwben && wSigs.src1Field === EigField\n lazy val cpwen7 = cpwben && wSigs.src1Field === EigField\n lazy val cpwen8 = cpwben && wSigs.src1Field === EigField\n\n val wen1 = alwen1 || ldwen1 || cpwen1\n val wen2 = alwen2 || ldwen2 || cpwen2\n val wen3 = alwen3 || ldwen3 || cpwen3\n val wen4 = alwen4 || ldwen4 || cpwen4\n val wen5 = alwen5 || ldwen5 || cpwen5\n val wen6 = alwen6 || ldwen6 || cpwen6\n val wen7 = alwen7 || ldwen7 || cpwen7\n val wen8 = alwen8 || ldwen8 || cpwen8\n\n veIn := MuxCase(0.U((8*VLEN).W),\n Array(isVeOut -> wb_reg_veOut,\n isVmOut -> Cat(0.U((7*VLEN).W), wb_reg_vmOut),\n isVRecv -> vdmemresp.io.vRecvOut))\n\n val vaddr = Mux(alwben, wSigs.dstField, eSigs.dstField)\n\n when(wen1) { vRegFile(vaddr) := veIn(VLEN-1, 0) }\n when(wen2) { vRegFile(vaddr + 1.U) := veIn(2*VLEN-1, VLEN) }\n when(wen3) { vRegFile(vaddr + 2.U) := veIn(3*VLEN-1, 2*VLEN) }\n when(wen4) { vRegFile(vaddr + 3.U) := veIn(4*VLEN-1, 3*VLEN) }\n when(wen5) { vRegFile(vaddr + 4.U) := veIn(5*VLEN-1, 4*VLEN) }\n when(wen6) { vRegFile(vaddr + 5.U) := veIn(6*VLEN-1, 5*VLEN) }\n when(wen7) { vRegFile(vaddr + 6.U) := veIn(7*VLEN-1, 6*VLEN) }\n when(wen8) { vRegFile(vaddr + 7.U) := veIn(8*VLEN-1, 7*VLEN) }\n\n//////////////////////////////////////////wb state//////////////////////////////////////////\n\n\n/////////////////////////////////////////control path///////////////////////////////////////\n\n val exevlmul = (vcsr.io.vlmul + \n (eSigs.isVd2SEW || eSigs.isSrc22SEW) + \n eSigs.isFullMul) & 3.U(2.W)\n def killEXE = exe_reg_enable && killx || ePipem && killm || ePipew && killw\n def killMEM = exe_reg_enable && killx || mPipem && killm || mPipew && killw\n def killILL = upload_reg_illInst0 && killx || upload_reg_illInst1 && killm || upload_reg_illInst2\n switch(vState) {\n is(idle) {\n when(illInst) {\n vState := inExpt\n }.elsewhen(llInst && isLdInst) {\n vState := inVLoad\n }.elsewhen(llInst && isStInst) {\n vState := inVStore\n }.elsewhen(llInst && isOCFullInst) {\n vState := inOCFull\n }.elsewhen(llInst && isMCFullInst) {\n vState := inMCWait0 //TODO can kill module inside process\n }.elsewhen(llInst && isOCPartInst) {\n vState := inOCPart0\n }.elsewhen(llInst && isMCPartInst) {\n vState := inMCWait0\n }\n }\n is(inVLoad) {\n when(vRecvOver || killMEM || faultFirst || vcsr.io.vl === 0.U(XLEN.W)) {\n vState := idle\n }\n }\n is(inVStore) {\n when(vSendOver || killMEM || faultFirst || vcsr.io.vl === 0.U(XLEN.W)) {\n vState := idle\n }\n }\n is(inExpt) {\n when(killILL) {\n vState := idle\n }\n }\n is(inOCFull) {\n when(!coreFire) {\n vState := idle\n }.elsewhen(illInst) {\n vState := inExpt\n }.elsewhen(killx || llInst && isLdInst) {\n vState := inVLoad\n }.elsewhen(killx || llInst && isStInst) {\n vState := inVStore\n }.elsewhen(killx || llInst && isMCFullInst) {\n vState := inMCWait0\n }.elsewhen(killx || llInst && isOCPartInst) {\n vState := inOCPart0\n }.elsewhen(killx || llInst && isMCPartInst) {\n vState := inMCWait0\n }\n }\n is(inMCFull) {\n when(vcompress.io.respValid || viota.io.resp.valid || \n eSigs.majFun === IsFMv && eSigs.isSEWOut || killEXE) {\n vState := idle\n }\n }\n is(inOCPart0) {\n when(exe_reg_enable && killx) {\n vState := idle\n }.elsewhen(exevlmul === SingReg) {\n vState := finish\n }.otherwise {\n vState := inOCPart1\n }\n }\n is(inOCPart1) {\n when(ePipem && killm) {\n vState := idle\n }.elsewhen(exevlmul === DoubReg) {\n vState := finish\n }.otherwise {\n vState := inOCPart2\n }\n }\n is(inOCPart2) {\n when(ePipew && killw) {\n vState := idle\n }.otherwise {\n vState := inOCPart3\n }\n }\n is(inOCPart3) {\n when(exevlmul === QuadReg) {\n vState := finish\n }.otherwise {\n vState := inOCPart4\n }\n }\n is(inOCPart4) {\n vState := inOCPart5\n }\n is(inOCPart5) {\n vState := inOCPart6\n }\n is(inOCPart6) {\n vState := inOCPart7\n }\n is(inOCPart7) {\n vState := finish\n }\n is(inMCWait0) {\n when(exe_reg_enable && killx) {\n vState := idle\n }.otherwise {\n vState := inMCWait1\n }\n }\n is(inMCWait1) {\n when(ePipem && killm || eSigs.majFun === IsCSR) {\n vState := idle\n }.otherwise {\n vState := inMCWait2\n }\n }\n is(inMCWait2) {\n when(ePipew && killw) {\n vState := idle\n }.elsewhen(inMCFullState) {\n vState := inMCFull\n }.otherwise {\n vState := inMCPart0w\n }\n }\n is(inMCPart0w) {\n when(exevlmul === SingReg && isMCRespValid) {\n vState := finish\n }.elsewhen(exevlmul =/= SingReg && isMCRespValid) {\n vState := inMCPart1p\n }\n }\n is(inMCPart1p) {\n vState := inMCPart1w\n }\n is(inMCPart1w) {\n when(exevlmul === DoubReg && isMCRespValid) {\n vState := finish\n }.elsewhen(exevlmul =/= DoubReg && isMCRespValid) {\n vState := inMCPart2p\n }\n }\n is(inMCPart2p) {\n vState := inMCPart2w\n }\n is(inMCPart2w) {\n when(isMCRespValid) {\n vState := inMCPart3p\n }\n }\n is(inMCPart3p) {\n vState := inMCPart3w\n }\n is(inMCPart3w) {\n when(exevlmul === QuadReg && isMCRespValid) {\n vState := finish\n }.elsewhen(exevlmul =/= QuadReg && isMCRespValid) {\n vState := inMCPart4p\n }\n }\n is(inMCPart4p) {\n vState := inMCPart4w\n }\n is(inMCPart4w) {\n when(isMCRespValid) {\n vState := inMCPart5p\n }\n }\n is(inMCPart5p) {\n vState := inMCPart5w\n }\n is(inMCPart5w) {\n when(isMCRespValid) {\n vState := inMCPart6p\n }\n }\n is(inMCPart6p) {\n vState := inMCPart6w\n }\n is(inMCPart6w) {\n when(isMCRespValid) {\n vState := inMCPart7p\n }\n }\n is(inMCPart7p) {\n vState := inMCPart7w\n }\n is(inMCPart7w) {\n when(isMCRespValid) {\n vState := finish\n }\n }\n is(finish) {\n vState := idle\n }\n }\n\n}\n", "groundtruth": " def inMCPart3w = 23.U(6.W)\n", "crossfile_context": ""}
{"task_id": "rocket_chip_vpu", "path": "rocket_chip_vpu/vpu/src/main/scala/VSplit.scala", "left_context": "// See LICENSE.UCTECHIP for license details.\n// See LICENSE.SZU for license details.\n/************************************************************\n*\n* Filename : VSplit.scala\n* Author : liangzh\n* Revision : 2019/04/22\n* Company : UC TECH IP\n* Department : MAG\n* Description : split 8VLEN data to SEW or MLEN width data\n*\n* io.vs1Data : input[8VLEN-1:0], data, to be split\n* io.vs2Data : input[8VLEN-1:0], data, to be split\n* io.vdvs3Data : input[8VLEN-1:0], data, to be split\n* io.v0Mask : input[VLEN-1:0], data, to be split\n* io.isSrc12SEW : input, control, showing whether source 1 is double SEW width or not\n* io.isSrc22SEW : input, control, showing whether source 2 is double SEW width or not\n* io.isVd2SEW : input, control, showing whether destination is double SEW width or not\n or quadruple SEW width for multiply-add\n* io.isFullMul : input, control, showing whether the multiply product is double SEW width or not\n* io.inStep : input, vector, control, showing in which step during rolling calculation\n* io.vs1e : output, bundle of vectors, data, split vs1Data into SEW width, for rolling calculation\n* io.vs2e : output, bundle of vectors, data, split vs2Data into SEW width, for rolling calculation\n* io.vdvs3e : output, bundle of vectors, data, split vdvs3Data into SEW width, for rolling calculation\n* io.vs1E : output, bundle of vectors, data, split vs1Data into SEW width, for full elements calculation\n* io.vs2E : output, bundle of vectors, data, split vs2Data into SEW width, for full elements calculation\n* io.vdvs3E : output, bundle of vectors, data, split vdvs3Data into SEW width, for full elements calculation\n* io.vs1m : output bundle of vectors, data, split vs1Data into MLEN width\n* io.vs2m : output bundle of vectors, data, split vs2Data into MLEN width\n* io.vdm : output bundle of vectors, data, split vdvs3Data into MLEN width\n* io.v0m : output bundle of vectors, data, split v0Mask into MLEN width\n*\n************************************************************/\npackage vpu\n\nimport chisel3._\nimport chisel3.util._\n\nclass VSplit(params: VPUParams) extends VModule(params) {\n require(VLEN == ELEN) //temporary require\n\n val io = IO(new Bundle {\n val vs1Data = Input(UInt((8*VLEN).W))\n val vs2Data = Input(UInt((8*VLEN).W))\n val vdvs3Data = Input(UInt((8*VLEN).W))\n val v0Mask = Input(UInt(VLEN.W))\n\n val isSrc12SEW = Input(Bool())\n val isSrc22SEW = Input(Bool())\n val isVd2SEW = Input(Bool())\n val isFullMul = Input(Bool())\n val inStep = Input(Vec(7, Bool()))\n\n val vs1e = Output(new SEWVec)\n val vs2e = Output(new SEWVec)\n val vdvs3e = Output(new SEWVec)\n\n val vs1E = Output(new FullSEWVec)\n val vs2E = Output(new FullSEWVec)\n val vdvs3E = Output(new FullSEWVec)\n\n val vs1m = Output(new MLENVec)\n val vs2m = Output(new MLENVec)\n val vdm = Output(new MLENVec)\n val v0m = Output(new MLENVec)\n\n val vs1d = Output(new SEWEDIVVec)\n val vs2d = Output(new SEWEDIVVec)\n })\n\n val vs1Data0 = Wire(UInt(ELEN.W))\n val vs1Data1 = Wire(UInt(ELEN.W))\n val vs1Data2 = Wire(UInt(ELEN.W))\n val needvs1Data1 = !io.isSrc12SEW && (io.isSrc22SEW || io.isVd2SEW) && !io.isFullMul || \n !io.isSrc12SEW && !io.isSrc22SEW && !io.isVd2SEW && io.isFullMul\n val needvs1Data2 = !io.isSrc12SEW && !io.isSrc22SEW && io.isVd2SEW && io.isFullMul\n val vs1Data = Mux(needvs1Data2, vs1Data2, Mux(needvs1Data1, vs1Data1, vs1Data0))\n vs1Data0 := MuxCase(io.vs1Data,\n Array(io.inStep(0) -> (io.vs1Data >> ELEN),\n io.inStep(1) -> (io.vs1Data >> 2*ELEN),\n io.inStep(2) -> (io.vs1Data >> 3*ELEN),\n io.inStep(3) -> (io.vs1Data >> 4*ELEN),\n io.inStep(4) -> (io.vs1Data >> 5*ELEN),\n io.inStep(5) -> (io.vs1Data >> 6*ELEN),\n io.inStep(6) -> (io.vs1Data >> 7*ELEN)))\n vs1Data1 := MuxCase(io.vs1Data,\n Array(io.inStep(0) -> (io.vs1Data >> ELEN/2),\n io.inStep(1) -> (io.vs1Data >> 2*ELEN/2),\n io.inStep(2) -> (io.vs1Data >> 3*ELEN/2),\n io.inStep(3) -> (io.vs1Data >> 4*ELEN/2),\n io.inStep(4) -> (io.vs1Data >> 5*ELEN/2),\n io.inStep(5) -> (io.vs1Data >> 6*ELEN/2),\n io.inStep(6) -> (io.vs1Data >> 7*ELEN/2)))\n vs1Data2 := MuxCase(io.vs1Data,\n Array(io.inStep(0) -> (io.vs1Data >> ELEN/4),\n io.inStep(1) -> (io.vs1Data >> 2*ELEN/4),\n io.inStep(2) -> (io.vs1Data >> 3*ELEN/4),\n io.inStep(3) -> (io.vs1Data >> 4*ELEN/4),\n io.inStep(4) -> (io.vs1Data >> 5*ELEN/4),\n io.inStep(5) -> (io.vs1Data >> 6*ELEN/4),\n io.inStep(6) -> (io.vs1Data >> 7*ELEN/4)))\n\n val vs2Data0 = Wire(UInt(ELEN.W))\n val vs2Data1 = Wire(UInt(ELEN.W))\n val vs2Data2 = Wire(UInt(ELEN.W))\n val needvs2Data1 = !io.isSrc22SEW && io.isVd2SEW || io.isFullMul\n val needvs2Data2 = !io.isSrc22SEW && io.isVd2SEW && io.isFullMul\n val vs2Data = Mux(needvs2Data2, vs2Data2, Mux(needvs2Data1, vs2Data1, vs2Data0))\n vs2Data0 := MuxCase(io.vs2Data,\n Array(io.inStep(0) -> (io.vs2Data >> ELEN),\n io.inStep(1) -> (io.vs2Data >> 2*ELEN),\n io.inStep(2) -> (io.vs2Data >> 3*ELEN),\n io.inStep(3) -> (io.vs2Data >> 4*ELEN),\n io.inStep(4) -> (io.vs2Data >> 5*ELEN),\n io.inStep(5) -> (io.vs2Data >> 6*ELEN),\n io.inStep(6) -> (io.vs2Data >> 7*ELEN)))\n vs2Data1 := MuxCase(io.vs2Data,\n Array(io.inStep(0) -> (io.vs2Data >> ELEN/2),\n io.inStep(1) -> (io.vs2Data >> 2*ELEN/2),\n io.inStep(2) -> (io.vs2Data >> 3*ELEN/2),\n io.inStep(3) -> (io.vs2Data >> 4*ELEN/2),\n io.inStep(4) -> (io.vs2Data >> 5*ELEN/2),\n io.inStep(5) -> (io.vs2Data >> 6*ELEN/2),\n io.inStep(6) -> (io.vs2Data >> 7*ELEN/2)))\n vs2Data2 := MuxCase(io.vs2Data,\n Array(io.inStep(0) -> (io.vs2Data >> ELEN/4),\n io.inStep(1) -> (io.vs2Data >> 2*ELEN/4),\n io.inStep(2) -> (io.vs2Data >> 3*ELEN/4),\n io.inStep(3) -> (io.vs2Data >> 4*ELEN/4),\n io.inStep(4) -> (io.vs2Data >> 5*ELEN/4),\n io.inStep(5) -> (io.vs2Data >> 6*ELEN/4),\n io.inStep(6) -> (io.vs2Data >> 7*ELEN/4)))\n\n val vdData = Wire(UInt(ELEN.W))\n vdData := MuxCase(io.vdvs3Data,\n Array(io.inStep(0) -> (io.vdvs3Data >> ELEN),\n io.inStep(1) -> (io.vdvs3Data >> 2*ELEN),\n io.inStep(2) -> (io.vdvs3Data >> 3*ELEN),\n io.inStep(3) -> (io.vdvs3Data >> 4*ELEN),\n io.inStep(4) -> (io.vdvs3Data >> 5*ELEN),\n io.inStep(5) -> (io.vdvs3Data >> 6*ELEN),\n io.inStep(6) -> (io.vdvs3Data >> 7*ELEN)))\n\n//split vs1Data into SEW width vectors\n for(i <- 0 until e8Depth) io.vs1e.e8(i) := vs1Data(8*(i+1)-1, 8*i)\n for(i <- 0 until e16Depth) io.vs1e.e16(i) := vs1Data(16*(i+1)-1, 16*i)\n for(i <- 0 until e32Depth) io.vs1e.e32(i) := vs1Data(32*(i+1)-1, 32*i)\n for(i <- 0 until e64Depth) io.vs1e.e64(i) := vs1Data(64*(i+1)-1, 64*i)\n for(i <- 0 until e128Depth) io.vs1e.e128(i) := vs1Data(128*(i+1)-1, 128*i)\n for(i <- 0 until e256Depth) io.vs1e.e256(i) := vs1Data(256*(i+1)-1, 256*i)\n for(i <- 0 until e512Depth) io.vs1e.e512(i) := vs1Data(512*(i+1)-1, 512*i)\n for(i <- 0 until e1024Depth) io.vs1e.e1024(i) := vs1Data(1024*(i+1)-1, 1024*i)\n//split vs2Data into SEW width vectors\n for(i <- 0 until e8Depth) io.vs2e.e8(i) := vs2Data(8*(i+1)-1, 8*i)\n for(i <- 0 until e16Depth) io.vs2e.e16(i) := vs2Data(16*(i+1)-1, 16*i)\n for(i <- 0 until e32Depth) io.vs2e.e32(i) := vs2Data(32*(i+1)-1, 32*i)\n for(i <- 0 until e64Depth) io.vs2e.e64(i) := vs2Data(64*(i+1)-1, 64*i)\n for(i <- 0 until e128Depth) io.vs2e.e128(i) := vs2Data(128*(i+1)-1, 128*i)\n for(i <- 0 until e256Depth) io.vs2e.e256(i) := vs2Data(256*(i+1)-1, 256*i)\n for(i <- 0 until e512Depth) io.vs2e.e512(i) := vs2Data(512*(i+1)-1, 512*i)\n for(i <- 0 until e1024Depth) io.vs2e.e1024(i) := vs2Data(1024*(i+1)-1, 1024*i)\n//split vdvs3Data into SEW width vectors\n for(i <- 0 until e8Depth) io.vdvs3e.e8(i) := vdData(8*(i+1)-1, 8*i)\n for(i <- 0 until e16Depth) io.vdvs3e.e16(i) := vdData(16*(i+1)-1, 16*i)\n for(i <- 0 until e32Depth) io.vdvs3e.e32(i) := vdData(32*(i+1)-1, 32*i)\n for(i <- 0 until e64Depth) io.vdvs3e.e64(i) := vdData(64*(i+1)-1, 64*i)\n for(i <- 0 until e128Depth) io.vdvs3e.e128(i) := vdData(128*(i+1)-1, 128*i)\n for(i <- 0 until e256Depth) io.vdvs3e.e256(i) := vdData(256*(i+1)-1, 256*i)\n for(i <- 0 until e512Depth) io.vdvs3e.e512(i) := vdData(512*(i+1)-1, 512*i)\n for(i <- 0 until e1024Depth) io.vdvs3e.e1024(i) := vdData(1024*(i+1)-1, 1024*i)\n\n//split vs1Data into SEW width vectors\n for(i <- 0 until E8Depth) io.vs1E.e8(i) := io.vs1Data(8*(i+1)-1, 8*i)\n for(i <- 0 until E16Depth) io.vs1E.e16(i) := io.vs1Data(16*(i+1)-1, 16*i)\n for(i <- 0 until E32Depth) io.vs1E.e32(i) := io.vs1Data(32*(i+1)-1, 32*i)\n for(i <- 0 until E64Depth) io.vs1E.e64(i) := io.vs1Data(64*(i+1)-1, 64*i)\n for(i <- 0 until E128Depth) io.vs1E.e128(i) := io.vs1Data(128*(i+1)-1, 128*i)\n for(i <- 0 until E256Depth) io.vs1E.e256(i) := io.vs1Data(256*(i+1)-1, 256*i)\n for(i <- 0 until E512Depth) io.vs1E.e512(i) := io.vs1Data(512*(i+1)-1, 512*i)\n for(i <- 0 until E1024Depth) io.vs1E.e1024(i) := io.vs1Data(1024*(i+1)-1, 1024*i)\n//split vs2Data into SEW width vectors\n for(i <- 0 until E8Depth) io.vs2E.e8(i) := io.vs2Data(8*(i+1)-1, 8*i)\n for(i <- 0 until E16Depth) io.vs2E.e16(i) := io.vs2Data(16*(i+1)-1, 16*i)\n for(i <- 0 until E32Depth) io.vs2E.e32(i) := io.vs2Data(32*(i+1)-1, 32*i)\n for(i <- 0 until E64Depth) io.vs2E.e64(i) := io.vs2Data(64*(i+1)-1, 64*i)\n for(i <- 0 until E128Depth) io.vs2E.e128(i) := io.vs2Data(128*(i+1)-1, 128*i)\n for(i <- 0 until E256Depth) io.vs2E.e256(i) := io.vs2Data(256*(i+1)-1, 256*i)\n for(i <- 0 until E512Depth) io.vs2E.e512(i) := io.vs2Data(512*(i+1)-1, 512*i)\n for(i <- 0 until E1024Depth) io.vs2E.e1024(i) := io.vs2Data(1024*(i+1)-1, 1024*i)\n//split vdvs3Data into SEW width vectors\n for(i <- 0 until E8Depth) io.vdvs3E.e8(i) := io.vdvs3Data(8*(i+1)-1, 8*i)\n for(i <- 0 until E16Depth) io.vdvs3E.e16(i) := io.vdvs3Data(16*(i+1)-1, 16*i)\n for(i <- 0 until E32Depth) io.vdvs3E.e32(i) := io.vdvs3Data(32*(i+1)-1, 32*i)\n for(i <- 0 until E64Depth) io.vdvs3E.e64(i) := io.vdvs3Data(64*(i+1)-1, 64*i)\n for(i <- 0 until E128Depth) io.vdvs3E.e128(i) := io.vdvs3Data(128*(i+1)-1, 128*i)\n for(i <- 0 until E256Depth) io.vdvs3E.e256(i) := io.vdvs3Data(256*(i+1)-1, 256*i)\n for(i <- 0 until E512Depth) io.vdvs3E.e512(i) := io.vdvs3Data(512*(i+1)-1, 512*i)\n for(i <- 0 until E1024Depth) io.vdvs3E.e1024(i) := io.vdvs3Data(1024*(i+1)-1, 1024*i)\n//split vs1Data into MLEN width vectors\n for(i <- 0 until m1Depth) io.vs1m.m1(i) := io.vs1Data(i)\n for(i <- 0 until m2Depth) io.vs1m.m2(i) := io.vs1Data(2*i)\n for(i <- 0 until m4Depth) io.vs1m.m4(i) := io.vs1Data(4*i)\n for(i <- 0 until m8Depth) io.vs1m.m8(i) := io.vs1Data(8*i)\n for(i <- 0 until m16Depth) io.vs1m.m16(i) := io.vs1Data(16*i)\n for(i <- 0 until m32Depth) io.vs1m.m32(i) := io.vs1Data(32*i)\n for(i <- 0 until m64Depth) io.vs1m.m64(i) := io.vs1Data(64*i)\n for(i <- 0 until m128Depth) io.vs1m.m128(i) := io.vs1Data(128*i)\n for(i <- 0 until m256Depth) io.vs1m.m256(i) := io.vs1Data(256*i)\n for(i <- 0 until m512Depth) io.vs1m.m512(i) := io.vs1Data(512*i)\n for(i <- 0 until m1024Depth) io.vs1m.m1024(i) := io.vs1Data(1024*i)\n//split vs2Data into MLEN width vectors\n for(i <- 0 until m1Depth) io.vs2m.m1(i) := io.vs2Data(i)\n for(i <- 0 until m2Depth) io.vs2m.m2(i) := io.vs2Data(2*i)\n for(i <- 0 until m4Depth) io.vs2m.m4(i) := io.vs2Data(4*i)\n for(i <- 0 until m8Depth) io.vs2m.m8(i) := io.vs2Data(8*i)\n for(i <- 0 until m16Depth) io.vs2m.m16(i) := io.vs2Data(16*i)\n for(i <- 0 until m32Depth) io.vs2m.m32(i) := io.vs2Data(32*i)\n for(i <- 0 until m64Depth) io.vs2m.m64(i) := io.vs2Data(64*i)\n for(i <- 0 until m128Depth) io.vs2m.m128(i) := io.vs2Data(128*i)\n for(i <- 0 until m256Depth) io.vs2m.m256(i) := io.vs2Data(256*i)\n for(i <- 0 until m512Depth) io.vs2m.m512(i) := io.vs2Data(512*i)\n for(i <- 0 until m1024Depth) io.vs2m.m1024(i) := io.vs2Data(1024*i)\n//split vdvs3Data into MLEN width vectors\n for(i <- 0 until m1Depth) io.vdm.m1(i) := io.vdvs3Data(i)\n for(i <- 0 until m2Depth) io.vdm.m2(i) := io.vdvs3Data(2*i)\n for(i <- 0 until m4Depth) io.vdm.m4(i) := io.vdvs3Data(4*i)\n for(i <- 0 until m8Depth) io.vdm.m8(i) := io.vdvs3Data(8*i)\n for(i <- 0 until m16Depth) io.vdm.m16(i) := io.vdvs3Data(16*i)\n for(i <- 0 until m32Depth) io.vdm.m32(i) := io.vdvs3Data(32*i)\n for(i <- 0 until m64Depth) io.vdm.m64(i) := io.vdvs3Data(64*i)\n for(i <- 0 until m128Depth) io.vdm.m128(i) := io.vdvs3Data(128*i)\n for(i <- 0 until m256Depth) io.vdm.m256(i) := io.vdvs3Data(256*i)\n for(i <- 0 until m512Depth) io.vdm.m512(i) := io.vdvs3Data(512*i)\n for(i <- 0 until m1024Depth) io.vdm.m1024(i) := io.vdvs3Data(1024*i)\n//split v0Mask into MLEN width vectors\n for(i <- 0 until m1Depth) io.v0m.m1(i) := io.v0Mask(i)\n for(i <- 0 until m2Depth) io.v0m.m2(i) := io.v0Mask(2*i)\n for(i <- 0 until m4Depth) io.v0m.m4(i) := io.v0Mask(4*i)\n for(i <- 0 until m8Depth) io.v0m.m8(i) := io.v0Mask(8*i)\n for(i <- 0 until m16Depth) io.v0m.m16(i) := io.v0Mask(16*i)\n for(i <- 0 until m32Depth) io.v0m.m32(i) := io.v0Mask(32*i)\n for(i <- 0 until m64Depth) io.v0m.m64(i) := io.v0Mask(64*i)\n for(i <- 0 until m128Depth) io.v0m.m128(i) := io.v0Mask(128*i)\n for(i <- 0 until m256Depth) io.v0m.m256(i) := io.v0Mask(256*i)\n for(i <- 0 until m512Depth) io.v0m.m512(i) := io.v0Mask(512*i)\n for(i <- 0 until m1024Depth) io.v0m.m1024(i) := io.v0Mask(1024*i)\n \n//split each element of vs1e vector into SEW/EDIV width vectors\n for(j <- 0 until 2){\n for(i <- 0 until e8Depth) io.vs1d.e8(i).d2(j) := io.vs1e.e8(i)((8/2)*(j+1)-1,(8/2)*j) \n for(i <- 0 until e16Depth) io.vs1d.e16(i).d2(j) := io.vs1e.e16(i)((16/2)*(j+1)-1,(16/2)*j) \n for(i <- 0 until e32Depth) io.vs1d.e32(i).d2(j) := io.vs1e.e32(i)((32/2)*(j+1)-1,(32/2)*j) \n for(i <- 0 until e64Depth) io.vs1d.e64(i).d2(j) := io.vs1e.e64(i)((64/2)*(j+1)-1,(64/2)*j) \n for(i <- 0 until e128Depth) io.vs1d.e128(i).d2(j) := io.vs1e.e128(i)((128/2)*(j+1)-1,(128/2)*j) \n for(i <- 0 until e256Depth) io.vs1d.e256(i).d2(j) := io.vs1e.e256(i)((256/2)*(j+1)-1,(256/2)*j) \n for(i <- 0 until e512Depth) io.vs1d.e512(i).d2(j) := io.vs1e.e512(i)((512/2)*(j+1)-1,(512/2)*j) \n for(i <- 0 until e1024Depth) io.vs1d.e1024(i).d2(j) := io.vs1e.e1024(i)((1024/2)*(j+1)-1,(1024/2)*j) \n }\n for(j <- 0 until 4){\n for(i <- 0 until e8Depth) io.vs1d.e8(i).d4(j) := io.vs1e.e8(i)((8/4)*(j+1)-1,(8/4)*j) \n for(i <- 0 until e16Depth) io.vs1d.e16(i).d4(j) := io.vs1e.e16(i)((16/4)*(j+1)-1,(16/4)*j) \n for(i <- 0 until e32Depth) io.vs1d.e32(i).d4(j) := io.vs1e.e32(i)((32/4)*(j+1)-1,(32/4)*j) \n for(i <- 0 until e64Depth) io.vs1d.e64(i).d4(j) := io.vs1e.e64(i)((64/4)*(j+1)-1,(64/4)*j) \n for(i <- 0 until e128Depth) io.vs1d.e128(i).d4(j) := io.vs1e.e128(i)((128/4)*(j+1)-1,(128/4)*j) \n for(i <- 0 until e256Depth) io.vs1d.e256(i).d4(j) := io.vs1e.e256(i)((256/4)*(j+1)-1,(256/4)*j) \n for(i <- 0 until e512Depth) io.vs1d.e512(i).d4(j) := io.vs1e.e512(i)((512/4)*(j+1)-1,(512/4)*j) \n for(i <- 0 until e1024Depth) io.vs1d.e1024(i).d4(j) := io.vs1e.e1024(i)((1024/4)*(j+1)-1,(1024/4)*j) \n }\n for(j <- 0 until 8){\n for(i <- 0 until e8Depth) io.vs1d.e8(i).d8(j) := io.vs1e.e8(i)((8/8)*(j+1)-1,(8/8)*j) \n for(i <- 0 until e16Depth) io.vs1d.e16(i).d8(j) := io.vs1e.e16(i)((16/8)*(j+1)-1,(16/8)*j) \n for(i <- 0 until e32Depth) io.vs1d.e32(i).d8(j) := io.vs1e.e32(i)((32/8)*(j+1)-1,(32/8)*j) \n for(i <- 0 until e64Depth) io.vs1d.e64(i).d8(j) := io.vs1e.e64(i)((64/8)*(j+1)-1,(64/8)*j) \n for(i <- 0 until e128Depth) io.vs1d.e128(i).d8(j) := io.vs1e.e128(i)((128/8)*(j+1)-1,(128/8)*j) \n for(i <- 0 until e256Depth) io.vs1d.e256(i).d8(j) := io.vs1e.e256(i)((256/8)*(j+1)-1,(256/8)*j) \n for(i <- 0 until e512Depth) io.vs1d.e512(i).d8(j) := io.vs1e.e512(i)((512/8)*(j+1)-1,(512/8)*j) \n for(i <- 0 until e1024Depth) io.vs1d.e1024(i).d8(j) := io.vs1e.e1024(i)((1024/8)*(j+1)-1,(1024/8)*j) \n }\n//split each element of vs2e vector into SEW/EDIV width vectors\n for(j <- 0 until 2){\n for(i <- 0 until e8Depth) io.vs2d.e8(i).d2(j) := io.vs2e.e8(i)((8/2)*(j+1)-1,(8/2)*j) \n for(i <- 0 until e16Depth) io.vs2d.e16(i).d2(j) := io.vs2e.e16(i)((16/2)*(j+1)-1,(16/2)*j) \n for(i <- 0 until e32Depth) io.vs2d.e32(i).d2(j) := io.vs2e.e32(i)((32/2)*(j+1)-1,(32/2)*j) \n for(i <- 0 until e64Depth) io.vs2d.e64(i).d2(j) := io.vs2e.e64(i)((64/2)*(j+1)-1,(64/2)*j) \n for(i <- 0 until e128Depth) io.vs2d.e128(i).d2(j) := io.vs2e.e128(i)((128/2)*(j+1)-1,(128/2)*j) \n for(i <- 0 until e256Depth) io.vs2d.e256(i).d2(j) := io.vs2e.e256(i)((256/2)*(j+1)-1,(256/2)*j) \n for(i <- 0 until e512Depth) io.vs2d.e512(i).d2(j) := io.vs2e.e512(i)((512/2)*(j+1)-1,(512/2)*j) \n for(i <- 0 until e1024Depth) io.vs2d.e1024(i).d2(j) := io.vs2e.e1024(i)((1024/2)*(j+1)-1,(1024/2)*j) \n }\n for(j <- 0 until 4){\n for(i <- 0 until e8Depth) io.vs2d.e8(i).d4(j) := io.vs2e.e8(i)((8/4)*(j+1)-1,(8/4)*j) \n for(i <- 0 until e16Depth) io.vs2d.e16(i).d4(j) := io.vs2e.e16(i)((16/4)*(j+1)-1,(16/4)*j) \n", "right_context": " for(i <- 0 until e16Depth) io.vs2d.e16(i).d8(j) := io.vs2e.e16(i)((16/8)*(j+1)-1,(16/8)*j) \n for(i <- 0 until e32Depth) io.vs2d.e32(i).d8(j) := io.vs2e.e32(i)((32/8)*(j+1)-1,(32/8)*j) \n for(i <- 0 until e64Depth) io.vs2d.e64(i).d8(j) := io.vs2e.e64(i)((64/8)*(j+1)-1,(64/8)*j) \n for(i <- 0 until e128Depth) io.vs2d.e128(i).d8(j) := io.vs2e.e128(i)((128/8)*(j+1)-1,(128/8)*j) \n for(i <- 0 until e256Depth) io.vs2d.e256(i).d8(j) := io.vs2e.e256(i)((256/8)*(j+1)-1,(256/8)*j) \n for(i <- 0 until e512Depth) io.vs2d.e512(i).d8(j) := io.vs2e.e512(i)((512/8)*(j+1)-1,(512/8)*j) \n for(i <- 0 until e1024Depth) io.vs2d.e1024(i).d8(j) := io.vs2e.e1024(i)((1024/8)*(j+1)-1,(1024/8)*j) \n }\n\n\n}\n", "groundtruth": " for(i <- 0 until e32Depth) io.vs2d.e32(i).d4(j) := io.vs2e.e32(i)((32/4)*(j+1)-1,(32/4)*j) \n for(i <- 0 until e64Depth) io.vs2d.e64(i).d4(j) := io.vs2e.e64(i)((64/4)*(j+1)-1,(64/4)*j) \n for(i <- 0 until e128Depth) io.vs2d.e128(i).d4(j) := io.vs2e.e128(i)((128/4)*(j+1)-1,(128/4)*j) \n for(i <- 0 until e256Depth) io.vs2d.e256(i).d4(j) := io.vs2e.e256(i)((256/4)*(j+1)-1,(256/4)*j) \n for(i <- 0 until e512Depth) io.vs2d.e512(i).d4(j) := io.vs2e.e512(i)((512/4)*(j+1)-1,(512/4)*j) \n", "crossfile_context": ""}
{"task_id": "rocket_chip_vpu", "path": "rocket_chip_vpu/vpu/src/test/scala/VPU/VPUMain.scala", "left_context": "package vpu\n\nimport chisel3._\n\ntrait CustomConfig {\n val SeqmulDiv = Some(Array(\n VMulDivParams(mulUnroll = 2, divUnroll = 2, mulEarlyOut = true, divEarlyOut = true),\n VMulDivParams(mulUnroll = 4, divUnroll = 4, mulEarlyOut = true, divEarlyOut = true),\n VMulDivParams(mulUnroll = 8, divUnroll = 8, mulEarlyOut = true, divEarlyOut = true),\n VMulDivParams(mulUnroll = 16, divUnroll = 16, mulEarlyOut = true, divEarlyOut = true),\n VMulDivParams(mulUnroll = 32, divUnroll = 32, mulEarlyOut = true, divEarlyOut = true),\n VMulDivParams(mulUnroll = 64, divUnroll = 64, mulEarlyOut = true, divEarlyOut = true),\n VMulDivParams(mulUnroll = 128, divUnroll = 128, mulEarlyOut = true, divEarlyOut = true),\n VMulDivParams(mulUnroll = 256, divUnroll = 256, mulEarlyOut = true, divEarlyOut = true)\n ))\n val customConfig = VPUParams(VLEN = 64, \n ELEN = 64, \n XLEN = 64, \n FLEN = 64, \n ZFINX = false, \n FSEW16 = false, \n FSEWMAX = 64, \n LMULMAX = 1, \n MERGE = true, \n MULDIV = true, \n MULADD = true, \n QMULADD = true, \n mulDiv = SeqmulDiv, \n RED = true, \n MV = true, \n SATADD = true, \n AVERADD = true, \n SATMUL = true, \n SCALESR = true, \n NCLIP = true, \n SLIDE = true, \n GATHER = true, \n COMPRESS = true, \n COPY = true, \n FMA = true, \n FCVT = true, \n FCMP = true, \n FSGNJ = true, \n FCLASS = true, \n FMERGE = true, \n FMV = true, \n FDIVSQRT = true, \n FRED = true, \n SEGLS = true, \n AMO = true, \n EDIV = false, \n DOT = true, \n FDOT = true)\n val tagBits = 8\n val addrBits = 40\n}\n\n", "right_context": " iotesters.Driver.execute(args, () => new VPU_64V64E1L(customConfig, tagBits, addrBits)) {\n c => new VPUTest(c)\n }\n}\n\nobject VPURepl extends App with CustomConfig {\n iotesters.Driver.executeFirrtlRepl(args, () => new VPU_64V64E1L(customConfig, tagBits, addrBits))\n}\n", "groundtruth": "object VPUVerilog extends App with CustomConfig {\n chisel3.Driver.execute(args, () => new VPU_64V64E1L(customConfig, tagBits, addrBits))\n}\n", "crossfile_context": ""}
{"task_id": "rocket_chip_vpu", "path": "rocket_chip_vpu/vpu/src/test/scala/VPU/VPUTest.scala", "left_context": "/*\ninst and data input order: \n\tfirst a CSR inst for setting VPU CSR environment,\n\tthen two load insts with incresing data sequence for inputting data, \n\tthen sixteen arithmetic or logic insts for data changing,\n final a store inst for data output;\nprint insts' name, insts' fields and data for better understanding waveform.\n*/\n\npackage vpu\n\nimport chisel3.iotesters._\nimport chisel3.util._\nimport java.io.File\nimport java.io.PrintWriter\n\nclass VPUTest(c: VPU_64V64E1L) extends PeekPokeTester(c) {\n val writer = new PrintWriter(new File(\"/home/liangzh/Desktop/ChiselProjects/Vector/src/test/scala/VPU/VPUResult\"))\n\n/////////////////////////////////environment setting////////////////////////////\n //set CSR and initial value for vector regfile\n val vsew = rnd.nextInt(log2Ceil(c.VLEN / 8))\n val vlmul = rnd.nextInt(log2Ceil(c.LMULMAX) + 1)\n val vtype = BigInt(vsew << 2 | vlmul)\n val SEW = 8 << vsew\n val LMUL = 1 << vlmul\n val VLMAX = LMUL * c.VLEN / SEW\n val MLEN = SEW / LMUL\n val AVL = rnd.nextInt(2*VLMAX+1)\n val vl = if(rs1 == \"00000\") VLMAX \n else if(AVL <= VLMAX) AVL\n else if(AVL < 2*VLMAX) AVL/2 + 1\n else VLMAX\n val atomVal = rnd.nextInt(1 << 8)\n val atomValStr = \"0\"*(2-atomVal.toHexString.length) + atomVal.toHexString\n val elemValStr = (\"0\"*(2-atomVal.toHexString.length) + atomVal.toHexString)*(1 << vsew)\n val elemVal = BigInt(elemValStr, 16)\n\n //print environment setting\n writer.println(\"VLEN -- the number of bits in a vector register = \" + c.VLEN)\n writer.println(\"XLEN -- the number of bits in a Rocket GPR = \" + c.XLEN)\n writer.println()\n writer.println(\"VLMAX -- maximum number of elements in a calculation = \" + VLMAX)\n writer.println(\"AVL -- application vector length = \" + AVL)\n writer.println(\"vl -- actual vector length = \" + vl)\n writer.println()\n writer.println(\"vsew -- dynamic standard width(SEW) encoding = \" + vsew)\n writer.println(\"SEW -- dynamic standard width = \" + SEW)\n writer.println(\"vlmul -- vector register grouping encoding = \" + vlmul)\n writer.println(\"LMUL -- vector register grouping = \" + LMUL)\n writer.println()\n writer.println(\"MLEN -- the size of each mask element in bits = \" + MLEN)\n writer.println()\n writer.println(\"atomic value(Hex) -- to construct load input values = \" + atomValStr)\n writer.println(\"element value(Hex) -- the first load input value = \" + elemValStr)\n writer.println()\n writer.println()\n/////////////////////////////////environment setting////////////////////////////\n\n def VTYPEI: String = \"0\"*(11-vtype.toString(2).length)+vtype.toString(2)\n def vm: String = BigInt(1, scala.util.Random).toString(2)\n def VlmulRF: String = { val rf = (BigInt(5, scala.util.Random) & (32 - LMUL)).toString(2); \"0\"*(5-rf.length)+rf }\n def SingleRF: String = { val rf = BigInt(5, scala.util.Random).toString(2); \"0\"*(5-rf.length)+rf }\n def VmlenRF(start: BigInt): String = { val rf = (BigInt(vlmul, scala.util.Random) + start).toString(2); \"0\"*(5-rf.length)+rf }\n\n val vtypei = VTYPEI\n val ldDstField = Array(VlmulRF, VlmulRF)\n val ldForVs1 = ldDstField(0)\n val ldForVs2 = ldDstField(1)\n val (rs1, rs2) = (SingleRF, SingleRF)\n val (vs1m, vs2m) = (VmlenRF(BigInt(ldDstField(0), 2)), VmlenRF(BigInt(ldDstField(1), 2)))\n val (vs1s, vs2s) = (VmlenRF(BigInt(ldDstField(0), 2)), VmlenRF(BigInt(ldDstField(1), 2)))\n val (rd, vde, vdm, vds) = (SingleRF, VlmulRF, SingleRF, SingleRF)\n val (vs2e, vs3e) = (VlmulRF, VlmulRF)\n val imm = SingleRF\n\n///////////////////////////instructions name-code pairs/////////////////////////\n //AL Insts\n def VADD_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"000000\"+vm +vs2e +vs1e +\"000\"+vde+\"1010111\", \"VADD_VV \")\n def VADD_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"000000\"+vm +vs2e +rs1 +\"100\"+vde+\"1010111\", \"VADD_VX \")\n def VADD_VI (vde: String = vde, vs2e: String = ldForVs2, imm: String = imm, vm: String = vm) = (\"000000\"+vm +vs2e +imm +\"011\"+vde+\"1010111\", \"VADD_VI \")\n def VSUB_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"000010\"+vm +vs2e +vs1e +\"000\"+vde+\"1010111\", \"VSUB_VV \")\n def VSUB_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"000010\"+vm +vs2e +rs1 +\"100\"+vde+\"1010111\", \"VSUB_VX \")\n def VRSUB_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"000011\"+vm +vs2e +rs1 +\"100\"+vde+\"1010111\", \"VRSUB_VX \")\n def VRSUB_VI (vde: String = vde, vs2e: String = ldForVs2, imm: String = imm, vm: String = vm) = (\"000011\"+vm +vs2e +imm +\"011\"+vde+\"1010111\", \"VRSUB_VI \")\n val addInsts = Array(VADD_VV(), VADD_VX(), VADD_VI(), \n VSUB_VV(), VSUB_VX(), \n VRSUB_VX(), VRSUB_VI())\n\n def VWADDU_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"110000\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VWADDU_VV \")\n def VWADDU_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"110000\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VWADDU_VX \")\n def VWADD_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"110001\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VWADD_VV \")\n def VWADD_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"110001\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VWADD_VX \")\n def VWSUBU_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"110010\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VWSUBU_VV \")\n def VWSUBU_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"110010\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VWSUBU_VX \")\n def VWSUB_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"110011\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VWSUB_VV \")\n def VWSUB_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"110011\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VWSUB_VX \")\n def VWADDU_WV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"110100\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VWADDU_WV \")\n def VWADDU_WX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"110100\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VWADDU_WX \")\n def VWADD_WV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"110101\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VWADD_WV \")\n def VWADD_WX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"110101\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VWADD_WX \")\n def VWSUBU_WV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"110110\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VWSUBU_WV \")\n def VWSUBU_WX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"110110\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VWSUBU_WX \")\n def VWSUB_WV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"110111\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VWSUB_WV \")\n def VWSUB_WX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"110111\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VWSUB_WX \")\n val waddInsts = Array(VWADDU_VV(), VWADDU_VX(), VWADD_VV(), VWADD_VX(), \n VWSUBU_VV(), VWSUBU_VX(), VWSUB_VV(), VWSUB_VX(), \n VWADDU_WV(), VWADDU_WX(), VWADD_WV(), VWADD_WX(), \n VWSUBU_WV(), VWSUBU_WX(), VWSUB_WV(), VWSUB_WX())\n\n def VADC_VVM (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1) = (\"010000\"+\"1\"+vs2e +vs1e +\"000\"+vde+\"1010111\", \"VADC_VVM \")\n def VMADC_VVM (vdm: String = vdm, vs2e: String = ldForVs2, vs1e: String = ldForVs1) = (\"010001\"+\"1\"+vs2e +vs1e +\"000\"+vdm+\"1010111\", \"VMADC_VVM \")\n def VADC_VXM (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1) = (\"010000\"+\"1\"+vs2e +rs1 +\"100\"+vde+\"1010111\", \"VADC_VXM \")\n def VMADC_VXM (vdm: String = vdm, vs2e: String = ldForVs2, rs1: String = rs1) = (\"010001\"+\"1\"+vs2e +rs1 +\"100\"+vdm+\"1010111\", \"VMADC_VXM \")\n def VADC_VIM (vde: String = vde, vs2e: String = ldForVs2, imm: String = imm) = (\"010000\"+\"1\"+vs2e +imm +\"011\"+vde+\"1010111\", \"VADC_VIM \")\n def VMADC_VIM (vdm: String = vdm, vs2e: String = ldForVs2, imm: String = imm) = (\"010001\"+\"1\"+vs2e +imm +\"011\"+vdm+\"1010111\", \"VMADC_VIM \")\n def VSBC_VVM (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1) = (\"010010\"+\"1\"+vs2e +vs1e +\"000\"+vde+\"1010111\", \"VSBC_VVM \")\n def VMSBC_VVM (vdm: String = vdm, vs2e: String = ldForVs2, vs1e: String = ldForVs1) = (\"010011\"+\"1\"+vs2e +vs1e +\"000\"+vdm+\"1010111\", \"VMSBC_VVM \")\n def VSBC_VXM (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1) = (\"010010\"+\"1\"+vs2e +rs1 +\"100\"+vde+\"1010111\", \"VSBC_VXM \")\n def VMSBC_VXM (vdm: String = vdm, vs2e: String = ldForVs2, rs1: String = rs1) = (\"010011\"+\"1\"+vs2e +rs1 +\"100\"+vdm+\"1010111\", \"VMSBC_VXM \")\n val adcInsts = Array(VADC_VVM(), VMADC_VVM(), VADC_VXM(), VMADC_VXM(), VADC_VIM(), VMADC_VIM(), \n VSBC_VVM(), VMSBC_VVM(), VSBC_VXM(), VMSBC_VXM())\n\n def VAND_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"001001\"+vm +vs2e +vs1e +\"000\"+vde+\"1010111\", \"VAND_VV \")\n def VAND_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"001001\"+vm +vs2e +rs1 +\"100\"+vde+\"1010111\", \"VAND_VX \")\n def VAND_VI (vde: String = vde, vs2e: String = ldForVs2, imm: String = imm, vm: String = vm) = (\"001001\"+vm +vs2e +imm +\"011\"+vde+\"1010111\", \"VAND_VI \")\n def VOR_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"001010\"+vm +vs2e +vs1e +\"000\"+vde+\"1010111\", \"VOR_VV \")\n def VOR_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"001010\"+vm +vs2e +rs1 +\"100\"+vde+\"1010111\", \"VOR_VX \")\n def VOR_VI (vde: String = vde, vs2e: String = ldForVs2, imm: String = imm, vm: String = vm) = (\"001010\"+vm +vs2e +imm +\"011\"+vde+\"1010111\", \"VOR_VI \")\n def VXOR_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"001011\"+vm +vs2e +vs1e +\"000\"+vde+\"1010111\", \"VXOR_VV \")\n def VXOR_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"001011\"+vm +vs2e +rs1 +\"100\"+vde+\"1010111\", \"VXOR_VX \")\n def VXOR_VI (vde: String = vde, vs2e: String = ldForVs2, imm: String = imm, vm: String = vm) = (\"001011\"+vm +vs2e +imm +\"011\"+vde+\"1010111\", \"VXOR_VI \")\n val bitInsts = Array(VAND_VV(), VAND_VX(), VAND_VI(), \n VOR_VV(), VOR_VX(), VOR_VI(),\n VXOR_VV(), VXOR_VX(), VXOR_VI())\n\n def VSLL_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"100101\"+vm +vs2e +vs1e +\"000\"+vde+\"1010111\", \"VSLL_VV \")\n def VSLL_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"100101\"+vm +vs2e +rs1 +\"100\"+vde+\"1010111\", \"VSLL_VX \")\n def VSLL_VI (vde: String = vde, vs2e: String = ldForVs2, imm: String = imm, vm: String = vm) = (\"100101\"+vm +vs2e +imm +\"011\"+vde+\"1010111\", \"VSLL_VI \")\n def VSRL_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"101000\"+vm +vs2e +vs1e +\"000\"+vde+\"1010111\", \"VSRL_VV \")\n def VSRL_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"101000\"+vm +vs2e +rs1 +\"100\"+vde+\"1010111\", \"VSRL_VX \")\n def VSRL_VI (vde: String = vde, vs2e: String = ldForVs2, imm: String = imm, vm: String = vm) = (\"101000\"+vm +vs2e +imm +\"011\"+vde+\"1010111\", \"VSRL_VI \")\n def VSRA_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"101001\"+vm +vs2e +vs1e +\"000\"+vde+\"1010111\", \"VSRA_VV \")\n def VSRA_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"101001\"+vm +vs2e +rs1 +\"100\"+vde+\"1010111\", \"VSRA_VX \")\n def VSRA_VI (vde: String = vde, vs2e: String = ldForVs2, imm: String = imm, vm: String = vm) = (\"101001\"+vm +vs2e +imm +\"011\"+vde+\"1010111\", \"VSRA_VI \")\n val shiftInsts = Array(VSLL_VV(), VSLL_VX(), VSLL_VI(), \n VSRL_VV(), VSRL_VX(), VSRL_VI(), \n VSRA_VV(), VSRA_VX(), VSRA_VI()) \n\n def VNSRL_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"101100\"+vm +vs2e +vs1e +\"000\"+vde+\"1010111\", \"VNSRL_VV \")\n def VNSRL_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"101100\"+vm +vs2e +rs1 +\"100\"+vde+\"1010111\", \"VNSRL_VX \")\n def VNSRL_VI (vde: String = vde, vs2e: String = ldForVs2, imm: String = imm, vm: String = vm) = (\"101100\"+vm +vs2e +imm +\"011\"+vde+\"1010111\", \"VNSRL_VI \")\n def VNSRA_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"101101\"+vm +vs2e +vs1e +\"000\"+vde+\"1010111\", \"VNSRA_VV \")\n def VNSRA_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"101101\"+vm +vs2e +rs1 +\"100\"+vde+\"1010111\", \"VNSRA_VX \")\n def VNSRA_VI (vde: String = vde, vs2e: String = ldForVs2, imm: String = imm, vm: String = vm) = (\"101101\"+vm +vs2e +imm +\"011\"+vde+\"1010111\", \"VNSRA_VI \")\n val nshiftInsts = Array(VNSRL_VV(), VNSRL_VX(), VNSRL_VI(), \n VNSRA_VV(), VNSRA_VX(), VNSRA_VI())\n\n def VMSEQ_VV (vdm: String = vdm, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"011000\"+vm +vs2e +vs1e +\"000\"+vdm+\"1010111\", \"VMSEQ_VV \")\n def VMSEQ_VX (vdm: String = vdm, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"011000\"+vm +vs2e +rs1 +\"100\"+vdm+\"1010111\", \"VMSEQ_VX \")\n def VMSEQ_VI (vdm: String = vdm, vs2e: String = ldForVs2, imm: String = imm, vm: String = vm) = (\"011000\"+vm +vs2e +imm +\"011\"+vdm+\"1010111\", \"VMSEQ_VI \")\n def VMSNE_VV (vdm: String = vdm, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"011001\"+vm +vs2e +vs1e +\"000\"+vdm+\"1010111\", \"VMSNE_VV \")\n def VMSNE_VX (vdm: String = vdm, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"011001\"+vm +vs2e +rs1 +\"100\"+vdm+\"1010111\", \"VMSNE_VX \")\n def VMSNE_VI (vdm: String = vdm, vs2e: String = ldForVs2, imm: String = imm, vm: String = vm) = (\"011001\"+vm +vs2e +imm +\"011\"+vdm+\"1010111\", \"VMSNE_VI \")\n def VMSLTU_VV (vdm: String = vdm, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"011010\"+vm +vs2e +vs1e +\"000\"+vdm+\"1010111\", \"VMSLTU_VV \")\n def VMSLTU_VX (vdm: String = vdm, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"011010\"+vm +vs2e +rs1 +\"100\"+vdm+\"1010111\", \"VMSLTU_VX \")\n def VMSLT_VV (vdm: String = vdm, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"011011\"+vm +vs2e +vs1e +\"100\"+vdm+\"1010111\", \"VMSLT_VV \")\n def VMSLT_VX (vdm: String = vdm, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"011011\"+vm +vs2e +rs1 +\"100\"+vdm+\"1010111\", \"VMSLT_VX \")\n def VMSLEU_VV (vdm: String = vdm, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"011100\"+vm +vs2e +vs1e +\"000\"+vdm+\"1010111\", \"VMSLEU_VV \")\n def VMSLEU_VX (vdm: String = vdm, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"011100\"+vm +vs2e +rs1 +\"100\"+vdm+\"1010111\", \"VMSLEU_VX \")\n def VMSLEU_VI (vdm: String = vdm, vs2e: String = ldForVs2, imm: String = imm, vm: String = vm) = (\"011100\"+vm +vs2e +imm +\"011\"+vdm+\"1010111\", \"VMSLEU_VI \")\n def VMSLE_VV (vdm: String = vdm, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"011101\"+vm +vs2e +vs1e +\"000\"+vdm+\"1010111\", \"VMSLE_VV \")\n def VMSLE_VX (vdm: String = vdm, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"011101\"+vm +vs2e +rs1 +\"100\"+vdm+\"1010111\", \"VMSLE_VX \")\n def VMSLE_VI (vdm: String = vdm, vs2e: String = ldForVs2, imm: String = imm, vm: String = vm) = (\"011101\"+vm +vs2e +imm +\"011\"+vdm+\"1010111\", \"VMSLE_VI \")\n def VMSGTU_VX (vdm: String = vdm, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"011110\"+vm +vs2e +rs1 +\"100\"+vdm+\"1010111\", \"VMSGTU_VX \")\n def VMSGTU_VI (vdm: String = vdm, vs2e: String = ldForVs2, imm: String = imm, vm: String = vm) = (\"011110\"+vm +vs2e +imm +\"011\"+vdm+\"1010111\", \"VMSGTU_VI \")\n def VMSGT_VX (vdm: String = vdm, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"011111\"+vm +vs2e +rs1 +\"100\"+vdm+\"1010111\", \"VMSGT_VX \")\n def VMSGT_VI (vdm: String = vdm, vs2e: String = ldForVs2, imm: String = imm, vm: String = vm) = (\"011111\"+vm +vs2e +imm +\"011\"+vdm+\"1010111\", \"VMSGT_VI \")\n val cmpInsts = Array(VMSEQ_VV(), VMSEQ_VX(), VMSEQ_VI(), \n VMSNE_VV(), VMSNE_VX(), VMSNE_VI(),\n VMSLTU_VV(), VMSLTU_VX(), \n VMSLT_VV(), VMSLT_VX(), \n VMSLEU_VV(), VMSLEU_VX(), VMSLEU_VI(), \n VMSLE_VV(), VMSLE_VX(), VMSLE_VI(), \n VMSGTU_VX(), VMSGTU_VI(), \n VMSGT_VX(), VMSGT_VI())\n\n def VMINU_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"000100\"+vm +vs2e +vs1e +\"000\"+vde+\"1010111\", \"VMINU_VV \")\n def VMINU_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"000100\"+vm +vs2e +rs1 +\"100\"+vde+\"1010111\", \"VMINU_VX \")\n def VMIN_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"000101\"+vm +vs2e +vs1e +\"000\"+vde+\"1010111\", \"VMIN_VV \")\n def VMIN_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"000101\"+vm +vs2e +rs1 +\"100\"+vde+\"1010111\", \"VMIN_VX \")\n def VMAXU_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"000110\"+vm +vs2e +vs1e +\"000\"+vde+\"1010111\", \"VMAXU_VV \")\n def VMAXU_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"000110\"+vm +vs2e +rs1 +\"100\"+vde+\"1010111\", \"VMAXU_VX \")\n def VMAX_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"000111\"+vm +vs2e +vs1e +\"000\"+vde+\"1010111\", \"VMAX_VV \")\n def VMAX_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"000111\"+vm +vs2e +rs1 +\"100\"+vde+\"1010111\", \"VMAX_VX \")\n val minInsts = Array(VMINU_VV(), VMINU_VX(), \n VMIN_VV(), VMIN_VX(), \n VMAXU_VV(), VMAXU_VX(), \n VMAX_VV(), VMAX_VX())\n\n def VMERGE_VVM (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"010111\"+vm +vs2e +vs1e +\"000\"+vde+\"1010111\", \"VMERGE_VVM \")\n def VMERGE_VXM (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"010111\"+vm +vs2e +rs1 +\"100\"+vde+\"1010111\", \"VMERGE_VXM \")\n def VMERGE_VIM (vde: String = vde, vs2e: String = ldForVs2, imm: String = imm, vm: String = vm) = (\"010111\"+vm +vs2e +imm +\"011\"+vde+\"1010111\", \"VMERGE_VIM \")\n val mergeInsts = Array(VMERGE_VVM(), VMERGE_VXM(), VMERGE_VIM())\n\n def VPOPC_M (rd: String = rd, vs2m: String = vs2m, vm: String = vm) = (\"010000\"+vm +vs2m +\"10000\"+\"010\"+rd +\"1010111\", \"VPOPC_M \")\n val popcInst = Array(VPOPC_M())\n\n def VFIRST_M (rd: String = rd, vs2m: String = vs2m, vm: String = vm) = (\"010000\"+vm +vs2m +\"10001\"+\"010\"+rd +\"1010111\", \"VFIRST_M \")\n val firstInst = Array(VFIRST_M())\n\n def VMSBF_M (vdm: String = vdm, vs2m: String = vs2m, vm: String = vm) = (\"010100\"+vm +vs2m +\"00001\"+\"010\"+vdm+\"1010111\", \"VMSBF_M \")\n def VMSOF_M (vdm: String = vdm, vs2m: String = vs2m, vm: String = vm) = (\"010100\"+vm +vs2m +\"00010\"+\"010\"+vdm+\"1010111\", \"VMSOF_M \")\n def VMSIF_M (vdm: String = vdm, vs2m: String = vs2m, vm: String = vm) = (\"010100\"+vm +vs2m +\"00011\"+\"010\"+vdm+\"1010111\", \"VMSIF_M \")\n val midxInsts = Array(VMSBF_M(), VMSOF_M(), VMSIF_M())\n\n def VIOTA_M (vde: String = vde, vs2m: String = vs2m, vm: String = vm) = (\"010100\"+vm +vs2m +\"10000\"+\"010\"+vde+\"1010111\", \"VIOTA_M \")\n val iotaInst = Array(VIOTA_M())\n\n def VID_V (vde: String = vde, vm: String = vm) = (\"010100\"+vm +\"00000\"+\"10001\"+\"010\"+vde+\"1010111\", \"VID_V \")\n val idInst = Array(VID_V())\n\n def VMANDNOT_MM (vdm: String = vdm, vs2m: String = vs2m, vs1m: String = vs1m) = (\"011000\"+\"1\"+vs2m +vs1m +\"010\"+vdm+\"1010111\", \"VMANDNOT_MM \")\n def VMAND_MM (vdm: String = vdm, vs2m: String = vs2m, vs1m: String = vs1m) = (\"011001\"+\"1\"+vs2m +vs1m +\"010\"+vdm+\"1010111\", \"VMAND_MM \")\n def VMOR_MM (vdm: String = vdm, vs2m: String = vs2m, vs1m: String = vs1m) = (\"011010\"+\"1\"+vs2m +vs1m +\"010\"+vdm+\"1010111\", \"VMOR_MM \")\n def VMXOR_MM (vdm: String = vdm, vs2m: String = vs2m, vs1m: String = vs1m) = (\"011011\"+\"1\"+vs2m +vs1m +\"010\"+vdm+\"1010111\", \"VMXOR_MM \")\n def VMORNOT_MM (vdm: String = vdm, vs2m: String = vs2m, vs1m: String = vs1m) = (\"011100\"+\"1\"+vs2m +vs1m +\"010\"+vdm+\"1010111\", \"VMORNOT_MM \")\n def VMNAND_MM (vdm: String = vdm, vs2m: String = vs2m, vs1m: String = vs1m) = (\"011101\"+\"1\"+vs2m +vs1m +\"010\"+vdm+\"1010111\", \"VMNAND_MM \")\n def VMNOR_MM (vdm: String = vdm, vs2m: String = vs2m, vs1m: String = vs1m) = (\"011110\"+\"1\"+vs2m +vs1m +\"010\"+vdm+\"1010111\", \"VMNOR_MM \")\n def VMXNOR_MM (vdm: String = vdm, vs2m: String = vs2m, vs1m: String = vs1m) = (\"011111\"+\"1\"+vs2m +vs1m +\"010\"+vdm+\"1010111\", \"VMXNOR_MM \")\n val mbitInsts = Array(VMANDNOT_MM(), VMAND_MM(), VMOR_MM(), VMXOR_MM(), VMORNOT_MM(), VMNAND_MM(), VMNOR_MM(), VMXNOR_MM())\n\n def VMUL_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"100101\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VMUL_VV \")\n def VMUL_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"100101\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VMUL_VX \")\n def VMULH_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"100111\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VMULH_VV \")\n def VMULH_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"100111\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VMULH_VX \")\n def VMULHU_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"100100\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VMULHU_VV \")\n def VMULHU_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"100100\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VMULHU_VX \")\n def VMULHSU_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"100110\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VMULHSU_VV \")\n def VMULHSU_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"100110\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VMULHSU_VX \")\n val mulInsts = Array(VMUL_VV(), VMUL_VX(), \n VMULH_VV(), VMULH_VX(), \n VMULHU_VV(), VMULHU_VX(), \n VMULHSU_VV(), VMULHSU_VX())\n\n def VWMUL_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"111011\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VWMUL_VV \")\n def VWMUL_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"111011\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VWMUL_VX \")\n def VWMULU_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"111000\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VWMULU_VV \")\n def VWMULU_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"111000\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VWMULU_VX \")\n def VWMULSU_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"111010\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VWMULSU_VV \")\n def VWMULSU_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"111010\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VWMULSU_VX \")\n val wmulInsts = Array(VWMUL_VV(), VWMUL_VX(), \n VWMULU_VV(), VWMULU_VX(), \n VWMULSU_VV(), VWMULSU_VX())\n\n def VDIV_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"100001\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VDIV_VV \")\n def VDIV_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"100001\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VDIV_VX \")\n def VDIVU_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"100000\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VDIVU_VV \")\n def VDIVU_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"100000\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VDIVU_VX \")\n def VREM_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"100011\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VREM_VV \")\n def VREM_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"100011\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VREM_VX \")\n def VREMU_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"100010\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VREMU_VV \")\n def VREMU_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"100010\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VREMU_VX \")\n val divInsts = Array(VDIV_VV(), VDIV_VX(), VDIVU_VV(), VDIVU_VX(), \n VREM_VV(), VREM_VX(), VREMU_VV(), VREMU_VX())\n\n def VMADD_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"101001\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VMADD_VV \")\n def VMADD_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"101001\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VMADD_VX \")\n def VNMSUB_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"101011\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VNMSUB_VV \")\n def VNMSUB_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"101011\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VNMSUB_VX \")\n def VMACC_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"101101\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VMACC_VV \")\n def VMACC_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"101101\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VMACC_VX \")\n def VNMSAC_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"101111\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VNMSAC_VV \")\n def VNMSAC_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"101111\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VNMSAC_VX \")\n val maddInsts = Array(VMADD_VV(), VMADD_VX(),\n VNMSUB_VV(), VNMSUB_VX(), \n VMACC_VV(), VMACC_VX(), \n VNMSAC_VV(), VNMSAC_VX())\n\n def VWMACCU_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"111100\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VWMACCU_VV \")\n def VWMACCU_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"111100\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VWMACCU_VX \")\n def VWMACC_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"111101\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VWMACC_VV \")\n def VWMACC_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"111101\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VWMACC_VX \")\n def VWMACCSU_VV (vde: String = vde, vs2e: String = ldForVs2, vs1e: String = ldForVs1, vm: String = vm) = (\"111110\"+vm +vs2e +vs1e +\"010\"+vde+\"1010111\", \"VWMACCSU_VV \")\n def VWMACCSU_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"111110\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VWMACCSU_VX \")\n def VWMACCUS_VX (vde: String = vde, vs2e: String = ldForVs2, rs1: String = rs1, vm: String = vm) = (\"111111\"+vm +vs2e +rs1 +\"110\"+vde+\"1010111\", \"VWMACCUS_VX \")\n val wmaddInsts = Array(VWMACCU_VV(), VWMACCU_VX(), \n VWMACC_VV(), VWMACC_VX(), \n VWMACCSU_VV(), VWMACCSU_VX(), \n VWMACCUS_VX())\n\n def VWREDSUMU_VS(vds: String = vds, vs2e: String = ldForVs2, vs1s: String = vs1s, vm: String = vm) = (\"110000\"+vm +vs2e +vs1s +\"000\"+vds+\"1010111\", \"VWREDSUMU_VS\")\n def VWREDSUM_VS (vds: String = vds, vs2e: String = ldForVs2, vs1s: String = vs1s, vm: String = vm) = (\"110001\"+vm +vs2e +vs1s +\"000\"+vds+\"1010111\", \"VWREDSUM_VS \")\n def VREDSUM_VS (vds: String = vds, vs2e: String = ldForVs2, vs1s: String = vs1s, vm: String = vm) = (\"000000\"+vm +vs2e +vs1s +\"010\"+vds+\"1010111\", \"VREDSUM_VS \")\n def VREDAND_VS (vds: String = vds, vs2e: String = ldForVs2, vs1s: String = vs1s, vm: String = vm) = (\"000001\"+vm +vs2e +vs1s +\"010\"+vds+\"1010111\", \"VREDAND_VS \")\n def VREDOR_VS (vds: String = vds, vs2e: String = ldForVs2, vs1s: String = vs1s, vm: String = vm) = (\"000010\"+vm +vs2e +vs1s +\"010\"+vds+\"1010111\", \"VREDOR_VS \")\n def VREDXOR_VS (vds: String = vds, vs2e: String = ldForVs2, vs1s: String = vs1s, vm: String = vm) = (\"000011\"+vm +vs2e +vs1s +\"010\"+vds+\"1010111\", \"VREDXOR_VS \")\n def VREDMINU_VS (vds: String = vds, vs2e: String = ldForVs2, vs1s: String = vs1s, vm: String = vm) = (\"000100\"+vm +vs2e +vs1s +\"010\"+vds+\"1010111\", \"VREDMINU_VS \")\n def VREDMIN_VS (vds: String = vds, vs2e: String = ldForVs2, vs1s: String = vs1s, vm: String = vm) = (\"000101\"+vm +vs2e +vs1s +\"010\"+vds+\"1010111\", \"VREDMIN_VS \")\n def VREDMAXU_VS (vds: String = vds, vs2e: String = ldForVs2, vs1s: String = vs1s, vm: String = vm) = (\"000110\"+vm +vs2e +vs1s +\"010\"+vds+\"1010111\", \"VREDMAXU_VS \")\n def VREDMAX_VS (vds: String = vds, vs2e: String = ldForVs2, vs1s: String = vs1s, vm: String = vm) = (\"000111\"+vm +vs2e +vs1s +\"010\"+vds+\"1010111\", \"VREDMAX_VS \")\n val redInsts = Array(VWREDSUMU_VS(), VWREDSUM_VS(), VREDSUM_VS(),\n VREDAND_VS(), VREDOR_VS(), VREDXOR_VS(),\n VREDMINU_VS(), VREDMIN_VS(),\n VREDMAXU_VS(), VREDMAX_VS())\n //integer scalar move instructions\n def VMV_X_S (rd: String = rd, vs2s: String = vs2s) = (\"010000\"+\"1\"+vs2s +\"00000\"+\"010\"+rd +\"1010111\", \"VMV_X_S \")\n def VMV_S_X (vds: String = vds, rs1: String = rs1) = (\"010000\"+\"1\"+\"00000\"+rs1 +\"110\"+vds+\"1010111\", \"VMV_S_X \")\n val mvInsts = Array(VMV_X_S(), VMV_S_X())\n\n //CSR Insts\n def VSETVLI(rd: String = rd, rs1: String = rs1, vtypei: String = vtypei) = (\"0\"+vtypei +rs1 +\"111\"+rd +\"1010111\", \"VSETVLI \")\n def VSETVL (rd: String = rd, rs1: String = rs1, rs2: String = rs2) = (\"1\"+\"000000\"+rs2 +rs1 +\"111\"+rd +\"1010111\", \"VSETVL \")\n val CSRInsts = Array(VSETVLI(), VSETVL())\n\n //Load Insts\n def VLB_V (vde: String, rs1: String = rs1, vm: String = \"1\") = (\"000\"+\"100\"+vm+\"00000\"+rs1+\"000\"+vde+\"0000111\", \"VLB_V \")\n def VLBU_V (vde: String, rs1: String = rs1, vm: String = \"1\") = (\"000\"+\"000\"+vm+\"00000\"+rs1+\"000\"+vde+\"0000111\", \"VLBU_V \")\n def VLSB_V (vde: String, rs1: String = rs1, rs2: String = rs2, vm: String = \"1\") = (\"000\"+\"110\"+vm+rs2 +rs1+\"000\"+vde+\"0000111\", \"VLSB_V \")\n def VLSBU_V(vde: String, rs1: String = rs1, rs2: String = rs2, vm: String = \"1\") = (\"000\"+\"010\"+vm+rs2 +rs1+\"000\"+vde+\"0000111\", \"VLSBU_V \")\n def VLXB_V (vde: String, rs1: String = rs1, vs2e: String = vs2e, vm: String = \"1\") = (\"000\"+\"111\"+vm+vs2e +rs1+\"000\"+vde+\"0000111\", \"VLXB_V \")\n def VLXBU_V(vde: String, rs1: String = rs1, vs2e: String = vs2e, vm: String = \"1\") = (\"000\"+\"011\"+vm+vs2e +rs1+\"000\"+vde+\"0000111\", \"VLXBU_V \")\n def LBInsts(vde: String) = Array(VLB_V(vde), VLBU_V(vde),\n VLSB_V(vde), VLSBU_V(vde),\n VLXB_V(vde), VLXBU_V(vde))\n\n def VLH_V (vde: String, rs1: String = rs1, vm: String = \"1\") = (\"000\"+\"100\"+vm+\"00000\"+rs1+\"101\"+vde+\"0000111\", \"VLH_V \")\n def VLHU_V (vde: String, rs1: String = rs1, vm: String = \"1\") = (\"000\"+\"000\"+vm+\"00000\"+rs1+\"101\"+vde+\"0000111\", \"VLHU_V \")\n def VLSH_V (vde: String, rs1: String = rs1, rs2: String = rs2, vm: String = \"1\") = (\"000\"+\"110\"+vm+rs2 +rs1+\"101\"+vde+\"0000111\", \"VLSH_V \")\n def VLSHU_V(vde: String, rs1: String = rs1, rs2: String = rs2, vm: String = \"1\") = (\"000\"+\"010\"+vm+rs2 +rs1+\"101\"+vde+\"0000111\", \"VLSHU_V \")\n", "right_context": " def VLXHU_V(vde: String, rs1: String = rs1, vs2e: String = vs2e, vm: String = \"1\") = (\"000\"+\"011\"+vm+vs2e +rs1+\"101\"+vde+\"0000111\", \"VLXHU_V \")\n def LHInsts(vde: String) = Array(VLH_V(vde), VLHU_V(vde), \n VLSH_V(vde), VLSHU_V(vde), \n VLXH_V(vde), VLXHU_V(vde))\n\n def VLW_V (vde: String, rs1: String = rs1, vm: String = \"1\") = (\"000\"+\"100\"+vm+\"00000\"+rs1+\"110\"+vde+\"0000111\", \"VLW_V \")\n def VLWU_V (vde: String, rs1: String = rs1, vm: String = \"1\") = (\"000\"+\"000\"+vm+\"00000\"+rs1+\"110\"+vde+\"0000111\", \"VLWU_V \")\n def VLSW_V (vde: String, rs1: String = rs1, rs2: String = rs2, vm: String = \"1\") = (\"000\"+\"110\"+vm+rs2 +rs1+\"110\"+vde+\"0000111\", \"VLSW_V \")\n def VLSWU_V(vde: String, rs1: String = rs1, rs2: String = rs2, vm: String = \"1\") = (\"000\"+\"010\"+vm+rs2 +rs1+\"110\"+vde+\"0000111\", \"VLSWU_V \")\n def VLXW_V (vde: String, rs1: String = rs1, vs2e: String = vs2e, vm: String = \"1\") = (\"000\"+\"111\"+vm+vs2e +rs1+\"110\"+vde+\"0000111\", \"VLXW_V \")\n def VLXWU_V(vde: String, rs1: String = rs1, vs2e: String = vs2e, vm: String = \"1\") = (\"000\"+\"011\"+vm+vs2e +rs1+\"110\"+vde+\"0000111\", \"VLXWU_V \")\n def LWInsts(vde: String) = Array(VLW_V(vde), VLWU_V(vde),\n VLSW_V(vde), VLSWU_V(vde), \n VLXW_V(vde), VLXWU_V(vde))\n\n def VLE_V (vde: String, rs1: String = rs1, vm: String = \"1\") = (\"000\"+\"000\"+vm+\"00000\"+rs1+\"111\"+vde+\"0000111\", \"VLE_V \")\n def VLSE_V (vde: String, rs1: String = rs1, rs2: String = rs2, vm: String = \"1\") = (\"000\"+\"010\"+vm+rs2 +rs1+\"111\"+vde+\"0000111\", \"VLSE_V \")\n def VLXE_V (vde: String, rs1: String = rs1, vs2e: String = vs2e, vm: String = \"1\") = (\"000\"+\"011\"+vm+vs2e +rs1+\"111\"+vde+\"0000111\", \"VLXE_V \")\n def LEInsts(vde: String) = Array(VLE_V(vde), VLSE_V(vde), VLXE_V(vde))\n\n //Store Insts\n def VSB_V (vs3e: String, rs1: String = rs1, vm: String = vm) = (\"000\"+\"000\"+vm+\"00000\"+rs1+\"000\"+vs3e+\"0100111\", \"VSB_V \")\n def VSSB_V (vs3e: String, rs1: String = rs1, rs2: String = rs2, vm: String = vm) = (\"000\"+\"010\"+vm+rs2 +rs1+\"000\"+vs3e+\"0100111\", \"VSSB_V \")\n def VSXB_V (vs3e: String, rs1: String = rs1, vs2e: String = vs2e, vm: String = vm) = (\"000\"+\"011\"+vm+vs2e +rs1+\"000\"+vs3e+\"0100111\", \"VSXB_V \")\n def SBInsts(vs3e: String) = Array(VSB_V(vs3e), VSSB_V(vs3e), VSXB_V(vs3e))\n\n def VSH_V (vs3e: String, rs1: String = rs1, vm: String = vm) = (\"000\"+\"000\"+vm+\"00000\"+rs1+\"101\"+vs3e+\"0100111\", \"VSH_V \")\n def VSSH_V (vs3e: String, rs1: String = rs1, rs2: String = rs2, vm: String = vm) = (\"000\"+\"010\"+vm+rs2 +rs1+\"101\"+vs3e+\"0100111\", \"VSSH_V \")\n def VSXH_V (vs3e: String, rs1: String = rs1, vs2e: String = vs2e, vm: String = vm) = (\"000\"+\"011\"+vm+vs2e +rs1+\"101\"+vs3e+\"0100111\", \"VSXH_V \")\n def SHInsts(vs3e: String) = Array(VSH_V(vs3e), VSSH_V(vs3e), VSXH_V(vs3e))\n\n def VSW_V (vs3e: String, rs1: String = rs1, vm: String = vm) = (\"000\"+\"000\"+vm+\"00000\"+rs1+\"110\"+vs3e+\"0100111\", \"VSW_V \")\n def VSSW_V (vs3e: String, rs1: String = rs1, rs2: String = rs2, vm: String = vm) = (\"000\"+\"010\"+vm+rs2 +rs1+\"110\"+vs3e+\"0100111\", \"VSSW_V \")\n def VSXW_V (vs3e: String, rs1: String = rs1, vs2e: String = vs2e, vm: String = vm) = (\"000\"+\"011\"+vm+vs2e +rs1+\"110\"+vs3e+\"0100111\", \"VSXW_V \")\n def SWInsts(vs3e: String) = Array(VSW_V(vs3e), VSSW_V(vs3e), VSXW_V(vs3e))\n\n def VSE_V (vs3e: String, rs1: String = rs1, vm: String = vm) = (\"000\"+\"000\"+vm+\"00000\"+rs1+\"111\"+vs3e+\"0100111\", \"VSE_V \")\n def VSSE_V (vs3e: String, rs1: String = rs1, rs2: String = rs2, vm: String = vm) = (\"000\"+\"010\"+vm+rs2 +rs1+\"111\"+vs3e+\"0100111\", \"VSSE_V \")\n def VSXE_V (vs3e: String, rs1: String = rs1, vs2e: String = vs2e, vm: String = vm) = (\"000\"+\"011\"+vm+vs2e +rs1+\"111\"+vs3e+\"0100111\", \"VSXE_V \")\n def SEInsts(vs3e: String) = Array(VSE_V(vs3e), VSSE_V(vs3e), VSXE_V(vs3e))\n///////////////////////////instructions name-code pairs/////////////////////////\n\n\n def InstHex(inst: BigInt) = \"0\"*(8-inst.toString(16).length)+inst.toString(16)\n\n //delay x cycles, under 8 cycles\n step(rnd.nextInt(8))\n\n/////////////////////////////////////CSR Inst///////////////////////////////////\n for(i <- 0 until 1) {\n val (csrCode, csrName) = CSRInsts(rnd.nextInt(2))\n val csrInst = BigInt(csrCode, 2)\n\n writer.println(\"CSRInstName = \" + csrName + \" CSRInst = \" + InstHex(csrInst))\n writer.println()\n\n //poke a CSR instruction\n poke(c.io.core.req.valid, 1)\n poke(c.io.core.req.bits.inst, csrInst)\n step(1)\n poke(c.io.core.fromXData1, AVL)\n poke(c.io.core.fromXData2, vtype)\n }\n/////////////////////////////////////CSR Inst///////////////////////////////////\n\n\n///////////////////////////////////Load Insts///////////////////////////////////\n var j = 0\n for(i <- 0 until 2) {\n val vde = ldDstField(i)\n val LdInsts = if(SEW == 8) LBInsts(vde) ++ LEInsts(vde)\n else if(SEW == 16) LBInsts(vde) ++ LHInsts(vde) ++ LEInsts(vde)\n else if(SEW == 32) LBInsts(vde) ++ LHInsts(vde) ++ LWInsts(vde) ++ LEInsts(vde)\n else LEInsts(vde)\n val ldIndex = if(SEW == 8) rnd.nextInt(9)\n else if(SEW == 16) rnd.nextInt(15)\n else if(SEW == 32) rnd.nextInt(21)\n else rnd.nextInt(3)\n val (ldCode, ldName) = LdInsts(ldIndex)\n val ldInst = BigInt(ldCode, 2)\n val baseAddr = BigInt(5, scala.util.Random)\n val strideConst = BigInt(5, scala.util.Random)\n\n writer.println(\"LoadInstName = \" + ldName + \" LoadInst = \" + InstHex(ldInst) + \" vm = 1\" + \" vd = \" + BigInt(vde, 2))\n\n //poke load instruction\n poke(c.io.core.req.valid, 1)\n poke(c.io.core.req.bits.inst, ldInst)\n step(1)\n poke(c.io.core.fromXData1, baseAddr)\n poke(c.io.core.fromXData2, strideConst)\n step(1)\n\n var storeReq = Array((BigInt(0),BigInt(0),BigInt(0)),(BigInt(0),BigInt(0),BigInt(0)))\n //poke data\n while(peek(c.io.core.req.ready) == 0) {\n val reqValid: BigInt = peek(c.io.reqValid)\n val reqTag: BigInt = peek(c.io.reqTag)\n val reqSize: BigInt = peek(c.io.reqSize)\n val respHasData = peek(c.io.reqCmd)+1\n val respData = elemVal + j\n val reqReady = 1\n val s2Nack = 0\n storeReq = storeReq ++ Array((reqValid,reqTag,reqSize))\n\n poke(c.io.respValid, storeReq(0)._1)\n poke(c.io.respTag, storeReq(0)._2)\n poke(c.io.respSize, storeReq(0)._3)\n poke(c.io.respHasData, respHasData)\n poke(c.io.respData, respData)\n poke(c.io.reqReady, reqReady)\n poke(c.io.s2Nack, s2Nack)\n step(1)\n j = j + storeReq(0)._1.toInt\n storeReq = storeReq drop 1\n }\n }\n///////////////////////////////////Load Insts///////////////////////////////////\n\n writer.println()\n\n/////////////////////////////////////AL Insts///////////////////////////////////\n for(i <- 0 until 8) {\n val baseALInsts = addInsts ++ waddInsts ++ adcInsts ++ bitInsts ++ shiftInsts ++ nshiftInsts ++ cmpInsts ++ minInsts ++ mergeInsts\n val maskInsts = popcInst ++ firstInst ++ midxInsts ++ iotaInst ++ idInst ++ mbitInsts\n// val alInsts = baseALInsts ++ maskInsts ++ \n// (if(c.MULDIV) mulInsts ++ wmulInsts ++ divInsts else Nil) ++ \n// (if(c.MULADD) maddInsts ++ wmaddInsts else Nil) ++ \n// (if(c.RED) redInsts else Nil) ++ \n// (if(c.MV) mvInsts else Nil)\n val alInsts = redInsts\n val alInstSum = alInsts.length\n val (alCode, alName) = alInsts(rnd.nextInt(alInstSum))\n val alInst = BigInt(alCode, 2)\n val alDstField = (alInst & BigInt(\"00000000000000000000111110000000\", 2)) >> 7\n val alSrc1Field = (alInst & BigInt(\"00000000000011111000000000000000\", 2)) >> 15\n val alSrc2Field = (alInst & BigInt(\"00000001111100000000000000000000\", 2)) >> 20\n val alVmField = (alInst & BigInt(\"00000010000000000000000000000000\", 2)) >> 25\n val alDstFieldStr = \" \"*(2-alDstField.toString.length) + alDstField.toString\n val alSrc1FieldStr = \" \"*(2-alSrc1Field.toString.length) + alSrc1Field.toString\n val alSrc2FieldStr = \" \"*(2-alSrc2Field.toString.length) + alSrc2Field.toString\n\n writer.println(\"ALInstName = \" + alName + \" ALInst = \" + InstHex(alInst) + \" DstField = \" + alDstFieldStr + \" Src2Field = \" + alSrc2FieldStr + \" Src1Field = \" + alSrc1FieldStr + \" vm = \" + alVmField)\n\n //poke a AL instruction\n poke(c.io.core.req.valid, 1)\n poke(c.io.core.req.bits.inst, alInst)\n step(1)\n while(peek(c.io.core.req.ready) == 0)\n step(1)\n }\n/////////////////////////////////////AL Insts///////////////////////////////////\n\n writer.println()\n\n//////////////////////////////////Store Insts///////////////////////////////////\n for(i <- 0 until 1) {\n val stInsts = if(SEW == 8) SBInsts(vs3e) ++ SEInsts(vs3e)\n else if(SEW == 16) SBInsts(vs3e) ++ SHInsts(vs3e) ++ SEInsts(vs3e)\n else if(SEW == 32) SBInsts(vs3e) ++ SHInsts(vs3e) ++ SWInsts(vs3e) ++ SEInsts(vs3e)\n else SEInsts(vs3e)\n val stInstSum = stInsts.length\n val (stCode, stName) = stInsts(rnd.nextInt(stInstSum))\n val stInst = BigInt(stCode, 2)\n val stDstField = (stInst & BigInt(\"00000000000000000000111110000000\", 2)) >> 7\n val stSrc1Field = (stInst & BigInt(\"00000000000011111000000000000000\", 2)) >> 15\n val stSrc2Field = (stInst & BigInt(\"00000001111100000000000000000000\", 2)) >> 20\n val stVmField = (stInst & BigInt(\"00000010000000000000000000000000\", 2)) >> 25\n val stDstFieldStr = \" \"*(2-stDstField.toString.length) + stDstField.toString\n val stSrc1FieldStr = \" \"*(2-stSrc1Field.toString.length) + stSrc1Field.toString\n val stSrc2FieldStr = \" \"*(2-stSrc2Field.toString.length) + stSrc2Field.toString\n\n writer.println(\"StoreInstName = \" + stName + \" StoreInst = \" + InstHex(stInst) + \" vs3 = \" + stDstFieldStr + \" rs1 = \" + stSrc1FieldStr + \" src2Field = \" + stSrc2FieldStr + \" vm = \" + stVmField)\n\n //poke a store instruction\n poke(c.io.core.req.valid, 1)\n poke(c.io.core.req.bits.inst, stInst)\n step(1)\n/*\n for(k <- 0 until AVL) {\n poke(c.io.respValid, 1)\n poke(c.io.respTag, peek(c.io.reqTag))\n poke(c.io.respSize, peek(c.io.reqSize))\n poke(c.io.respHasData, 0)\n poke(c.io.respData, 0)\n poke(c.io.reqReady, 1)\n poke(c.io.s2Nack, 0)\n step(1)\n }\n*/\n var storeReq = Array((BigInt(0),BigInt(0),BigInt(0)),(BigInt(0),BigInt(0),BigInt(0)))\n //poke data\n while(peek(c.io.core.req.ready) == 0) {\n val reqValid: BigInt = peek(c.io.reqValid)\n val reqTag: BigInt = peek(c.io.reqTag)\n val reqSize: BigInt = peek(c.io.reqSize)\n val respHasData = peek(c.io.reqCmd)+1\n val respData = elemVal + j\n val reqReady = 1\n val s2Nack = 0\n storeReq = storeReq ++ Array((reqValid,reqTag,reqSize))\n\n poke(c.io.respValid, storeReq(0)._1)\n poke(c.io.respTag, storeReq(0)._2)\n poke(c.io.respSize, storeReq(0)._3)\n poke(c.io.respHasData, respHasData)\n poke(c.io.respData, respData)\n poke(c.io.reqReady, reqReady)\n poke(c.io.s2Nack, s2Nack)\n step(1)\n j = j + storeReq(0)._1.toInt\n storeReq = storeReq drop 1\n }\n }\n//////////////////////////////////Store Insts///////////////////////////////////\n poke(c.io.core.req.valid, 0)\n step(5)\n writer.close()\n}\n", "groundtruth": " def VLXH_V (vde: String, rs1: String = rs1, vs2e: String = vs2e, vm: String = \"1\") = (\"000\"+\"111\"+vm+vs2e +rs1+\"101\"+vde+\"0000111\", \"VLXH_V \")\n", "crossfile_context": ""}
{"task_id": "100DaysOfCHISEL", "path": "100DaysOfCHISEL/src/main/scala/day24/Mux_Case.scala", "left_context": "package day24\nimport chisel3._\nimport chisel3.util._\n", "right_context": " // 3 bit input\n val select = Input(UInt(3.W))\n // 32 bit output\n val out = Output (UInt (32.W))\n}\nclass Mux_Case extends Module {\n val io = IO (new LM_IO_Interface )\n //when the select pin matches with any of the condition that value is returned from the mux case\n // if no match is found the 0 is returned as the default value\n io.out := MuxCase(0.U, Array(\n (io.select === \"b000\".U) -> 0.U,\n (io.select === \"b001\".U) -> 8.U,\n (io.select === \"b010\".U) -> 16.U,\n (io.select === \"b011\".U) -> 24.U,\n (io.select === \"b100\".U) -> 32.U,\n ) )\n\n}", "groundtruth": "class LM_IO_Interface extends Bundle {\n", "crossfile_context": ""}
{"task_id": "100DaysOfCHISEL", "path": "100DaysOfCHISEL/src/main/scala/day26/branch_control.scala", "left_context": "package day26\n\nimport chisel3._\nimport chisel3.util._\nimport chisel3.stage.ChiselStage\n\nclass LM_IO_Interface_BranchControl extends Bundle {\n val fnct3 = Input ( UInt (3.W ) )\n val branch = Input ( Bool () )\n val arg_x = Input ( UInt (4.W ) )\n val arg_y = Input ( UInt (4.W ) )\n val br_taken = Output ( Bool () )\n}\n\nclass BranchControl extends Module{\n val io = IO (new LM_IO_Interface_BranchControl)\n\nwhen( io.branch === 1.B ){ // Check if the branch signal is high\n", "right_context": " io.br_taken := io.arg_x < io.arg_y // Branch taken if arg_x is less than arg_y\n }.elsewhen ( io.fnct3 === 5.U ) {\n io.br_taken := io.arg_x > io.arg_y // Branch taken if arg_x is greater than arg_y\n }.otherwise{\n io.br_taken := 0.B // Default case: branch not taken\n }\n\n}.otherwise{\n io.br_taken := 0.B\n}\n\n}", "groundtruth": " when ( io.fnct3 === 0.U ) {\n io.br_taken := io.arg_x === io.arg_y // Branch taken if arg_x is equal to arg_y\n }.elsewhen ( io.fnct3 === 1.U ) {\n", "crossfile_context": ""}
{"task_id": "100DaysOfCHISEL", "path": "100DaysOfCHISEL/src/main/scala/day27/ImmExtension.scala", "left_context": "package day27\n\nimport chisel3._\nimport chisel3.util._\n\n// IO definition for the Immediate Value Generator\n", "right_context": " val s = 35.U(7.W) // s-type opcode defined as per RISC-V standard\n val sb = 99.U(7.W) // sb-type opcode defined as per RISC-V standard\n val u = 55.U(7.W) // u-type opcode defined as per RISC-V standard\n val uj = 111.U(7.W)// uj-type opcode defined as per RISC-V standard\n val ei = 0.U(32.W) // Extra immediate, defined as zero in immediate\n}\n\n// Module for Immediate Extension\nclass ImmExtension extends Module {\n val io = IO(new LM_IO_Interface_ImmdValGen)\n\n // Immediate extension logic using Mux statements\n io.immd_se := Mux(\n io.instr(6, 0) === imm.i || io.instr(6, 0) === \"b0000011\".U || io.instr(6, 0) === \"b1100111\".U,\n Cat(imm.ei(19, 0), io.instr(31, 20)),\n Mux(\n io.instr(6, 0) === imm.s,\n Cat(imm.ei(19, 0), io.instr(31, 25), io.instr(11, 7)),\n Mux(\n io.instr(6, 0) === imm.sb,\n Cat(imm.ei(19, 0), io.instr(31), io.instr(7), io.instr(30, 25), io.instr(11, 8), \"b0\".U) + (io.pc_in).asUInt,\n Mux(\n io.instr(6, 0) === imm.u,\n Cat(io.instr(31, 12), imm.ei(11, 0)),\n Mux(\n io.instr(6, 0) === imm.uj,\n Cat(imm.ei(11, 0), io.instr(31), io.instr(19, 12), io.instr(20), io.instr(30, 21), \"b0\".U) + (io.pc_in).asUInt,\n 0.U\n ).asUInt\n )\n )\n )\n )\n}\n", "groundtruth": "class LM_IO_Interface_ImmdValGen extends Bundle {\n val instr = Input(UInt(32.W)) // 32-bit instruction input\n val pc_in = Input(SInt(32.W)) // 32-bit signed program counter input\n val immd_se = Output(UInt(32.W)) // 32-bit signed immediate output\n}\n", "crossfile_context": ""}
{"task_id": "100DaysOfCHISEL", "path": "100DaysOfCHISEL/src/main/scala/day29/ArbiterQueue.scala", "left_context": "package day29\nimport chisel3._\nimport chisel3.util._\n\nclass Arbriter extends Module{\n val io = IO (new Bundle {\n val in1 = Flipped (Decoupled(UInt(4.W)))\n val in2 = Flipped (Decoupled(UInt(4.W)))\n val out = Decoupled(UInt(4.W))\n", "right_context": "\nval arb_priority = Module (new Arbiter ( UInt () , 2) )\n\narb_priority.io.in(0) <> queue1\narb_priority.io.in(1) <> queue2\n\nio.out <> arb_priority.io.out\n}", "groundtruth": "})\nval queue1 = Queue (io.in1 , 5)\n", "crossfile_context": ""}
{"task_id": "100DaysOfCHISEL", "path": "100DaysOfCHISEL/src/main/scala/day3/Bitwidth.scala", "left_context": "package day3\n\nimport chisel3._\n\nclass Bitwidth extends Module {\n val io = IO(new Bundle { //Bundle Definition\n val input = Input(UInt(4.W)) //Datatype\n\n", "right_context": " val temp = Wire(SInt(4.W)) //wiring\n temp := io.input.asSInt //typecasting\n io.output := temp\n}\n", "groundtruth": " val output = Output(SInt(4.W))\r\n })\r\n", "crossfile_context": ""}
{"task_id": "100DaysOfCHISEL", "path": "100DaysOfCHISEL/src/test/scala/day1/Gates.scala", "left_context": "package day1\nimport chisel3._\nimport org.scalatest._\nimport chiseltest._\n\nclass GatesTests extends FreeSpec with ChiselScalatestTester {\n \"Gates Test\" in {\n test(new Gates()) {c =>\n c.io.a.poke(1.U)\n", "right_context": "\n c.clock.step(3)\n\n c.io.AND.expect(0.U)\n c.io.OR.expect(3.U)\n c.io.NOT.expect(14.U)\n c.io.NOR.expect(12.U)\n c.io.XOR.expect(3.U)\n c.io.XNOR.expect(12.U)\n }\n }\n}\n", "groundtruth": " c.io.b.poke(2.U)\r\n", "crossfile_context": ""}
{"task_id": "100DaysOfCHISEL", "path": "100DaysOfCHISEL/src/test/scala/day14/Adder_Param_Test.scala", "left_context": "package day14\nimport org.scalatest._\nimport chiseltest._\nimport chisel3._\n\nclass Adder_param_Test extends FreeSpec with ChiselScalatestTester{\n \"Adder_param\" in {\n", "right_context": "", "groundtruth": " test(new Adder(32)){c=>\n c.io.in_0.poke(12.U)\n c.io.in_1.poke(4.U)\n c.clock.step(100)}\n", "crossfile_context": ""}
{"task_id": "100DaysOfCHISEL", "path": "100DaysOfCHISEL/src/test/scala/day18/TwoStageQueueTest.scala", "left_context": "package day18\nimport chisel3._\nimport org.scalatest.FreeSpec\nimport chiseltest._\n\nclass My_QueueTest extends FreeSpec with ChiselScalatestTester {\n \"QueueTest\" in {\n test(new My_Queue) { c =>\n // Test case description: Test the My_Queue module.\n\n // Set the input data to 4 (bits) and indicate that it's valid.\n c.io.in.bits.poke(4.U)\n c.io.in.valid.poke(1.B)\n\n // Advance the simulation clock by 5 cycles.\n", "right_context": " }\n}\n", "groundtruth": " c.clock.step(5)\n\n // Expect that the output bits should be 4.\n", "crossfile_context": ""}
{"task_id": "100DaysOfCHISEL", "path": "100DaysOfCHISEL/src/test/scala/day19/OneShotTimerTest.scala", "left_context": "package day19\n\nimport chisel3._\nimport org.scalatest.FreeSpec\nimport chiseltest._\n\nclass OneShotTimerTest extends FreeSpec with ChiselScalatestTester{\n \"OneShotTimerTest test\" in{\n", "right_context": "", "groundtruth": " test(new OneShotTimerModule()){c =>\n c.clock.step(10) \n }\n", "crossfile_context": ""}
{"task_id": "100DaysOfCHISEL", "path": "100DaysOfCHISEL/src/test/scala/day23/Mux_2to1test.scala", "left_context": "package day23\n\nimport chisel3._\nimport chisel3.tester._\nimport org.scalatest.FreeSpec\nimport chisel3.experimental.BundleLiterals._\n\nclass Mux_2to1test extends FreeSpec with ChiselScalatestTester{\n \"lab 2 ex1Tester \" in {\n test(new Mux_2to1){ a=>\n a.io.in_A.poke(45.U) // input A\n a.io.in_B.poke(55.U) // input B\n a.io.select.poke(1.B) // select pin selects which input to send as output\n a.io.out.expect(45.U) // output received\n", "right_context": "", "groundtruth": " a.clock.step(4)\n\n }\n", "crossfile_context": ""}
{"task_id": "100DaysOfCHISEL", "path": "100DaysOfCHISEL/src/test/scala/day26/branch_controlTest.scala", "left_context": "package day26\n\nimport chisel3._\nimport org.scalatest.FreeSpec\nimport chiseltest._\n\n// Define a test class for the BranchControl module\nclass branch_controlTest extends FreeSpec with ChiselScalatestTester{\n \"branch_controlTest test\" in{\n", "right_context": "}", "groundtruth": " test(new BranchControl()){c =>\n c.io.fnct3.poke(1.U) // Set input signals for the BranchControl module\n c.io.branch.poke(1.B)\n c.io.arg_x.poke(1.U)\n c.io.arg_y.poke(0.U)\n", "crossfile_context": ""}
{"task_id": "chiselverify", "path": "chiselverify/src/main/scala/chiselverify/assembly/BinaryLoader.scala", "left_context": "package chiselverify.assembly\n\nimport java.nio.file.{Files, Paths}\n\nclass ProgramBinaries(n: String, bin: Array[Int], len: Int) {\n val name = n\n val byteBinaries = bin\n val wordBinaries = bin.map(BigInt(_)).sliding(4, 4).map(a => a(3) << 24 | a(2) << 16 | a(1) << 8 | a(0)).toArray\n val length = len\n}\n\nobject BinaryLoader {\n def loadProgram(path: String): ProgramBinaries = {\n val (bin, length) = loadBin(path)\n val split = path.split(Array('/', '\\\\'))\n val name = split(split.length - 1)\n new ProgramBinaries(name.substring(0, name.length - 4), bin, length)\n }\n\n def loadBin(path: String): (Array[Int], Int) = {\n val bytes = Files.readAllBytes(Paths.get(path)).map(_ & 0xFF).sliding(4, 4).toArray\n", "right_context": " (Array.concat(bytes.flatten, Array.fill(16)(0)), bytes.flatten.length / 4)\n }\n}\n", "groundtruth": " if (bytes(bytes.length - 1).length < 4) bytes(bytes.length - 1) = Array(0, 0, 0, 0)\n", "crossfile_context": ""}
{"task_id": "chiselverify", "path": "chiselverify/src/main/scala/chiselverify/assembly/Label.scala", "left_context": "package chiselverify.assembly\n\n/**\n * Functions for creating symbolic labels in generated assembly code\n * they are represented by instruction objects whose assembly code is\n * the label itself\n */\nobject Label {\n\n case class LabelRecord(id: String)\n\n // auto generated label factory\n def apply(): InstructionFactory with Categorizable = {\n Pattern(Category.Label)(implicit c => {\n val lbl = s\"RANDOM_LABEL_${c.labelCounter.inc()}\"\n c.jumpTargets.append(LabelRecord(lbl))\n Seq(Label.create(lbl))\n })\n }\n\n // user defined labels factory\n def apply(lbl: String): Pattern = {\n Pattern(implicit c => {\n c.jumpTargets.append(LabelRecord(lbl))\n Seq(Label.create(lbl))\n })\n }\n\n // create a anonymous instruction instance with the label name set as the assembly representation\n private def create(id: String): Instruction = {\n new Instruction(Category.Label) {\n override def apply(): Instruction = Label.create(id)\n", "right_context": " }\n }\n}\n", "groundtruth": " override def toAsm: String = s\"$id:\"\n", "crossfile_context": ""}
{"task_id": "chiselverify", "path": "chiselverify/src/main/scala/chiselverify/assembly/ProgramGenerator.scala", "left_context": "package chiselverify.assembly\n\nimport chiselverify.assembly.Label.LabelRecord\nimport chiselverify.assembly.RandomHelpers.{rand, randomSelect}\nimport chiselverify.assembly.AssemblyDistributions._\n\nimport java.io.{File, PrintWriter}\nimport scala.collection.mutable.ListBuffer\nimport scala.math.BigInt\nimport scala.util.Random\n\n/**\n * The generator context is used to collect information required during the generation process centrally\n * It holds all \"sampler\" functions which produce new values for instructions, memory addresses etc.\n * Global state like defined labels and the current PC are tracked here.\n * An instance of a generator context is passed down the function call tree which produces the final instruction sequence\n */\ncase class GeneratorContext(\n isa: InstructionSet,\n nextInstruction: Seq[Constraint] => InstructionFactory with Categorizable,\n nextMemoryAddress: Seq[Constraint] => BigInt,\n nextIOAddress: Seq[Constraint] => BigInt,\n nextJumpTarget: () => LabelRecord,\n pc: Counter,\n labelCounter: Counter,\n jumpTargets: ListBuffer[LabelRecord]\n)\n\nobject GeneratorContext {\n // a generator context can be defined by an ISA and a set of constraints\n def apply(isa: InstructionSet, constraints: Seq[Constraint]): GeneratorContext ={\n val pc = new Counter\n val targets = new ListBuffer[LabelRecord]()\n GeneratorContext(\n isa,\n createInstructionGenerator(isa, constraints),\n createMemoryAddressGenerator(isa, constraints),\n createIOAddressGenerator(isa, constraints),\n createJumpTargetGenerator(pc,targets),\n pc,\n new Counter,\n targets\n )\n }\n\n /**\n * The instruction generator gives access to a distribution driven instruction stream.\n * Additional white and black list constraints can be added when sampling.\n */\n private def createInstructionGenerator(isa: InstructionSet, constraints: Seq[Constraint]): Seq[Constraint] => InstructionFactory with Categorizable = { additionalConstraints =>\n // get all applicable instruction constraints\n val allCons = (constraints ++ additionalConstraints).collect { case x: InstructionConstraint => x }\n\n // apply black and white lists to find allowed categories\n val allowedCategories: Seq[Category] = allCons.foldLeft(Category.all) {\n case (cats, CategoryBlackList(bl@_*)) => cats.filter(!bl.contains(_))\n case (cats, CategoryWhiteList(w@_*)) => cats.filter(w.contains(_))\n case (cats, _) => cats\n }\n\n val blacklisted = allCons.collect { case CategoryBlackList(bl@_*) => bl}.flatten\n\n // find all distribution constraints\n val distConstraints = allCons.collect { case x: CategoryDistribution => x }.flatMap(_.dis)\n\n if (distConstraints.nonEmpty) {\n // sort out black listed categories\n val filtered = distConstraints.filter { case (c, _) => allowedCategories.contains(c) }\n\n // add the label category, to always make random labels appear\n val withLabel = filtered ++ Seq((Category.Label,filtered.map(_._2).sum * 0.15))\n\n // create uniform distributions with all applicable instructions for each category\n val distributionConstraints = withLabel.map { case (c, d) =>\n val instructions = (isa.instructions ++ Seq(Label())).filter(i => i.isOfCategory(c) && !i.isOfOneOfCategories(blacklisted))\n (instructions, d)\n }.filter(_._1.nonEmpty).map { case (instr, d) =>\n (discreteUniform(instr).sample(1).head, d)\n }\n\n // create the top level distribution which contains the category weights\n discrete(distributionConstraints: _*).sample(1).head\n } else {\n // no distribution was supplied and all allowed instructions are distributed uniformly\n randomSelect((isa.instructions ++ Seq(Label())).filter(i => i.isOfOneOfCategories(allowedCategories) && !i.isOfOneOfCategories(blacklisted)))\n }\n }\n\n /**\n * The memory address generator can be sampled to produce new memory addresses.\n * A distribution can be defined when the sampler is created.\n */\n private def createMemoryAddressGenerator(isa: InstructionSet, constraints: Seq[Constraint]): Seq[Constraint] => BigInt = { additionalConstraints =>\n val dis = constraints.collect { case x: MemoryDistribution => x }.toList match {\n case x :: _ => x.dis\n case _ => Seq(isa.memoryAddressSpace -> 1.0)\n }\n discrete(dis.map { case (r, d) => (rand(r), d) }: _*).sample(1).head\n }\n\n /**\n * The I/O address generator can be sampled to produce new I/O port addresses.\n * A distribution can be defined when the samples is created.\n */\n private def createIOAddressGenerator(isa: InstructionSet, constraints: Seq[Constraint]): Seq[Constraint] => BigInt = { additionalConstraints =>\n val dis = constraints.collect { case x: IODistribution => x }.toList match {\n case x :: _ => x.dis\n case _ => Seq(isa.inputOutputAddressSpace -> 1.0)\n }\n discrete(dis.map { case (r, d) => (rand(r), d) }: _*).sample(1).head\n }\n\n /**\n * The jump target generator produces references to defined symbolic labels in the produced assembly code\n */\n private def createJumpTargetGenerator(pc: Counter, targets: ListBuffer[LabelRecord]): () => LabelRecord = { () =>\n if(targets.nonEmpty) randomSelect(targets.toSeq) else LabelRecord(\"RANDOM_LABEL_0\")\n }\n}\n\nobject ProgramGenerator {\n def apply(isa: InstructionSet)(constraints: Constraint*): ProgramGenerator = {\n new ProgramGenerator(GeneratorContext(isa, constraints))\n }\n}\n\n/**\n * Wrapper for the generated instruction sequence.\n *\n * Gives access to some distribution statistics and printing as well as saving to file methods\n */\ncase class Program(instructions: Seq[Instruction], isa: InstructionSet) {\n // returns the assembly code\n override def toString: String = instructions.map(_.toAsm).map { str =>\n if (str.contains(':')) str else \" \" + str\n }.mkString(\"\\n\")\n\n // assembly code + instruction and category histograms\n def pretty: String = {\n", "right_context": " }\n\n // the number of occurrences for each instruction in the program\n def histogram: Seq[(String, Int)] = {\n instructions\n .map(_.toAsm.split(\" \").head)\n .filter(!_.contains(':'))\n .distinct.map { instr =>\n instr -> instructions.count(_.toAsm.split(\" \").head == instr)\n }\n }\n\n // the number of instructions matching the different categories\n def categoryHistogram: Seq[(String, Int)] = {\n Category.all.map { c =>\n (c.toString, instructions.count(_.categories.contains(c)))\n }\n }\n\n // export the assembly code to a file\n def saveToFile(fileName: String): Unit = {\n val writer = new PrintWriter(new File(fileName))\n writer.write(toString+\"\\n\")\n writer.close()\n }\n}\n\n/**\n * A program generator object is characterized by its constraints which are applied to every\n * generation call. A specific seed can be provided when generating a new sequence.\n */\nclass ProgramGenerator(context: GeneratorContext) {\n\n // generate approximately n instructions using the passed seed\n def generate(n: Int, seed: Long): Program = {\n Random.setSeed(seed)\n Program(Seq.fill(n)(context.nextInstruction(Seq()).produce()(context)).flatten, context.isa)\n }\n\n // generate approximately n instructions using a random seed\n def generate(n: Int): Program = {\n generate(n, Random.nextLong())\n }\n\n // generate an instruction sequence based on a pattern using the passed seed\n def generate(p: Pattern, seed: Long): Program = {\n Random.setSeed(seed)\n Program(p.produce()(context), context.isa)\n }\n\n // generate an instruction sequence based on a pattern with a random seed\n def generate(p: Pattern): Program = {\n generate(p, Random.nextLong())\n }\n}\n", "groundtruth": " s\"$this\\n\\nInstruction histogram:\\n${this.histogram.map(_.toString()).mkString(\", \")}\\nCategory histogram:\\n${this.categoryHistogram.map(_.toString()).mkString(\", \")}\\n\"\n", "crossfile_context": ""}
{"task_id": "chiselverify", "path": "chiselverify/src/main/scala/chiselverify/crv/RandObj.scala", "left_context": "package chiselverify.crv\n\ntrait RandObj {\n /** Randomize the current object\n * @return Boolean returns true only if a solution was found\n */\n def randomize: Boolean\n\n /** Randomize the current object with additional [[Constraint]]\n * @return Boolean returns true only if a solution was found\n */\n def randomizeWith(constraints: CRVConstraint*): Boolean\n\n /** Method containing a set of directives to run before the current object is randomized\n */\n", "right_context": "\n /** Method containing a set of directives to run after the current object is randomized\n */\n def postRandomize(): Unit = {}\n}\n", "groundtruth": " def preRandomize(): Unit = {}\n", "crossfile_context": ""}
{"task_id": "chiselverify", "path": "chiselverify/src/main/scala/chiselverify/crv/backends/jacop/DistConstraint.scala", "left_context": "package chiselverify.crv.backends.jacop\n\nimport scala.collection.immutable\nimport scala.util.Random\n\nimport chiselverify.crv.CRVException\n\ntrait DistTrait {\n protected val random: Random\n protected val wConstraintGList: Seq[WConstraintGroup]\n protected val _var: Rand\n /**\n * Like for normal constraints, the distribution constraint can be enabled or disabled\n */\n var isEnabled = true\n\n /** \n * Disables the constraint\n */\n def disable(): Unit = {\n isEnabled = false\n }\n\n /** \n * Enables the constraint\n * \n * Each constraint is by default enabled when instantiated. This method has effect only if called after [[disable]]\n */\n def enable(): Unit = {\n isEnabled = true\n }\n\n /**\n * Randomly enables one of the constraint groups defined in the constraint group list\n */\n def randomlyEnable(): Unit = {\n val number = random.nextDouble()\n wConstraintGList.find(x => x.contains(number)) match {\n", "right_context": " case Some(x) => x.enable()\n }\n }\n\n /**\n * Disables all the constraints in the constraint group list\n */\n def disableAll(): Unit = wConstraintGList foreach (_.disable())\n\n /**\n * From a list of doubles creates a list of buckets where the min is the current double and the max is the next element on the list\n */\n protected def swipeAndSum(buckets: List[Double]): List[Bucket] = {\n buckets match {\n case Nil => Nil\n case _ :: Nil => Nil\n case x :: xs => Bucket(x, xs.head) :: swipeAndSum(xs)\n }\n }\n}\n\n/**\n * Create a [[DistConstraint]] between a [[Rand]] and a list of [[WeightedRange]] and [[WeightedValue]]\n * @param variable the [[Rand]] variable to constrain\n * @param listOfDistC list of [[WeightedRange]] and [[WeightedValue]]\n * @param model implicit [[Model]] of the current [[RandObj]]\n */\nclass DistConstraint(variable: Rand, listOfDistC: List[Weight])(implicit model: Model) extends DistTrait {\n protected override val _var: Rand = variable\n protected override val random = new Random(model.seed + listOfDistC.length)\n\n /**\n * Creates a [[WConstraintGroup]] based on the type of [[Weight]] and [[Bucket]]\n * @param rangeAndBucket tuple of [[Weight]] and [[Bucket]]\n * @return the defined constraint group\n */\n private def createWeightedConstraintGroup(rangeAndBucket: (Weight, Bucket)) = {\n rangeAndBucket match {\n case (weight, bucket) => weight match {\n case WeightedRange(range, _) => new WConstraintGroup(bucket, variable > range.start, variable <= range.end)\n case WeightedValue(value, _) => new WConstraintGroup(bucket, variable == value)\n }\n }\n }\n\n /**\n * Constraint group list\n */\n protected override val wConstraintGList = {\n val total: Double = listOfDistC.map(_.weight).sum.toDouble\n val buckets: List[Double] = listOfDistC.map(_.weight / total).scan(0.0)((a, b) => a + b)\n val zipped = listOfDistC zip swipeAndSum(buckets)\n zipped.map(createWeightedConstraintGroup)\n }\n}\n", "groundtruth": " case None => throw CRVException(s\"Something went wrong in the distribution selection of ${_var.toString}\")\n", "crossfile_context": ""}
{"task_id": "chiselverify", "path": "chiselverify/src/main/scala/chiselverify/crv/backends/jacop/IfCon.scala", "left_context": "package chiselverify.crv.backends.jacop\n\nimport org.jacop.constraints.PrimitiveConstraint\n\n/** \n * Since not all csp solvers have support for conditional constraints, the IfThen and IfThenElse are not part of the common crv package.\n */\nclass IfCon(val const: JaCoPConstraint, val ifC: chiselverify.crv.CRVConstraint, val thenC: chiselverify.crv.CRVConstraint)(implicit model: Model)\n extends JaCoPConstraint(const.getConstraint) {\n\n /** \n * Companion class for creating if-then-else constraint\n * @param ifCons an IfConstraint\n * @param elseC an ElseConstraint\n */\n class IfElseCon(val ifCons: IfCon, val elseC: chiselverify.crv.CRVConstraint) extends IfCon(const, ifC, thenC) {\n val newConstraint = new org.jacop.constraints.IfThenElse(\n ifC.getConstraint.asInstanceOf[PrimitiveConstraint],\n thenC.getConstraint.asInstanceOf[PrimitiveConstraint],\n elseC.getConstraint.asInstanceOf[PrimitiveConstraint]\n )\n val crvc = new JaCoPConstraint(newConstraint)\n model.crvconstr += crvc\n elseC.disable()\n\n", "right_context": " crvc.enable()\n }\n }\n\n override def enable(): Unit = {\n const.enable()\n }\n\n override def disable(): Unit = {\n const.disable()\n }\n\n /** Create an if-then-else constraint\n * @param elseC the constraint to be applied if the ifC condition is NOT true\n * @return\n */\n def ElseC(elseC: chiselverify.crv.CRVConstraint): IfElseCon = {\n const.disable()\n new IfElseCon(this, elseC)\n }\n\n // Initialization conde\n model.crvconstr += const\n ifC.disable()\n thenC.disable()\n}\n\n/** \n * Helper object for defining IfThen constraints\n */\nobject IfCon {\n /** \n * Creates a new IfThen constraint\n * @param ifC the if condition represented as a constraint\n * @param thenC the constraint to be applied if the ifC condition is true\n * @param model the current [[Model]], constraint can only be defined inside a [[RandObj]]\n * @return return the newly constructed [[Constraint]]\n */\n def apply(ifC: chiselverify.crv.CRVConstraint)(thenC: chiselverify.crv.CRVConstraint)(implicit model: Model): IfCon = {\n val newConstraint =\n new org.jacop.constraints.IfThen(\n ifC.getConstraint.asInstanceOf[PrimitiveConstraint],\n thenC.getConstraint.asInstanceOf[PrimitiveConstraint]\n )\n val crvc = new JaCoPConstraint(newConstraint)\n new IfCon(crvc, ifC, thenC)\n }\n}\n", "groundtruth": " override def disable(): Unit = {\n crvc.disable()\n }\n", "crossfile_context": ""}
{"task_id": "chiselverify", "path": "chiselverify/src/main/scala/chiselverify/crv/backends/jacop/package.scala", "left_context": "package chiselverify.crv.backends\n\nimport org.jacop.constraints._\nimport org.jacop.core.IntDomain\nimport org.jacop.scala.{IntSet, SetVar}\nimport org.jacop.set.constraints.{EinA, XinA}\nimport scala.util.Random\n\nimport chiselverify.crv.randName\n\npackage object jacop {\n type RandVar = Rand\n type RandCVar = Randc\n private[crv] class Rand(name: String, min: Int, max: Int)(implicit val model: Model)\n extends org.jacop.core.IntVar(model, name, min, max)\n with chiselverify.crv.Rand {\n\n override type U = Rand\n\n /** Defines an anonymous finite domain integer variable.\n *\n * @constructor Creates a new finite domain integer variable.\n * @param min minimal value of variable's domain.\n * @param max maximal value of variable's domain.\n */\n def this(min: Int, max: Int)(implicit model: Model) = {\n this(\"_$\" + model.n, min, max)(model)\n model.n += 1\n }\n\n /** Defines an anonymous finite domain integer variable.\n *\n * @constructor Creates a new finite domain integer variable with minimal and maximal\n * values in the domain defined by [[org.jacop]]\n * @param name variable's identifier.\n */\n def this(name: String)(implicit model: Model) = {\n this(name, org.jacop.core.IntDomain.MinInt, org.jacop.core.IntDomain.MaxInt)(model)\n model.n += 1\n }\n\n /** Defines an anonymous finite domain integer variable.\n *\n * @constructor Creates a new finite domain integer variable with minimal and maximal\n * values in the domain defined by [[org.jacop]]\n */\n def this()(implicit model: Model) = {\n this(org.jacop.core.IntDomain.MinInt, org.jacop.core.IntDomain.MaxInt)(model)\n model.n += 1\n }\n\n /** Defines a finite domain integer variable.\n *\n * @constructor Create a new finite domain integer variable with the domain defined by IntSet.\n * @param dom variable's domain defined as a set of integers IntSet.\n */\n def this(dom: IntSet)(implicit model: Model) = {\n this()(model)\n this.dom.intersectAdapt(dom)\n model.n += 1\n }\n\n /** Defines a finite domain integer variable.\n *\n * @constructor Create a new finite domain integer variable with the domain\n * defined by IntSet.\n * @param name variable's identifier.\n * @param dom variable's domain defined as a set of IntSet.\n */\n def this(name: String, dom: IntSet)(implicit model: Model) = {\n this(name)(model)\n this.dom.intersectAdapt(dom)\n model.n += 1\n }\n\n /** Assign a specific value to the current variable\n * @param v BigInt\n */\n def setVar(v: BigInt): Unit = {\n require(v < Int.MaxValue)\n setDomain(v.toInt, v.toInt)\n }\n\n /** Defines the add [[JaCoPConstraint]] between two Rand variables\n *\n * @param that a second parameter for the addition constraint\n * @return [[Rand]] variable being the result of the addition [[JaCoPConstraint]].\n */\n def +(that: Rand): Rand = {\n val result = new Rand(IntDomain.addInt(this.min(), that.min()), IntDomain.addInt(this.max(), that.max()))\n val c = new XplusYeqZ(this, that, result)\n model.crvconstr += new JaCoPConstraint(c)\n result\n }\n\n /** Defines add [[JaCoPConstraint]] between Rand and an integer value.\n *\n * @param that a second integer parameter for the addition [[JaCoPConstraint]].\n * @return [[Rand]] variable being the result of the addition [[JaCoPConstraint]].\n */\n def +(that: BigInt): Rand = {\n require(that <= Int.MaxValue)\n val result = new Rand(IntDomain.addInt(this.min(), that.toInt), IntDomain.addInt(this.max(), that.toInt))\n val c = new XplusCeqZ(this, that.toInt, result)\n model.crvconstr += new JaCoPConstraint(c)\n result\n }\n\n /** Defines subtract [[JaCoPConstraint]] between two Rand.\n *\n * @param that a second parameter for the subtraction [[JaCoPConstraint]].\n * @return [[Rand]] variable being the result of the subtraction [[JaCoPConstraint]].\n */\n def -(that: Rand): Rand = {\n val result = new Rand(IntDomain.subtractInt(this.min(), that.max()), IntDomain.subtractInt(this.max(), that.min()))\n val c = new XplusYeqZ(result, that, this)\n model.crvconstr += new JaCoPConstraint(c)\n result\n }\n\n /** Defines subtract [[JaCoPConstraint]] between [[Rand]] and an integer value.\n *\n * @param that a second integer parameter for the subtraction [[JaCoPConstraint]].\n * @return [[Rand]] variable being the result of the subtraction [[JaCoPConstraint]].\n */\n def -(that: BigInt): Rand = {\n require(that <= Int.MaxValue)\n val result = new Rand(IntDomain.subtractInt(this.min(), that.toInt), IntDomain.subtractInt(this.max(), that.toInt))\n val c = new XplusCeqZ(result, that.toInt, this)\n val crvc = new JaCoPConstraint(c)\n model.crvconstr += crvc\n result\n }\n\n /** Defines equation [[JaCoPConstraint]] between two [[Rand]].\n *\n * @param that a second parameter for equation [[JaCoPConstraint]].\n * @return the defined [[JaCoPConstraint]].\n */\n def ==(that: Rand): JaCoPConstraint = {\n val c = new XeqY(this, that)\n val crvc = new JaCoPConstraint(c)\n model.crvconstr += crvc\n crvc\n }\n\n /** Defines equation [[JaCoPConstraint]] between [[Rand]] and a integer constant.\n *\n * @param that a second parameter for equation [[JaCoPConstraint]].\n * @return the defined [[JaCoPConstraint]].\n */\n def ==(that: BigInt): JaCoPConstraint = {\n require(that <= Int.MaxValue)\n val c = new XeqC(this, that.toInt)\n val crvc = new JaCoPConstraint(c)\n model.crvconstr += crvc\n crvc\n }\n def ==(that: Int): JaCoPConstraint = ==(BigInt(that))\n\n /** Defines multiplication [[JaCoPConstraint]] between two [[Rand]].\n *\n * @param that a second parameter for the multiplication [[JaCoPConstraint]].\n * @return [[Rand]] variable being the result of the multiplication [[JaCoPConstraint]].\n */\n def *(that: Rand): Rand = {\n val bounds = IntDomain.mulBounds(this.min(), this.max(), that.min(), that.max())\n val result = new Rand(bounds.min(), bounds.max())\n val c = new XmulYeqZ(this, that, result)\n model.crvconstr += new JaCoPConstraint(c)\n result\n }\n\n /** Defines multiplication [[JaCoPConstraint]] between [[Rand]] and an integer value.\n *\n * @param that a second integer parameter for the multiplication [[JaCoPConstraint]].\n * @return [[Rand]] variable being the result of the multiplication [[JaCoPConstraint]].\n */\n def *(that: BigInt): Rand = {\n require(that <= Int.MaxValue)\n val bounds = IntDomain.mulBounds(this.min(), this.max(), that.toInt, that.toInt)\n val result = new Rand(bounds.min(), bounds.max())\n val c = new XmulCeqZ(this, that.toInt, result)\n model.crvconstr += new JaCoPConstraint(c)\n result\n }\n\n /** Defines integer division [[JaCoPConstraint]] between two [[Rand]].\n *\n * @param that a second parameter for the integer division [[JaCoPConstraint]].\n * @return [[Rand]] variable being the result of the integer division [[JaCoPConstraint]].\n */\n def div(that: Rand): Rand = {\n val bounds = IntDomain.divBounds(this.min(), this.max(), that.min(), that.max())\n val result = new Rand(bounds.min(), bounds.max())\n val c = new XdivYeqZ(this, that, result)\n model.crvconstr += new JaCoPConstraint(c)\n result\n }\n\n /** Defines integer division [[JaCoPConstraint]] between [[Rand]] and an integer value.\n *\n * @param that a second parameter for the integer division [[JaCoPConstraint]].\n * @return [[Rand]] variable being the result of the integer division [[JaCoPConstraint]].\n */\n def div(that: BigInt): Rand = {\n require(that < Int.MaxValue)\n this.div(new Rand(that.toInt, that.toInt))\n }\n\n /** Defines [[JaCoPConstraint]] for integer reminder from division between two [[Rand]].\n *\n * @param that a second parameter for integer reminder from division [[JaCoPConstraint]].\n * @return [[Rand]] variable being the result of the integer reminder from division [[JaCoPConstraint]].\n */\n def mod(that: Rand): Rand = {\n var reminderMin: Int = 0\n var reminderMax: Int = 0\n\n if (this.min() >= 0) {\n reminderMin = 0\n reminderMax = Math.max(Math.abs(that.min()), Math.abs(that.max())) - 1\n } else if (this.max() < 0) {\n reminderMax = 0\n reminderMin = -Math.max(Math.abs(that.min()), Math.abs(that.max())) + 1\n } else {\n reminderMin = Math.min(Math.min(that.min(), -that.min()), Math.min(that.max(), -that.max())) + 1\n reminderMax = Math.max(Math.max(that.min(), -that.min()), Math.max(that.max(), -that.max())) - 1\n }\n\n val result = new Rand(reminderMin, reminderMax)\n val c = new XmodYeqZ(this, that, result)\n model.crvconstr += new JaCoPConstraint(c)\n result\n }\n\n /** Defines [[JaCoPConstraint]] for integer reminder from division [[Rand]] and an integer value.\n *\n * @param that a second parameter for integer reminder from division [[JaCoPConstraint]].\n * @return [[Rand]] variable being the result of the integer reminder from division [[JaCoPConstraint]].\n */\n def mod(that: BigInt): Rand = {\n require(that <= Int.MaxValue)\n this.mod(new Rand(that.toInt, that.toInt))\n }\n\n /** Defines exponentiation [[JaCoPConstraint]] between two [[Rand]].\n *\n * @param that exponent for the exponentiation [[JaCoPConstraint]].\n * @return [[Rand]] variable being the result of the exponentiation [[JaCoPConstraint]].\n */\n def ^(that: Rand): Rand = {\n val result = new Rand()\n val c = new XexpYeqZ(this, that, result)\n model.crvconstr += new JaCoPConstraint(c)\n result\n }\n\n /** Defines exponentiation [[JaCoPConstraint]] between [[Rand]] and an integer value.\n *\n * @param that exponent for the exponentiation [[JaCoPConstraint]].\n * @return [[Rand]] variable being the result of the exponentiation [[JaCoPConstraint]].\n */\n def ^(that: BigInt): Rand = {\n require(that <= Int.MaxValue)\n this ^ new Rand(that.toInt, that.toInt)\n }\n\n /** Defines unary \"-\" [[JaCoPConstraint]] for [[Rand]].\n *\n * @return the defined [[JaCoPConstraint]].\n */\n def unary_- : Rand = {\n val result = new Rand(-this.max(), -this.min())\n val c = new XplusYeqC(this, result, 0)\n model.crvconstr += new JaCoPConstraint(c)\n result\n }\n\n /** Defines inequality [[JaCoPConstraint]] between two [[Rand]].\n *\n * @param that a second parameter for inequality [[JaCoPConstraint]].\n * @return the defined [[JaCoPConstraint]].\n */\n def \\=(that: Rand): JaCoPConstraint = {\n val c = new XneqY(this, that)\n val crvc = new JaCoPConstraint(c)\n model.crvconstr += crvc\n crvc\n }\n\n /** Defines inequality [[JaCoPConstraint]] between [[Rand]] and integer constant.\n *\n * @param that a second parameter for inequality [[JaCoPConstraint]].\n * @return the defined [[JaCoPConstraint]].\n */\n def \\=(that: BigInt): JaCoPConstraint = {\n require(that <= Int.MaxValue)\n val c = new XneqC(this, that.toInt)\n val crvc = new JaCoPConstraint(c)\n model.crvconstr += crvc\n crvc\n }\n\n /** Defines \"less than\" [[JaCoPConstraint]] between two [[Rand]].\n *\n * @param that a second parameter for \"less than\" [[JaCoPConstraint]].\n * @return the defined [[JaCoPConstraint]].\n */\n def <(that: Rand): JaCoPConstraint = {\n val c = new XltY(this, that)\n val crvc = new JaCoPConstraint(c)\n model.crvconstr += crvc\n crvc\n }\n\n /** Defines \"less than\" [[JaCoPConstraint]] between [[Rand]] and integer constant.\n *\n * @param that a second parameter for \"less than\" [[JaCoPConstraint]].\n * @return the equation [[JaCoPConstraint]].\n */\n def <(that: BigInt): JaCoPConstraint = {\n require(that <= Int.MaxValue)\n val c = new XltC(this, that.toInt)\n val crvc = new JaCoPConstraint(c)\n model.crvconstr += crvc\n crvc\n }\n\n /** Defines \"less than or equal\" [[JaCoPConstraint]] between two [[Rand]].\n *\n * @param that a second parameter for \"less than or equal\" [[JaCoPConstraint]].\n * @return the defined [[JaCoPConstraint]].\n */\n def <=(that: Rand): JaCoPConstraint = {\n val c = new XlteqY(this, that)\n val crvc = new JaCoPConstraint(c)\n model.crvconstr += crvc\n crvc\n }\n\n /** Defines \"less than or equal\" [[JaCoPConstraint]] between [[Rand]] and integer constant.\n *\n * @param that a second parameter for \"less than or equal\" [[JaCoPConstraint]].\n * @return the equation [[JaCoPConstraint]].\n */\n def <=(that: BigInt): JaCoPConstraint = {\n require(that <= Int.MaxValue)\n val c = new XlteqC(this, that.toInt)\n val crvc = new JaCoPConstraint(c)\n model.crvconstr += crvc\n crvc\n }\n\n /** Defines \"greater than\" [[JaCoPConstraint]] between two [[Rand]].\n *\n * @param that a second parameter for \"greater than\" [[JaCoPConstraint]].\n * @return the defined [[JaCoPConstraint]].\n */\n def >(that: Rand): JaCoPConstraint = {\n val c = new XgtY(this, that)\n val crvc = new JaCoPConstraint(c)\n model.crvconstr += crvc\n crvc\n }\n\n /** Defines \"greater than\" [[JaCoPConstraint]] between [[Rand]] and integer constant.\n *\n * @param that a second parameter for \"greater than\" [[JaCoPConstraint]].\n * @return the equation [[JaCoPConstraint]].\n */\n def >(that: BigInt): JaCoPConstraint = {\n require(that <= Int.MaxValue)\n val c = new XgtC(this, that.toInt)\n val crvc = new JaCoPConstraint(c)\n model.crvconstr += crvc\n crvc\n }\n\n /** Defines \"greater than or equal\" [[JaCoPConstraint]] between two [[Rand]].\n *\n * @param that a second parameter for \"greater than or equal\" [[JaCoPConstraint]].\n * @return the defined [[JaCoPConstraint]].\n */\n def >=(that: Rand): JaCoPConstraint = {\n val c = new XgteqY(this, that)\n val crvc = new JaCoPConstraint(c)\n model.crvconstr += crvc\n crvc\n }\n\n /** Defines \"greater than or equal\" [[JaCoPConstraint]] between [[Rand]] and integer constant.\n *\n * @param that a second parameter for \"greater than or equal\" [[JaCoPConstraint]].\n * @return the equation [[JaCoPConstraint]].\n */\n def >=(that: BigInt): JaCoPConstraint = {\n require(that <= Int.MaxValue)\n val c = new XgteqC(this, that.toInt)\n val crvc = new JaCoPConstraint(c)\n model.crvconstr += crvc\n crvc\n }\n\n /** defines the add constraint between two [[Rand]] variables.\n * @param that a second parameter for the addition constraint\n * @return rand variable being the result of the addition constraint.\n */\n def #+(that: U): U = this.+(that)\n\n /** defines the add constraint between a [[Rand]] variable and a BigInt.\n * @param that a second parameter for the addition constraint\n * @return rand variable being the result of the addition constraint.\n */\n def #+(that: BigInt): U = this.+(that)\n\n /** defines the subtraction constraint between two [[Rand]] variables.\n * @param that a second parameter for the addition constraint\n * @return rand variable being the result of the addition constraint.\n */\n def #-(that: U): U = this.-(that)\n\n /** defines the subtraction constraint between a [[Rand]] variable and a BigInt.\n * @param that a second parameter for the addition constraint\n * @return rand variable being the result of the addition constraint.\n */\n def #-(that: BigInt): U = this.-(that)\n\n /** defines the multiplication constraint between two [[Rand]] variables.\n * @param that a second parameter for the addition constraint\n * @return rand variable being the result of the addition constraint.\n */\n def #*(that: U): U = this.*(that)\n\n /** defines the multiplication constraint between a [[Rand]] variable and a BigInt.\n * @param that a second parameter for the addition constraint\n * @return rand variable being the result of the addition constraint.\n */\n def #*(that: BigInt): U = this.*(that)\n\n /** defines the exponential constraint between two [[Rand]] variables.\n * @param that a second parameter for the addition constraint\n * @return rand variable being the result of the addition constraint.\n */\n", "right_context": "\n /** defines the exponential constraint between a [[Rand]] variable and a BigInt.\n * @param that a second parameter for the addition constraint\n * @return rand variable being the result of the addition constraint.\n */\n def #^(that: BigInt): U = this.^(that)\n\n /** Defines inequality [[JaCoPConstraint]] between [[Rand]] and BigInt constant.\n *\n * @param that a second parameter for inequality [[JaCoPConstraint]].\n * @return the defined [[JaCoPConstraint]].\n */\n def #\\=(that: U): JaCoPConstraint = this.\\=(that)\n\n /** Defines inequality [[JaCoPConstraint]] between [[Rand]] and BigInt constant.\n *\n * @param that a second parameter for inequality [[JaCoPConstraint]].\n * @return the defined [[JaCoPConstraint]].\n */\n def #\\=(that: BigInt): JaCoPConstraint = this.\\=(that)\n\n /** Defines inequality [[JaCoPConstraint]] between [[Rand]] and BigInt constant.\n *\n * @param that a second parameter for inequality [[JaCoPConstraint]].\n * @return the defined [[JaCoPConstraint]].\n */\n def #=(that: U): JaCoPConstraint = this.==(that)\n\n /** Defines inequality [[JaCoPConstraint]] between [[Rand]] and BigInt constant.\n *\n * @param that a second parameter for inequality [[JaCoPConstraint]].\n * @return the defined [[JaCoPConstraint]].\n */\n def #=(that: BigInt): JaCoPConstraint = this.==(that)\n\n /** Defines \"less than\" [[JaCoPConstraint]] between two [[Rand]].\n *\n * @param that a second parameter for \"less than\" [[JaCoPConstraint]].\n * @return the defined [[JaCoPConstraint]].\n */\n def #<(that: U): JaCoPConstraint = this.<(that)\n\n /** Defines \"less than\" [[JaCoPConstraint]] between [[Rand]] and BigInt constant.\n *\n * @param that a second parameter for \"less than\" [[JaCoPConstraint]].\n * @return the equation [[JaCoPConstraint]].\n */\n def #<(that: BigInt): JaCoPConstraint = this.<(that)\n\n /** Defines \"less than or equal\" [[JaCoPConstraint]] between two [[Rand]].\n *\n * @param that a second parameter for \"less than or equal\" [[JaCoPConstraint]].\n * @return the defined [[JaCoPConstraint]].\n */\n def #<=(that: U): JaCoPConstraint = this.<=(that)\n\n /** Defines \"less than or equal\" [[JaCoPConstraint]] between [[Rand]] and BigInt constant.\n *\n * @param that a second parameter for \"less than or equal\" [[JaCoPConstraint]].\n * @return the equation [[JaCoPConstraint]].\n */\n def #<=(that: BigInt): JaCoPConstraint = this.<=(that)\n\n /** Defines \"greater than\" [[JaCoPConstraint]] between two [[Rand]].\n *\n * @param that a second parameter for \"greater than or equal\" [[JaCoPConstraint]].\n * @return the defined [[JaCoPConstraint]].\n */\n def #>(that: U): JaCoPConstraint = this.>(that)\n\n /** Defines \"greater than\" [[JaCoPConstraint]] between [[Rand]] and BigInt constant.\n *\n * @param that a second parameter for \"greater than or equal\" [[JaCoPConstraint]].\n * @return the equation [[JaCoPConstraint]].\n */\n def #>(that: BigInt): JaCoPConstraint = this.>(that)\n\n /** Defines \"greater than or equal\" [[JaCoPConstraint]] between two [[Rand]].\n *\n * @param that a second parameter for \"greater than or equal\" [[JaCoPConstraint]].\n * @return the defined [[JaCoPConstraint]].\n */\n def #>=(that: U): JaCoPConstraint = this.>=(that)\n\n /** Defines \"greater than or equal\" [[JaCoPConstraint]] between [[Rand]] and BigInt constant.\n *\n * @param that a second parameter for \"greater than or equal\" [[JaCoPConstraint]].\n * @return the equation [[JaCoPConstraint]].\n */\n def #>=(that: BigInt): JaCoPConstraint = this.>=(that)\n\n /** Defines [[JaCoPConstraint]] on inclusion of a [[Rand]] variable value in a set.\n *\n * @param that set that this variable's value must be included.\n * @return the equation [[JaCoPConstraint]].\n */\n def in(that: SetVar): JaCoPConstraint = {\n if (min == max) {\n val c = new EinA(min, that)\n val crvc = new JaCoPConstraint(c)\n model.crvconstr += crvc\n crvc\n } else {\n val c = new XinA(this, that)\n val crvc = new JaCoPConstraint(c)\n model.crvconstr += crvc\n crvc\n }\n }\n\n /** Defines [[JaCoPConstraint]] on inclusion of a [[Rand]] variable value in a set.\n *\n * @param that set that this variable's value must be included.\n * @return the equation [[JaCoPConstraint]].\n */\n def inside(that: SetVar): JaCoPConstraint = {\n this.in(that)\n }\n\n /**\n * Create a distribution constraint for the current value\n * @param groups the [[WeightedRange]] or [[WeightedValue]] to assign to the current variable\n * @return the [[DistConstraint]]\n */\n def dist(groups: Weight*): DistConstraint = {\n val c = new DistConstraint(this, groups.toList)\n model.distConst += c\n c\n }\n }\n\n private[crv] class Randc(min: Int, max: Int)(implicit model: Model)\n extends Rand(randName(10 ,model.seed), min, max) with chiselverify.crv.Randc {\n model.randcVars += this\n\n private val rand = new Random(model.seed)\n private var currentValue: Int = (math.abs(rand.nextInt()) % (max - min)) + min\n\n /** Returns the current value of the variable\n * @return return the current value of the variable\n */\n override def value(): Int = currentValue.toInt\n\n /** Gets the next value of the random variable\n * @return return the next value of the variable\n */\n override def next(): Int = {\n currentValue = if (currentValue == max) min else currentValue + 1\n currentValue\n }\n\n /** Set the value of the variable\n * @param that the value to be set\n */\n override def setVar(that: Int): Unit = currentValue = that\n }\n\n abstract class RandType\n case object Normal extends RandType\n case object Cyclic extends RandType\n\n /**\n * Allows for the declaration of either type of RandomVar.\n * @param min the minimum value that the random variable can take.\n * @param max the maximum value that the random variable can take.\n * @param randType Either Normal or Cyclic, the type of the random variable.\n * @param model the model used to store the random data.\n * @return a random variable of the correct type\n */\n def rand(min: Int, max: Int, randType: RandType = Normal)(implicit model: Model) : Rand = randType match {\n case Normal =>\n val rand = new Random(model.seed)\n val randLength = (rand.nextInt() % 30) + 10\n new Rand(randName(randLength, model.seed), min, max)\n\n case Cyclic => new Randc(min, max)\n }\n}\n", "groundtruth": " def #^(that: U): U = this.^(that)\n", "crossfile_context": ""}
{"task_id": "chiselverify", "path": "chiselverify/src/main/scala/examples/heappriorityqueue/Interfaces.scala", "left_context": "package examples.heappriorityqueue\n\nimport chisel3._\nimport chisel3.util._\n\n/**\n * contains relevant bundle types and port types for the heap-based priority queue\n */\nobject Interfaces {\n\n class Event(implicit parameters: PriorityQueueParameters) extends Bundle {\n import parameters._\n val cycle = UInt(cycleWidth.W)\n val superCycle = UInt(superCycleWidth.W)\n\n def <(that: Event): Bool = superCycle < that.superCycle || (superCycle === that.superCycle && cycle < that.cycle)\n", "right_context": " def ===(that: Event): Bool = superCycle === that.superCycle && cycle === that.cycle\n }\n\n class TaggedEvent(implicit parameters: PriorityQueueParameters) extends Bundle {\n import parameters._\n val event = new Event\n val id = UInt(referenceIdWidth.W)\n }\n\n class rdPort[T <: Data](addrWid: Int, dType: T) extends Bundle { // as seen from reader side\n val address = Output(UInt(addrWid.W))\n val data = Input(dType)\n }\n\n class wrPort[T <: Data](addrWid: Int, maskWid: Int, dType: T) extends Bundle { // as seen from writer side\n val address = Output(UInt(addrWid.W))\n val mask = Output(UInt(maskWid.W))\n val data = Output(dType)\n val write = Output(Bool())\n }\n\n class searchPort(implicit parameters: PriorityQueueParameters) extends Bundle { // as seen from requester side\n import parameters._\n val refID = Output(UInt(referenceIdWidth.W))\n val heapSize = Output(UInt(log2Ceil(size + 1).W))\n val res = Input(UInt(log2Ceil(size).W))\n val search = Output(Bool())\n val error = Input(Bool())\n val done = Input(Bool())\n }\n}\n", "groundtruth": " def >(that: Event): Bool = superCycle > that.superCycle || (superCycle === that.superCycle) && cycle > that.cycle\n", "crossfile_context": ""}
{"task_id": "chiselverify", "path": "chiselverify/src/main/scala/examples/heappriorityqueue/PriorityQueue.scala", "left_context": "package examples.heappriorityqueue\n\nimport chisel3._\nimport chisel3.util._\n\nimport examples.heappriorityqueue.Interfaces._\nimport examples.heappriorityqueue.modules.{QueueControl, linearSearchMem}\n\n", "right_context": "\n/**\n * Component implementing a priority queue, where the minimum value gets to the head of the queue\n * - The sorting is based on heap sort\n * - inserted priorities are made up of 3 fields:\n * - cyclic priority which is most important\n * - normal priority which decides in the case of equal cyclic priorities\n * - a user generated reference ID given at insertion which is used to remove elements from the queue\n * - the component needs to be provided with the following:\n * - a synchronous memory of appropriate size\n * - the memory has to be initialized to all 1s\n * - thus the reference ID with all 1s is reserved for empty cells\n * - a component which is able to search through the reference ID fields and return the index where a given reference ID is present\n * - the queue waits until the search result is given\n * - the head element is kept locally in a FF for symmetry and access speed reasons\n * - the head element is furthermore presented at a dedicated port\n *\n * @param size the maximum size of the heap\n * @param order the number of children per node in the tree. Must be power of 2\n * @param nWid width of the normal priority value\n * @param cWid width of the cyclic priority value\n * @param rWid width of the reference ID tags\n */\nclass PriorityQueue(size: Int, order: Int, superCycleRes: Int, cyclesPerSuperCycle: Int, exposeState: Boolean = false) extends Module {\n require(isPow2(order), \"The number of children per node needs to be a power of 2!\")\n\n val superCycleWidth = superCycleRes\n val cycleWidth = log2Ceil(cyclesPerSuperCycle)\n val referenceIdWidth = log2Ceil(size+1)\n implicit val parameters = PriorityQueueParameters(size, order, superCycleWidth, cycleWidth, referenceIdWidth)\n\n val io = IO(new Bundle {\n // Interface for signaling head element to user.\n // I.e. the element with the lowest priority\n val head = new Bundle {\n val valid = Output(Bool())\n val none = Output(Bool())\n val prio = Output(new Event)\n val refID = Output(UInt(referenceIdWidth.W))\n }\n\n // Interface for element insertion/removal\n // Timing:\n // User must maintain input asserted until done is asserted.\n // User must deassert input when done is asserted (unless a new cmd is made).\n // User must ensure that reference ID tags are unique.\n val cmd = new Bundle {\n // inputs\n val valid = Input(Bool())\n val op = Input(Bool()) // 0=Remove, 1=Insert\n val prio = Input(new Event)\n val refID = Input(UInt(referenceIdWidth.W))\n // outputs\n val done = Output(Bool())\n val result = Output(Bool()) // 0=Success, 1=Failure\n val rm_prio = Output(new Event)\n }\n\n val state = if (exposeState) Some(Output(UInt())) else None\n })\n\n val mem = Module(new linearSearchMem(size - 1))\n val queue = Module(new QueueControl)\n\n mem.srch <> queue.io.srch\n mem.rd <> queue.io.rdPort\n mem.wr <> queue.io.wrPort\n io.head <> queue.io.head\n io.cmd <> queue.io.cmd\n\n io.cmd.done := mem.srch.done && queue.io.cmd.done\n\n if (exposeState) io.state.get := queue.io.state\n}\n", "groundtruth": "case class PriorityQueueParameters(size: Int, order: Int, superCycleWidth: Int, cycleWidth: Int, referenceIdWidth: Int)\n", "crossfile_context": ""}
{"task_id": "chiselverify", "path": "chiselverify/src/test/scala/examples/heappriorityqueue/MinFinderTest.scala", "left_context": "package examples.heappriorityqueue\n\nimport chiseltest._\nimport org.scalatest.freespec.AnyFreeSpec\nimport org.scalatest.matchers.should.Matchers\n\nimport examples.heappriorityqueue.Helpers._\nimport examples.heappriorityqueue.modules.MinFinder\n\n/**\n * contains a randomized test for the MinFinder module\n */\nclass MinFinderTest extends AnyFreeSpec with ChiselScalatestTester with Matchers {\n def calculateOut(values: Seq[Seq[Int]]): Int = {\n val cyclic = values.map(_.head)\n val cyclicMins = cyclic.zipWithIndex.filter(_._1 == cyclic.min).map(_._2)\n if (cyclicMins.length == 1) {\n cyclicMins.head\n } else {\n val normals = values.map(_ (1))\n", "right_context": " candidates.indexOf(candidates.min)\n }\n }\n\n val n = 8\n implicit val parameters = PriorityQueueParameters(32, 4, 4, 8, 5)\n\n \"MinFinder should identify minimum value with the lowest index\" in {\n test(new MinFinder(n)) { dut =>\n import parameters._\n setWidths(superCycleWidth, cycleWidth, referenceIdWidth)\n\n for (_ <- 0 until 1000) {\n val values = pokePrioAndIDVec(dut.io.values)\n dut.io.index.peek().litValue should equal (calculateOut(values))\n peekPrioAndId(dut.io.res) should equal (values(calculateOut(values)))\n }\n }\n }\n}\n", "groundtruth": " val candidates = Seq.tabulate(values.length)(i => if (cyclicMins.contains(i)) normals(i) else Int.MaxValue)\n", "crossfile_context": ""}
{"task_id": "chiselverify", "path": "chiselverify/src/test/scala/examples/leros/AluVerification.scala", "left_context": "package examples.leros\n\nimport chisel3._\nimport chisel3.experimental.BundleLiterals.AddBundleLiteralConstructor\nimport chiseltest._\nimport chiseltest.ChiselScalatestTester\nimport org.scalatest.BeforeAndAfterAll\nimport org.scalatest.flatspec.AnyFlatSpec\nimport scala.math.pow\n\nimport chiselverify.coverage.{cover => ccover, _}\nimport chiselverify.coverage.CoverReport._\nimport chiselverify.crv.{RangeBinder, ValueBinder}\nimport chiselverify.crv.backends.jacop._\n\ncase class AluAccumulator(value: BigInt)\n\nclass AluTransaction(seed: Int, size: Int) extends RandObj {\n currentModel = new Model(seed)\n val max = pow(2, size).toInt\n\n val op: RandVar = rand(0, 7)\n val din: RandVar = rand(0, max)\n val ena: RandVar = rand(0, 1)\n\n val values: DistConstraint = din dist (\n 0 to 0xF := 1,\n 0xF to 0xFF := 1,\n 0xFF to 0xFFF := 1,\n 0xFFF to 0xFFFF := 1,\n )\n\n val onlyHigh: DistConstraint = din dist (\n 0xFF to 0xFFF := 1,\n 0xFFF to 0xFFFF := 10,\n )\n\n val enaHigh: DistConstraint = ena dist (\n 1 := 99,\n 0 := 1\n )\n\n onlyHigh.disable()\n\n def toBundle: AluAccuInput = {\n new AluAccuInput(size).Lit(_.op -> op.value().U, _.din -> din.value().U, _.ena -> ena.value().B)\n }\n}\n\nobject AluGoldenModel {\n\n def genNextState(transaction: AluAccuInput, accu: AluAccumulator): AluAccumulator = {\n val mask: Int = (1 << transaction.din.getWidth) - 1\n if (transaction.ena.litToBoolean) {\n transaction.op.litValue.toInt match {\n case 0 => accu\n case 1 => if ((accu.value + transaction.din.litValue) > mask) {\n AluAccumulator((accu.value + transaction.din.litValue) & mask)\n } else {\n AluAccumulator(accu.value + transaction.din.litValue)\n }\n case 2 => if ((accu.value - transaction.din.litValue) < 0) {\n AluAccumulator((accu.value - transaction.din.litValue) & mask)\n } else {\n AluAccumulator(accu.value - transaction.din.litValue)\n }\n case 3 => AluAccumulator(accu.value & transaction.din.litValue)\n case 4 => AluAccumulator(accu.value | transaction.din.litValue)\n case 5 => AluAccumulator(accu.value ^ transaction.din.litValue)\n case 6 => AluAccumulator(transaction.din.litValue)\n case 7 => AluAccumulator(accu.value.toInt >>> 1)\n }\n } else {\n accu\n }\n }\n\n def genOutputStates(listT: List[AluAccuInput], accu: AluAccumulator): List[AluAccumulator] = {\n listT match {\n case Nil => Nil\n case x :: xs =>\n val nexAccu = genNextState(x, accu)\n nexAccu :: genOutputStates(xs, nexAccu)\n }\n }\n\n def serializeAccu(accu: AluAccumulator, size: Int): AluAccuOutput =\n new AluAccuOutput(size).Lit(_.accu -> accu.value.U)\n\n def generateAluAccuTransactions(listT: List[AluAccuInput], accu: AluAccumulator): List[AluAccuOutput] =\n genOutputStates(listT, accu).map(serializeAccu(_, listT.head.din.getWidth))\n\n def compareSingle(transaction: (AluAccuOutput, AluAccuOutput)): Boolean = {\n val (dutT, genT) = transaction\n equals(dutT.accu.litValue == genT.accu.litValue)\n dutT.accu.litValue == genT.accu.litValue\n }\n\n def compare(transactions: List[(AluAccuOutput, AluAccuOutput)]): List[Boolean] = transactions.map(compareSingle(_))\n}\n\ntrait AluBehavior {\n this: AnyFlatSpec with ChiselScalatestTester =>\n val coverageCollector = new CoverageCollector\n\n def compute(name: String, size: Int, inputT: List[AluAccuInput]): Unit = {\n it should s\"test alu with $name\" in {\n test(new AluAccuMultiChisel(size)) { dut =>\n val cr = new CoverageReporter(dut)\n cr.register(\n ccover(\"op\", dut.input.op)(\n bin(\"nop\", 0 to 0),\n bin(\"add\", 1 to 1),\n bin(\"sub\", 2 to 2),\n bin(\"and\", 3 to 3),\n bin(\"or\", 4 to 4),\n bin(\"xor\", 5 to 5),\n bin(\"ld\", 6 to 6),\n bin(\"shr\", 7 to 7)),\n ccover(\"din\", dut.input.din)(\n bin(\"0xF\", 0 to 0xF),\n bin(\"0xFF\", 0xF to 0xFF),\n bin(\"0xFFF\", 0xFF to 0xFFF),\n bin(\"0xFFFF\", 0xFFF to 0xFFFF),\n ),\n ccover(\"accu\", dut.output.accu)(\n bin(\"0xF\", 0 to 0xF),\n bin(\"0xFF\", 0xF to 0xFF),\n bin(\"0xFFF\", 0xFF to 0xFFF),\n bin(\"0xFFFF\", 0xFFF to 0xFFFF),\n ),\n ccover(\"ena\", dut.input.ena)(\n bin(\"disabled\", 0 to 0),\n bin(\"enabled\", 1 to 1)\n ),\n ccover(\"operations cross enable\", dut.input.op, dut.input.ena)(\n cross(\"operation enable\", Seq(0 to 7, 1 to 1)),\n cross(\"operation disabled\", Seq(0 to 7, 0 to 0))\n )\n )\n\n val computedTransactions: List[AluAccuOutput] = inputT.map { trx =>\n dut.input.poke(trx)\n dut.clock.step()\n cr.sample()\n dut.output.peek()\n }\n\n val goldenTransactions = AluGoldenModel.generateAluAccuTransactions(inputT, AluAccumulator(0))\n AluGoldenModel.compare(computedTransactions zip goldenTransactions)\n coverageCollector.collect(cr.report)\n }\n }\n }\n}\n\nclass AluVerification extends AnyFlatSpec with AluBehavior with ChiselScalatestTester with BeforeAndAfterAll {\n behavior of \"AluAccumulator\"\n val size = 16\n val IsUnitTest = true // set to false to generate a lot more transactions\n", "right_context": " val seeds = if(IsUnitTest) { List(30, 104) } else {\n List(30, 104, 60, 90, 200, 50, 22, 2000, 40, 900, 70, 23)\n }\n\n println(s\"Testing ALU with ${tnumber * seeds.size * 2} random transactions\")\n // General test\n seeds.foreach { seed =>\n val length = tnumber\n val masterT = new AluTransaction(seed, size)\n val transactions: Seq[AluAccuInput] = (0 to length) map { _ =>\n masterT.randomize\n masterT.toBundle\n }\n it should behave like compute(s\"seed = $seed, and normal values\", size, transactions.toList)\n }\n\n // Only transactions with values between 0xFF to 0xFFFF\n seeds.foreach { seed =>\n val length = tnumber\n val masterT = new AluTransaction(seed, size)\n val onlyHighTransactions: Seq[AluAccuInput] = (0 to length) map { _ =>\n masterT.onlyHigh.enable()\n masterT.values.disable()\n masterT.randomize\n masterT.toBundle\n }\n it should behave like compute(s\"seed = $seed, and high values\", size, onlyHighTransactions.toList)\n }\n}\n", "groundtruth": " val tnumber = if(IsUnitTest) { 10 } else { 5000 }\n", "crossfile_context": ""}
{"task_id": "ofdm", "path": "ofdm/rocket/src/test/scala/ofdm/AXI4StreamTimeAdapterSpec.scala", "left_context": "package ofdm\n\nimport chisel3._\nimport chisel3.iotesters.PeekPokeTester\nimport freechips.rocketchip.amba.axi4stream._\nimport freechips.rocketchip.config.Parameters\nimport freechips.rocketchip.diplomacy._\nimport org.scalatest.{FlatSpec, Matchers}\n\nclass AXI4StreamTimeAdapaterTestModule extends Module {\n\n implicit val p = Parameters.empty\n val lm = LazyModule(new LazyModule {\n val fuzzerADC = AXI4StreamFuzzer(AXI4StreamTransaction.linearSeq(100))\n val fuzzerDAC = AXI4StreamFuzzer(Seq.tabulate(100)(x => AXI4StreamTransaction(data = 100 + x, user = 100 + x)), u = 64)\n val (adc, dac) = AXI4StreamTimeAdapter()\n val adcOut = AXI4StreamSlaveNode(AXI4StreamSlaveParameters())\n val dacOut = AXI4StreamSlaveNode(AXI4StreamSlaveParameters())\n\n adcOut := adc := fuzzerADC\n dacOut := dac := fuzzerDAC\n\n lazy val module = new LazyModuleImp(this) {\n val (a, aOutEdge) = adcOut.in.head\n val (d, dOutEdge) = dacOut.in.head\n val aOut = IO(AXI4StreamBundle(aOutEdge.bundle))\n val dOut = IO(AXI4StreamBundle(dOutEdge.bundle))\n aOut <> a\n dOut <> d\n }\n })\n val m = Module(lm.module)\n\n val io = IO(new Bundle {\n val adc = AXI4StreamBundle(m.aOutEdge.bundle)\n val dac = AXI4StreamBundle(m.dOutEdge.bundle)\n })\n\n io.adc <> m.aOut\n io.dac <> m.dOut\n}\n\nclass AXI4StreamTimeAdapterTester(c: AXI4StreamTimeAdapaterTestModule)\n extends PeekPokeTester(c)\n with AXI4StreamSlaveModel {\n\n bindSlave(c.io.adc).addExpects(Seq.tabulate(100)(d => AXI4StreamTransactionExpect(data = Some(d))))\n bindSlave(c.io.dac).addExpects(Seq.tabulate(100)(x => AXI4StreamTransactionExpect(data = Some(100 + x))))\n\n stepToCompletion()\n}\n\nclass AXI4StreamTimeAppenderSpec extends FlatSpec with Matchers {\n behavior of \"AXI4StreamTimeAppender\"\n\n it should \"work with no DAC\" in {\n", "right_context": " }\n\n it should \"work with multiple inputs to the DAC\" ignore {\n\n }\n\n it should \"work with multiple ADC inputs/outputs\" ignore {\n\n }\n}\n", "groundtruth": " chisel3.iotesters.Driver(() => new AXI4StreamTimeAdapaterTestModule) { new AXI4StreamTimeAdapterTester(_) } should be (true)\n", "crossfile_context": ""}
{"task_id": "ofdm", "path": "ofdm/rocket/src/test/scala/ofdm/SyncBlockSpec.scala", "left_context": "package ofdm\n\nimport freechips.rocketchip.amba.axi4.AXI4MasterModel\nimport breeze.math.Complex\nimport chisel3._\nimport chisel3.experimental._\nimport chisel3.iotesters.PeekPokeTester\nimport dsptools.numbers._\nimport freechips.rocketchip.amba.axi4._\nimport freechips.rocketchip.amba.axi4stream.{AXI4StreamFuzzer, AXI4StreamTransaction}\nimport freechips.rocketchip.config.Parameters\nimport freechips.rocketchip.diplomacy.{LazyModule, LazyModuleImp, ValName}\nimport freechips.rocketchip.interrupts.{IntSinkNode, IntSinkPortSimple}\nimport ieee80211.IEEE80211\nimport org.scalatest.{FlatSpec, Matchers}\n\nclass AXI4SyncBlockTester[\n// T <: Data,\nM <: LazyModuleImp\n//MultiIOModule with SyncBlockImp[\n// T, AXI4MasterPortParameters, AXI4SlavePortParameters, AXI4EdgeParameters, AXI4EdgeParameters, AXI4Bundle\n// ]\n](c: M)\n extends PeekPokeTester(c) with AXI4MasterModel {\n val outer = c.wrapper.asInstanceOf[SyncBlockTestModule[_]]\n override val memAXI: AXI4Bundle = outer.module.in\n val intbundles = outer.module.intout\n\n axiWriteWord(0, 64)\n axiWriteWord(8, 64)\n axiWriteWord(24, 160)\n axiWriteWord(32, 100)\n\n step(1000)\n}\n\nclass AXI4MasterPort(params: AXI4MasterPortParameters)(implicit p: Parameters) extends LazyModule {\n val node = AXI4MasterNode(Seq(params))\n\n lazy val module = new LazyModuleImp(this) {\n val (ins, inEdgeParams) = node.in.unzip\n val (outs, outEdgeParams) = node.out.unzip\n\n ins.zip(outs).foreach { case (i, o) => o <> i }\n }\n}\n\nobject AXI4MasterPort {\n def apply(params: AXI4MasterPortParameters =\n AXI4MasterPortParameters(Seq(AXI4MasterParameters(\"axi4master\"))))\n (implicit p: Parameters, valName: ValName): AXI4MasterNode = {\n LazyModule(new AXI4MasterPort(params)).node\n }\n}\n\nclass SyncBlockTestModule[T <: Data : Real]\n(\n proto: T,\n maxNumPeaks: Int = 32,\n autocorrParams: AutocorrParams[DspComplex[T]],\n transactions: Seq[AXI4StreamTransaction] = AXI4StreamTransaction.linearSeq(100)\n)(implicit p: Parameters) extends LazyModule {\n val sync = LazyModule(new AXI4SyncBlock(proto, maxNumPeaks = maxNumPeaks, autocorrParams = autocorrParams))\n val memMaster = AXI4MasterNode(Seq(AXI4MasterPortParameters(Seq(AXI4MasterParameters(\"axi4master\")))))\n sync.mem.get := memMaster\n val fuzzer = AXI4StreamFuzzer(transactions = transactions, u = 64)\n sync.streamNode := fuzzer\n val intnode = IntSinkNode(IntSinkPortSimple(ports = 1, sinks = 1))\n intnode := sync.intnode\n\n lazy val module = new LazyModuleImp(this) {\n val in = IO(Flipped(AXI4Bundle(memMaster.out.head._1.params)))\n memMaster.out.head._1 <> in\n\n val intout = IO(Output(Vec(intnode.in.length, Bool())))\n intout := intnode.in.head._1\n\n // val ints = IO(Vec(sync.intnode.in.length, Bool()))\n // ints.zip(sync.intnode.in.map(_._1)).map(_ <> _)\n }\n}\n\ntrait TestSyncBlock[T <: Data] extends AXI4SyncBlock[T] {\n def trans: Seq[AXI4StreamTransaction]\n}\n\nclass SyncBlockSpec extends FlatSpec with Matchers {\n behavior of \"Sync Block\"\n\n implicit val p = Parameters.empty\n def axiDut[T <: Data : Real]\n (\n proto: T,\n maxNumPeaks: Int = 512,\n autocorrParams: AutocorrParams[DspComplex[T]],\n transactions: Seq[AXI4StreamTransaction] = AXI4StreamTransaction.linearSeq(100)\n )(implicit valName: ValName) = {\n LazyModule(new SyncBlockTestModule(\n proto, maxNumPeaks = maxNumPeaks, autocorrParams = autocorrParams, transactions = transactions\n )).module\n }\n\n it should \"detect packets\" in {\n val proto = FixedPoint(32.W, 14.BP)\n\n", "right_context": " def complexToBigInt(c: Complex): BigInt = {\n val real = FixedPoint.toBigInt(c.real, binaryPoint = proto.binaryPoint.get - 2)\n val imag = FixedPoint.toBigInt(c.imag, binaryPoint = proto.binaryPoint.get - 2)\n (unsignedBigInt(real) << proto.getWidth) + unsignedBigInt(imag)\n }\n\n chisel3.iotesters.Driver.execute( Array(\"-fiwv\", \"-tbn\", \"verilator\"),\n () => axiDut\n (\n proto,\n autocorrParams = AutocorrParams(DspComplex(proto),\n 512,\n 512),\n transactions = (IEEE80211.stf ++ Seq.fill(500)(Complex(0, 0)) ++ IEEE80211.stf ++ Seq.fill(500)(Complex(0, 0))).zipWithIndex.map { case (c, i) =>\n AXI4StreamTransaction(data = complexToBigInt(c), user = i)\n }\n )\n ) {\n c => new AXI4SyncBlockTester(c)\n } should be (true)\n }\n\n}\n", "groundtruth": " def unsignedBigInt(i: BigInt): BigInt = if (i < 0) {\n (BigInt(2) << proto.getWidth) + i\n } else {\n", "crossfile_context": ""}
{"task_id": "ofdm", "path": "ofdm/src/main/scala/ldpc/Encoder.scala", "left_context": "package ldpc\n\nimport chisel3._\nimport chisel3.util.Decoupled\nimport ofdm.TreeReduce\n\nobject SWEncoder {\n def apply(word: Seq[Boolean], params: LdpcParams): Seq[Boolean] = {\n require(word.length == params.generator.length)\n val selectedRows: Seq[Seq[Boolean]] = word.zip(params.generator).map({ case (w: Boolean, g: Seq[Boolean]) =>\n", "right_context": " selectedRows.foldLeft[Seq[Boolean]](Seq.fill(selectedRows.head.length)(false)) { case (prod, row) =>\n prod.zip(row).map({ case (l, r) => l ^ r})\n }\n }\n}\n\nclass Encoder(params: LdpcParams) extends MultiIOModule {\n val in = IO(Flipped(Decoupled(Vec(params.k, Bool()))))\n val out = IO(Decoupled(Vec(params.n, Bool())))\n\n val selectedRows = in.bits.zip(params.generator.toSeq).map({ case (i: Bool, p: Seq[Boolean]) =>\n p.map(pp => if (pp) Some(i) else None)\n })\n\n def rowSum(top: Seq[Option[Bool]], bottom: Seq[Option[Bool]]): Seq[Option[Bool]] = {\n top.zip(bottom).map({\n case (Some(t), Some(b)) => Some(t ^ b)\n case (Some(t), None) => Some(t)\n case (None, Some(b)) => Some(b)\n case _ => None\n })\n }\n\n out.bits := VecInit(TreeReduce(selectedRows, rowSum).flatten)\n\n out.valid := in.valid\n in.ready := out.ready\n}\n", "groundtruth": " if (w) g else Seq.fill(g.length)(false) })\n", "crossfile_context": ""}
{"task_id": "ofdm", "path": "ofdm/src/main/scala/ofdm/AdjustableShiftRegister.scala", "left_context": "package ofdm\n\nimport chisel3._\nimport chisel3.internal.requireIsHardware\n\nobject AdjustableShiftRegister {\n def apply[T <: Data](in: T, maxDepth: Int, depth: UInt, resetData: T, en: Bool = true.B): T = {\n require(maxDepth > 0)\n requireIsHardware(in)\n assert(depth <= maxDepth.U)\n\n val adjustableShiftRegister = Module(new chisel3.util.Queue(chiselTypeOf(in), entries = maxDepth, pipe = true, flow = true))\n\n adjustableShiftRegister.io.enq.bits := in\n adjustableShiftRegister.io.enq.valid := adjustableShiftRegister.io.count < depth && en\n", "right_context": "", "groundtruth": " adjustableShiftRegister.io.deq.ready := adjustableShiftRegister.io.count >= depth && en\n\n Mux(adjustableShiftRegister.io.deq.fire(), adjustableShiftRegister.io.deq.bits, resetData)\n", "crossfile_context": ""}
{"task_id": "ofdm", "path": "ofdm/src/main/scala/ofdm/CPRemover.scala", "left_context": "package ofdm\n\nimport chisel3._\nimport chisel3.internal.requireIsChiselType\nimport chisel3.util.{Decoupled, log2Ceil}\n\nclass CPRemover[T <: Data](proto: T, cpSize: Int, nFFT: Int) extends MultiIOModule {\n requireIsChiselType(proto)\n\n val in = IO(Flipped(Decoupled(proto)))\n val out = IO(Decoupled(proto))\n val tlastIn = IO(Input(Bool()))\n val tlastOut = IO(Output(Bool()))\n\n val maxCnt = cpSize + nFFT\n\n val cnt = RegInit(0.U(log2Ceil(maxCnt + 1).W))\n\n when (in.fire()) {\n when (cnt === (maxCnt - 1).U || tlastIn) {\n cnt := 0.U\n } .otherwise {\n", "right_context": " out.valid := in.valid && cnt >= cpSize.U // only pass input to output when counter is past the cyclic prefix\n in.ready := out.ready || cnt < cpSize.U // accept input if output is ready, or if it is the cyclic prefix (ok to discard)\n\n tlastOut := tlastIn || (cnt === (maxCnt - 1).U)\n}\n", "groundtruth": " cnt := cnt +% 1.U\n }\n }\n", "crossfile_context": ""}
{"task_id": "ofdm", "path": "ofdm/src/main/scala/ofdm/Demod.scala", "left_context": "package ofdm\n\nimport chisel3._\nimport chisel3.experimental.chiselName\nimport chisel3.util.Decoupled\nimport dsptools.numbers._\n\nclass QPSKDemodUnit[T <: Data : Real](protoIn: DspComplex[T], protoOut: T) extends MultiIOModule {\n val in = IO(Input(protoIn))\n val out = IO(Output(Vec(2, protoOut)))\n\n", "right_context": " out(1) := in.real\n}\n\nclass QPSKDemod[T <: Data : Real](params: RXParams[T]) extends MultiIOModule {\n val in = IO(Flipped(Decoupled(Vec(params.nDataSubcarriers, params.protoChannelEst))))\n val out = IO(Decoupled(Vec(params.nDataSubcarriers, Vec(2, params.protoLLR))))\n\n in.bits.zip(out.bits).foreach { case (i, o) =>\n val demod = Module(new QPSKDemodUnit(params.protoChannelEst, params.protoLLR))\n demod.in := i\n o := demod.out\n }\n out.valid := in.valid\n in.ready := out.ready\n}\n", "groundtruth": " out(0) := in.imag\n", "crossfile_context": ""}
{"task_id": "ofdm", "path": "ofdm/src/main/scala/ofdm/FFT.scala", "left_context": "package ofdm\n\nimport chisel3._\nimport chisel3.util._\nimport breeze.math.Complex\nimport chisel3.experimental.{ChiselEnum, chiselName}\nimport chisel3.internal.requireIsChiselType\nimport dsptools.{DspContext, DspTester}\nimport dsptools.numbers._\n\nobject BitRev {\n def apply(x: BigInt, nBits: Int): BigInt = {\n val trailingBits = x.toString(2)\n assert(trailingBits.length <= nBits)\n val allBits = \"0\" * (nBits - trailingBits.length) + trailingBits\n BigInt(allBits.reverse, 2)\n }\n}\n\nclass FixedButterflyIO[T <: Data : Ring](genIn: T, genOut: T, n: Int) extends Bundle {\n val in = Input (Vec(n, DspComplex(genIn, genIn)))\n val out = Output(Vec(n, DspComplex(genOut, genOut)))\n}\n\nclass FixedButterfly[T <: Data : Ring : ConvertableTo](genIn: T, genOut: T, genTwiddle: T, twiddles: Map[Int, Seq[Complex]], n: Int) extends Module {\n val io = IO(new FixedButterflyIO(genIn, genOut, n))\n\n for (outIdx <- 0 until n) {\n require(twiddles.contains(outIdx), s\"Twiddles don't contain $outIdx\")\n val out = io.out(outIdx)\n val t = twiddles(outIdx)\n require(t.length == n, s\"Twiddles should be length $n, got ${t.length}\")\n\n val terms = io.in.zip(t) map { case (input, twiddle) =>\n twiddle match {\n case Complex(0, 0) => None\n case Complex(1, 0) => Some(input)\n case Complex(-1, 0) => Some(-input)\n case Complex(0, 1) => Some(input.mulj())\n case Complex(0, -1) => Some(-input.mulj())\n case Complex(r, i) =>\n val real = ConvertableTo[T].fromDouble(r, genTwiddle)\n val imag = ConvertableTo[T].fromDouble(i, genTwiddle)\n Some(input * DspComplex(real, imag))\n }\n } collect { case Some(x) => x }\n\n require(terms.nonEmpty, s\"Output $outIdx has no twiddles!\")\n\n out := TreeReduce(terms, (x: DspComplex[T], y: DspComplex[T]) => x + y)\n }\n}\n\nclass Butterfly2[T <: Data : Ring](genIn: T, genOut: Option[T] = None) extends MultiIOModule {\n val in0 = IO(Input (genIn.cloneType))\n val in1 = IO(Input (genIn.cloneType))\n\n val sum = in0 + in1\n val diff = in0 - in1\n\n val out0 = IO(Output(genOut.getOrElse(sum).cloneType))\n val out1 = IO(Output(genOut.getOrElse(diff).cloneType))\n\n out0 := sum\n out1 := diff\n}\n\nclass StreamingFFTIO[T <: Data : Ring](genIn: T, genOut: T) extends Bundle {\n val in = Input (Valid(DspComplex(genIn, genIn)))\n val last = Input(Bool())\n val out = Output(Valid(DspComplex(genOut, genOut)))\n}\n\ntrait HasStreamingFFTIO[T <: Data] {\n def io: StreamingFFTIO[T]\n}\n\nobject SimulateStreamingFFT {\n def apply[T <: Data, M <: Module with HasStreamingFFTIO[T]]\n (\n dut: () => M,\n in: Seq[Complex],\n expects: Option[Seq[Complex]] = None,\n tolerance: Int = 14\n ): Seq[Complex] = {\n var out: Seq[Complex] = Seq()\n var expectsMutable = expects.getOrElse(Seq())\n dsptools.Driver.execute( dut, Array[String](\"-tbn\", \"verilator\") ) { c => new DspTester(c) {\n def checkOutput(): Unit = {\n fixTolLSBs.withValue(tolerance) {\n if (peek(c.io.out.valid)) {\n out = out :+ peek(c.io.out.bits)\n if (expectsMutable.nonEmpty) {\n expect(c.io.out.bits, expectsMutable.head)\n expectsMutable = expectsMutable.tail\n }\n }\n }\n }\n poke(c.io.in.valid, 1)\n for (i <- in) {\n poke(c.io.in.bits, i)\n step(1)\n checkOutput()\n }\n for (_ <- in.indices) {\n step(1)\n checkOutput()\n }\n }}\n out\n }\n}\n\nclass R2SDF[T <: Data : Ring : ConvertableTo](val n: Int, val genIn: T, val genOut: T, val genTwiddle: Option[T] = None)\n extends Module with HasStreamingFFTIO[T] {\n\n require(isPow2(n), s\"Radix 2 FFT must be power of 2\")\n\n val io = IO(new StreamingFFTIO(genIn, genOut))\n\n val nStages = log2Ceil(n)\n", "right_context": "\n val en = io.in.valid\n\n val genTwiddleResolved = genTwiddle.getOrElse(genIn)\n\n io.out.bits := delays.foldLeft(io.in.bits) { case (in, delay) =>\n val bf = Module(new Butterfly2(in))\n\n val shifted = if (delay <= 1 || true) {\n ShiftRegister(bf.out0, delay, en = en)\n } else {\n val shr = Module(new ShiftRegisterMem(chiselTypeOf(in), delay))\n shr.io.in.valid := en\n shr.io.in.bits := bf.out0\n shr.io.depth.valid := reset\n shr.io.depth.bits := delay.U\n shr.io.out.bits\n }\n\n bf.in0 := shifted\n if (delay == 1) {\n bf.in1 := in.mulj()\n } else {\n bf.in1 := in\n }\n\n val twiddlesComplex = Seq.tabulate(delay) { i => RootsOfUnity(i * n / delay, n) }\n val twiddlesDspComplex = twiddlesComplex.map( c => DspComplex.wire(\n ConvertableTo[T].fromDoubleWithFixedWidth(c.real, genTwiddleResolved),\n ConvertableTo[T].fromDoubleWithFixedWidth(c.imag, genTwiddleResolved)\n ))\n\n val twiddles = VecInit(twiddlesDspComplex)\n val (twiddleCount, _) = Counter(en, delay * 2)\n\n val product = bf.out1 * twiddles(twiddleCount)\n val out = Wire(chiselTypeOf(product))\n\n when (twiddleCount < delay.U) {\n out := DspComplex.wire(Ring[T].zero, Ring[T].zero)\n } .otherwise {\n out := product\n }\n\n out\n }\n\n io.out.valid := ShiftRegister(io.in.valid, n, false.B, true.B)\n}\n\nclass BF2I[T <: Data : Ring](proto: T, val delay: Int) extends MultiIOModule {\n requireIsChiselType(proto)\n require(delay > 0)\n\n val en = IO(Input(Bool()))\n val sel = IO(Input(Bool()))\n val in = IO(Input(DspComplex(proto)))\n val out = IO(Output(DspComplex(proto)))\n\n val feedbackIn = Wire(Valid(DspComplex(proto)))\n val feedback = if (delay > 1) { //delay > 1) {\n ShiftRegisterMem(feedbackIn, delay).bits\n } else {\n ShiftRegister(feedbackIn.bits, delay, en = feedbackIn.valid)\n }\n\n feedbackIn.valid := en\n\n when (sel) {\n feedbackIn.bits := feedback - in\n } .otherwise {\n // passthrough, swap\n feedbackIn.bits := in\n }\n when (ShiftRegister(sel, DspContext.current.numAddPipes)) { //, resetData = false.B, en = true.B)) {\n out := feedback context_+ in\n }.otherwise {\n out := ShiftRegister(feedback, DspContext.current.numAddPipes)\n }\n}\n\nclass BF2II[T <: Data : Ring](proto: T, val delay: Int) extends MultiIOModule {\n requireIsChiselType(proto)\n require(delay > 0)\n\n val en = IO(Input(Bool()))\n val inMultByJ = IO(Input(Bool()))\n val sel = IO(Input(Bool()))\n val in = IO(Input(DspComplex(proto)))\n val out = IO(Output(DspComplex(proto)))\n\n val scaledIn = Wire(in.cloneType)\n scaledIn.real := in.imag\n scaledIn.imag := -in.real\n val inTwiddled = Mux(sel && inMultByJ, scaledIn, in)\n val feedbackIn = Wire(Valid(DspComplex(proto)))\n val feedback = if (delay > 1) { // (delay > 1) {\n ShiftRegisterMem(feedbackIn, delay).bits\n } else {\n ShiftRegister(feedbackIn.bits, delay, en = feedbackIn.valid)\n }\n\n feedbackIn.valid := en // ShiftRegister(en, DspContext.current.numAddPipes, resetData = false.B, en = true.B)\n when (sel) {\n feedbackIn.bits := feedback - inTwiddled\n } .otherwise {\n feedbackIn.bits := inTwiddled\n }\n when (ShiftRegister(sel, DspContext.current.numAddPipes)) { //, resetData = false.B, en = true.B)) {\n out := feedback context_+ inTwiddled\n }.otherwise {\n out := ShiftRegister(feedback, DspContext.current.numAddPipes)\n }\n}\n\nclass R22Stage[T <: Data : Ring](proto:T, val n: Int) extends MultiIOModule {\n requireIsChiselType(proto)\n require(n > 2)\n require(isPow2(n))\n\n val en = IO(Input(Bool()))\n val in = IO(Input(DspComplex(proto)))\n val ctrl = IO(Input(UInt(2.W)))\n val protoOut = chiselTypeOf(in.real context_+ in.real)\n val out = IO(Output(DspComplex(protoOut)))\n\n val stage1 = Module(new BF2I(proto, n / 2))\n val stage2 = Module(new BF2II(protoOut, n / 4))\n\n stage1.in := in\n stage1.en := en\n stage1.sel := ctrl(1)\n\n stage2.in := stage1.out\n stage2.en := ShiftRegister(en, DspContext.current.numAddPipes, resetData = false.B, en = true.B)\n stage2.sel := ShiftRegister(ctrl(0), DspContext.current.numAddPipes)\n stage2.inMultByJ := ShiftRegister(!ctrl(1) && ctrl(0), DspContext.current.numAddPipes)\n\n out := stage2.out\n}\n\nclass SDFInputManager[T <: Data](val n: Int, val proto: T) extends MultiIOModule {\n require(n > 0)\n requireIsChiselType(proto)\n\n val in = IO(Flipped(Decoupled(proto)))\n val in_last = IO(Input(Bool()))\n\n val out = IO(Decoupled(proto))\n val out_last = IO(Output(Bool()))\n\n val cnt = RegInit(0.U(log2Ceil(n).W))\n val last = RegInit(false.B)\n\n out <> in\n out_last := in_last && !last\n when (out.fire()) {\n cnt := cnt +% 1.U\n }\n\n when (in.fire() && in_last) {\n last := true.B\n }\n\n // this flushes the previous\n when (last) {\n out.bits := 0.U.asTypeOf(proto)\n out.valid := true.B\n in.ready := false.B\n when (out.fire() && cnt === (n - 1).U) {\n last := false.B\n }\n }\n}\n\nclass SDFOutputManager[T <: Data](val n: Int, val proto: T) extends MultiIOModule {\n require(n > 0)\n requireIsChiselType(proto)\n\n val in = IO(Flipped(Decoupled(proto)))\n val in_last = IO(Input(Bool()))\n\n val out = IO(Decoupled(proto))\n val out_last = IO(Output(Bool()))\n\n object State extends ChiselEnum {\n // sLast is not the \"last\" state in the state machine,\n // it is the state you go to when in_last is asserted\n val sLast, sDrop, sPass = Value\n }\n\n val state = RegInit(State.sDrop)\n val cnt = RegInit(n.U)\n var drop = WireInit(false.B)\n\n when (in.fire() && cnt > 0.U) {\n cnt := cnt -% 1.U\n }\n\n\n // unless we are dropping, pass through\n out <> in\n when (drop) {\n in.ready := true.B\n out.valid := false.B\n }\n out_last := false.B\n\n when (state === State.sLast) {\n when (in.fire() && cnt === 0.U) {\n cnt := n.U\n state := State.sDrop\n out_last := true.B\n }\n }.elsewhen (state === State.sDrop) {\n drop := true.B\n when (in.fire() && cnt === 0.U) {\n state := State.sPass\n }\n } .elsewhen (state === State.sPass) {\n // stay in here until you see in_last\n }\n\n when (in.valid && in_last) {\n drop := false.B\n state := State.sLast\n cnt := n.U\n }\n}\n\n@chiselName\nclass R22SDF[T <: Data : Ring : ConvertableTo](val n: Int, val protoIn: T, val protoOut: T, val protoTwiddle: T)\nextends MultiIOModule {\n requireIsChiselType(protoIn)\n requireIsChiselType(protoOut)\n requireIsChiselType(protoTwiddle)\n require(n > 2)\n require(isPow2(n))\n val logn = log2Ceil(n)\n require(logn % 2 == 0, \"n must be a power of 4\")\n\n val in = IO(Flipped(Decoupled(DspComplex(protoIn, protoIn))))\n val in_last = IO(Input(Bool()))\n val out = IO(Decoupled(DspComplex(protoOut, protoOut)))\n val out_last = IO(Output(Bool()))\n\n val inputManager = Module(new SDFInputManager(n - 1, DspComplex(protoIn, protoIn)))\n inputManager.in <> in\n inputManager.in_last := in_last\n val outputManager = Module(new SDFOutputManager(n - 1, DspComplex(protoOut, protoOut)))\n out <> outputManager.out\n out_last := outputManager.out_last\n\n val cnt = RegInit(0.U(logn.W))\n\n when (inputManager.out.fire()) {\n cnt := cnt +% 1.U\n }\n\n val complexMulLatency = DspContext.current.complexMulPipe\n\n // input, en, last, ctrl, proto\n type StageInfo = (DspComplex[T], Bool, Bool, UInt, T)\n def makeStage(stageInfo: StageInfo, logStage: Int): StageInfo = {\n val (input, en, last, ctrl, proto) = stageInfo\n val stageN = 1 << (logn - logStage)\n val lastStage = stageN == 4\n val outputLatency = 2 * DspContext.current.numAddPipes + (if (lastStage) 0 else complexMulLatency)\n\n val stage = Module(new R22Stage(proto, stageN))\n stage.in := input\n stage.en := en\n stage.ctrl := ctrl.head(2)\n println(s\"stage $stageN\")\n\n val lastOut = if (!lastStage) {\n val twiddleIdxs =\n Seq.fill(stageN / 4)(0) ++\n Seq.tabulate(stageN / 4)(i => i * 2) ++\n Seq.tabulate(stageN / 4)(i => i) ++\n Seq.tabulate(stageN / 4)(i => i * 3) // ++\n val uniqueTwiddleIdxs = twiddleIdxs.distinct.sorted\n val uniqueTwiddleTable = VecInit(uniqueTwiddleIdxs.map(t =>\n DspComplex.wire(\n real = ConvertableTo[T].fromDoubleWithFixedWidth( math.cos(2 * math.Pi * t / stageN), protoTwiddle),\n imag = ConvertableTo[T].fromDoubleWithFixedWidth(-math.sin(2 * math.Pi * t / stageN), protoTwiddle)\n )))\n val twiddleIdxTable = VecInit(twiddleIdxs.map(i => {\n ( (uniqueTwiddleIdxs.indexOf(i) /*+ stageN / 2*/) /*% stageN*/).U\n }))\n\n val twiddleCnt = ShiftRegister(ctrl + (stageN / 4).U, 2 * DspContext.current.numAddPipes)\n val twiddle = uniqueTwiddleTable(twiddleIdxTable(twiddleCnt))\n\n stage.out context_* twiddle\n } else {\n stage.out\n }\n\n (\n lastOut,\n ShiftRegister(en, outputLatency, resetData = false.B, en = true.B),\n ShiftRegister(last, outputLatency),\n ShiftRegister(ctrl.tail(2), outputLatency, resetData = 0.U, en = true.B),\n chiselTypeOf(stage.out.real)\n )\n }\n\n val initStageInfo = (inputManager.out.bits, inputManager.out.fire(), inputManager.out_last, cnt, protoIn)\n val (outBits, outFire, outLast, outCnt, _) = (0 until logn by 2).foldLeft(initStageInfo)(makeStage)\n\n // (1 add per BF stage) (1 mul every other stage, also excluding the last two)\n val latency = (DspContext.current.numAddPipes) * logn + complexMulLatency * ((logn - 2) / 2)\n println(s\"latency = $latency, numAdd = ${DspContext.current.numAddPipes}, numMul = ${DspContext.current.numMulPipes}\")\n // entries has + 1 because does not input does not flow through to output in single cycle\n val outQueue = Module(new Queue(DspComplex(protoOut), entries = latency + 1))\n val outLastQueue = Module(new Queue(Bool(), entries = latency + 1))\n outQueue.io.enq.bits := outBits\n outQueue.io.enq.valid := outFire\n assert(!outFire || outQueue.io.enq.ready, \"Output dropped because output queue full\")\n\n outLastQueue.io.enq.bits := outLast\n outLastQueue.io.enq.valid := outFire\n assert(!outFire || outLastQueue.io.enq.ready, \"Last dropped because output queue full\")\n assert(outQueue.io.deq.valid === outLastQueue.io.deq.valid)\n\n val inFlight = RegInit(0.U(log2Ceil(latency + 2).W))\n inFlight := inFlight +% inputManager.out.fire() -% outFire\n assert(inFlight > 0.U || inputManager.out.fire() || !outFire, \"Underflow on the inFlight counter\")\n\n inputManager.out.ready := inFlight +% outQueue.io.count < (latency + 1).U\n outputManager.in <> outQueue.io.deq\n outputManager.in_last := outLastQueue.io.deq.bits\n outLastQueue.io.deq.ready := outputManager.in.ready\n\n out <> outputManager.out\n out_last := outputManager.out_last\n}\n", "groundtruth": " val delays = (1 to nStages).map { n >> _ }\n", "crossfile_context": ""}
{"task_id": "ofdm", "path": "ofdm/src/main/scala/ofdm/Packetizer.scala", "left_context": "package ofdm\n\nimport chisel3._\nimport chisel3.internal.requireIsChiselType\nimport chisel3.util.log2Ceil\n\ncase class PacketizerIO[T <: Data](proto: T, size: Int) extends Bundle {\n requireIsChiselType(proto)\n val in = Flipped(IrrevocableLast(proto))\n val out = IrrevocableLast(proto)\n\n val includeMask = Input(Vec(size, Bool()))\n}\n\nclass Packetizer[T <: Data](proto: T, size: Int) extends Module {\n val io = IO(PacketizerIO(proto, size))\n\n val count = RegInit(UInt(log2Ceil(size).W), 0.U)\n val nextCount = Wire(UInt())\n count := nextCount\n\n when (io.in.fire()) {\n nextCount := count + 1.U\n", "right_context": " nextCount := 0.U\n }\n\n io.out.valid := io.in.fire() && io.includeMask(count)\n io.out.bits := io.in.bits\n io.out.last := nextCount === 0.U\n}\n", "groundtruth": " when (count + 1.U === size.U) {\n nextCount := 0.U\n }\n", "crossfile_context": ""}
{"task_id": "ofdm", "path": "ofdm/src/main/scala/ofdm/TreeReduce.scala", "left_context": "package ofdm\n\nobject TreeReduce {\n", "right_context": " if (in.length == 1) {\n return in.head\n }\n if (in.length == 2) {\n return func(in.head, in(1))\n }\n if (in.length % 2 == 0) {\n val withIdxs = in.zipWithIndex\n val evens = withIdxs.filter{case (_, idx) => idx % 2 == 0}.map(_._1)\n val odds = withIdxs.filter{case (_, idx) => idx % 2 != 0}.map(_._1)\n val evenOddPairs: Seq[(V, V)] = evens zip odds\n TreeReduce(evenOddPairs.map(x => func(x._1, x._2)), func)\n } else {\n TreeReduce(Seq(in.head, TreeReduce(in.drop(1), func)), func)\n }\n }\n}\n", "groundtruth": " def apply[V](in: Seq[V], func: (V, V) => V): V = {\n", "crossfile_context": ""}
{"task_id": "ofdm", "path": "ofdm/src/test/scala/ldpc/LdpcSpec.scala", "left_context": "package ldpc\n\nimport chisel3._\nimport chisel3.experimental.FixedPoint\nimport org.scalatest.{FlatSpec, Matchers}\n\nclass LdpcSpec extends FlatSpec with Matchers {\n\n behavior of \"Encoder\"\n\n it should \"work for simple wikipedia examples\" in {\n val generator = Seq(\n Seq(1, 0, 0, 1, 0, 1).map(_ != 0),\n Seq(0, 1, 0, 1, 1, 1).map(_ != 0),\n Seq(0, 0, 1, 1, 1, 0).map(_ != 0)\n )\n val inOuts = Seq(\n (Seq(0, 0, 0).map(_ != 0), Seq(0, 0, 0, 0, 0, 0).map(_ != 0)),\n (Seq(0, 0, 1).map(_ != 0), Seq(0, 0, 1, 1, 1, 0).map(_ != 0)),\n (Seq(0, 1, 0).map(_ != 0), Seq(0, 1, 0, 1, 1, 1).map(_ != 0)),\n (Seq(0, 1, 1).map(_ != 0), Seq(0, 1, 1, 0, 0, 1).map(_ != 0)),\n (Seq(1, 0, 0).map(_ != 0), Seq(1, 0, 0, 1, 0, 1).map(_ != 0)),\n (Seq(1, 0, 1).map(_ != 0), Seq(1, 0, 1, 0, 1, 1).map(_ != 0)),\n (Seq(1, 1, 0).map(_ != 0), Seq(1, 1, 0, 0, 1, 0).map(_ != 0)),\n (Seq(1, 1, 1).map(_ != 0), Seq(1, 1, 1, 1, 0, 0).map(_ != 0)),\n )\n EncoderTester(generator, inOuts) should be (true)\n }\n\n it should \"work for CCSDS (128, 64) example\" in {\n val generator = Generator.fromHexString(16, 128,\n \"0E69166BEF4C0BC2\" +\n \"7766137EBB248418\" +\n \"C480FEB9CD53A713\" +\n \"4EAA22FA465EEA11\"\n )\n // println(s\"Generator is ${generator.size} x ${generator.head.size}\")\n // println(generator.head.drop(64).mkString(\", \"))\n val inOuts = Seq(\n (Seq.fill(64)(false), Seq.fill(128)(false)),\n (Seq(true) ++ Seq.fill(63)(false),\n Seq(\n 1,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,\n 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,\n 0,0,0,0, 1,1,1,0, 0,1,1,0, 1,0,0,1, 0,0,0,1, 0,1,1,0, 0,1,1,0, 1,0,1,1,\n 1,1,1,0, 1,1,1,1, 0,1,0,0, 1,1,0,0, 0,0,0,0, 1,0,1,1, 1,1,0,0, 0,0,1,0).map(_ != 0)),\n (Seq(false, true) ++ Seq.fill(62)(false),\n Seq(\n 0,1,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,\n 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,\n 1,0,0,0,0, 1,1,1,0, 0,1,1,0, 1,0,0, 1,0,0,0,1, 0,1,1,0, 0,1,1,0, 1,0,1,\n 0,1,1,1,0, 1,1,1,1, 0,1,0,0, 1,1,0, 0,0,0,0,0, 1,0,1,1, 1,1,0,0, 0,0,1).map(_ != 0)),\n // (Seq.fill(64)(true), )\n )\n EncoderTester(generator, inOuts) should be (true)\n }\n\n behavior of \"Bitonic Sorter\"\n\n for (i <- 1 until 6) {\n val n = 1 << i\n it should s\"work for n = $n\" in {\n BitonicSorterTester(n) should be (true)\n }\n }\n\n behavior of \"Shifter\"\n\n for (i <- 2 until 32) {\n", "right_context": " behavior of \"Params\"\n\n it should \"compute a good schedule\" in {\n\n for (e <- CCSDS.params64x128.schedule) {\n println(e.entries.mkString(\", \"))\n }\n }\n\n behavior of \"BPDecoder\"\n\n it should \"decode small CCSDS (128, 64) code\" in {\n BPDecoderTester(FixedPoint(6.W, 2.BP), CCSDS.params64x128, nTrials = 2000, ebn0 = Seq(0.0, 1.0, 2.0, 3.0, 10.0)) should be (true)\n }\n\n it should \"decode the medium CCSDS (256, 128) code\" in {\n BPDecoderTester(FixedPoint(6.W, 2.BP), CCSDS.params128x256, nTrials = 500, ebn0 = Seq(3.0)) should be (true)\n }\n\n it should \"decode larger CCSDS (512, 256) code\" in {\n BPDecoderTester(FixedPoint(6.W, 2.BP), CCSDS.params256x512, nTrials = 500, ebn0 = Seq(3.0)) should be (true)\n }\n}\n", "groundtruth": " it should s\"work for n = $i\" in {\n ShifterTester(i) should be (true)\n }\n", "crossfile_context": ""}
{"task_id": "ofdm", "path": "ofdm/src/test/scala/ofdm/fft/TesterUtil.scala", "left_context": "package ofdm\npackage fft\n\nimport dsptools.DspTester\nimport breeze.math.Complex\nimport chisel3._\nimport dsptools.numbers._\n\n/*\n * Contains useful helper functions for testers\n */\ntrait HasTesterUtil[T <: Module] extends DspTester[T] {\n\n /*\n * Waits to see if a signal is asserted. If more than the allowed number\n * of cycles is passed while waiting, fail the test.\n */\n def wait_for_assert(signal: Bool, maxCyclesWait: Int) {\n require(maxCyclesWait > 0, \"maximum number of cycles to wait must be positive\")\n var cyclesWaiting = 0\n while (!peek(signal) && cyclesWaiting < maxCyclesWait) {\n cyclesWaiting += 1\n", "right_context": " step(1)\n }\n }\n\n // Poke the individual elements of a Vec of DspComplex\n def poke_complex_seq[U <: Data](sig_vec: Vec[DspComplex[U]], stim_seq: Seq[Complex]) {\n stim_seq.zipWithIndex.foreach { case (value, index) => poke(sig_vec(index), value) }\n }\n\n // Inspect and expect the individual elements of a Vec of DspComplex\n def expect_complex_seq[U <: Data](sig_vec: Vec[DspComplex[U]], exp_seq: Seq[Complex]) {\n assert(sig_vec.length == exp_seq.length)\n\n for ((e, s) <- exp_seq.zip(sig_vec)) {\n expect(s, e)\n }\n }\n\n}", "groundtruth": " if (cyclesWaiting >= maxCyclesWait) { expect(false, \"waited for input too long\") }\n", "crossfile_context": ""}
{"task_id": "OpenNCB", "path": "OpenNCB/src/main/scala/openncb/WithNCBParameters.scala", "left_context": "package cc.xiangshan.openncb\n\nimport org.chipsalliance.cde.config.Parameters\n\n\ntrait WithNCBParameters {\n\n implicit val p: Parameters\n \n", "right_context": "}\n", "groundtruth": " val paramNCB = p(NCBParametersKey)\n", "crossfile_context": ""}
{"task_id": "OpenNCB", "path": "OpenNCB/src/main/scala/openncb/axi/channel/AXI4ChannelAW.scala", "left_context": "package cc.xiangshan.openncb.axi.channel\n\nimport chisel3._\nimport chisel3.util._\nimport org.chipsalliance.cde.config.Parameters\nimport cc.xiangshan.openncb.axi.bundle._\n\n\n/*\n* AXI AW Channel. \n*/\nclass AXI4ChannelAW[+T <: AXI4BundleAW](gen: T) extends AbstractAXI4Channel[T](gen)\n\nobject AXI4ChannelAW {\n\n def apply[T <: AXI4BundleAW](gen: T) = new AXI4ChannelAW(gen)\n\n", "right_context": "}\n\n// Master AW Channel.\nobject AXI4ChannelMasterAW {\n\n def apply[T <: AXI4BundleAW](gen: T) = AXI4ChannelAW(gen)\n\n def apply()(implicit p: Parameters) = AXI4ChannelAW()\n}\n\n// Slave AW Channel.\nobject AXI4ChannelSlaveAW {\n\n def apply[T <: AXI4BundleAW](gen: T) = Flipped(AXI4ChannelAW(gen))\n\n def apply()(implicit p: Parameters) = Flipped(AXI4ChannelAW())\n}\n", "groundtruth": " def apply()(implicit p: Parameters) = new AXI4ChannelAW(new AXI4BundleAW)\n", "crossfile_context": ""}
{"task_id": "OpenNCB", "path": "OpenNCB/src/main/scala/openncb/chi/channel/package.scala", "left_context": "package cc.xiangshan.openncb.chi\n\nimport chisel3._\nimport chisel3.util.Cat\nimport cc.xiangshan.openncb.chi.bundle.CHIBundleDAT\nimport cc.xiangshan.openncb.chi.bundle.AbstractCHIBundle\nimport freechips.rocketchip.util.SeqToAugmentedSeq\nimport freechips.rocketchip.util.DataToAugmentedData\n\npackage object channel {\n\n /* \n * Connectors for CHI Channels and CHI Raw Channels\n */\n implicit class connectRawChannelFrom(dst: CHIRawChannel) {\n\n def :<<=[T <: Data](src: AbstractCHIChannel[T]) = {\n\n require(dst.channelType == src.channelType,\n s\"channel type mismatch: \" +\n s\"${dst.channelType.canonicalName} :<= ${src.channelType.canonicalName}\")\n\n if (dst.flit.isWidthKnown)\n require(dst.flit.getWidth == src.flit.getWidth,\n s\"width mismatch in raw channel connection: \" +\n s\"(dst = ${dst.flit.getWidth}) :<= (src = ${src.flit.getWidth})\")\n\n dst.flitpend := src.flitpend\n dst.flitv := src.flitv\n dst.flit := Cat(src.flit.getElements.map(_.asUInt))\n src.lcrdv := dst.lcrdv\n }\n }\n\n implicit class connectRawChannelTo(src: CHIRawChannel) {\n\n def :>>=[T <: Data](dst: AbstractCHIChannel[T]) = {\n\n require(dst.channelType == src.channelType,\n s\"channel type mismatch: \" +\n", "right_context": "\n if (dst.flit.isWidthKnown)\n require(dst.flit.getWidth == src.flit.getWidth,\n s\"width mismatch in raw channel connection: \" +\n s\"(dst = ${dst.flit.getWidth}) :>= (src = ${src.flit.getWidth})\")\n\n dst.flitpend := src.flitpend\n dst.flitv := src.flitv\n src.lcrdv := dst.lcrdv\n\n var scalaLsb = 0\n dst.flit.getElements.reverse.foreach(e => {\n e := src.flit(scalaLsb + e.getWidth - 1, scalaLsb)\n scalaLsb += e.getWidth\n })\n }\n }\n}\n\n", "groundtruth": " s\"${dst.channelType.canonicalName} :>= ${src.channelType.canonicalName}\")\n", "crossfile_context": ""}
{"task_id": "OpenNCB", "path": "OpenNCB/src/main/scala/openncb/logical/NCBOrderAddressCAM.scala", "left_context": "package cc.xiangshan.openncb.logical\n\nimport chisel3._\nimport chisel3.util._\nimport org.chipsalliance.cde.config.Parameters\nimport org.chipsalliance.cde.config.Field\nimport cc.xiangshan.openncb.WithNCBParameters\nimport cc.xiangshan.openncb.chi.WithCHIParameters\nimport cc.xiangshan.openncb.chi.field.CHIFieldSize\nimport cc.xiangshan.openncb.debug.DebugBundle\nimport cc.xiangshan.openncb.debug.DebugSignal\nimport cc.xiangshan.openncb.debug.DebugElement\nimport cc.xiangshan.openncb.util.ParallelMux\nimport cc.xiangshan.openncb.util.XZBarrier\nimport cc.xiangshan.openncb.util.ValidMux\n\n\n/*\n* NCB Address CAM for transaction address-order maintainence. \n*/\nobject NCBOrderAddressCAM {\n\n case class PublicParameters (\n )\n\n case object PublicParametersKey extends Field[PublicParameters]\n}\n\nclass NCBOrderAddressCAM(implicit val p: Parameters)\n extends Module with WithCHIParameters\n with WithNCBParameters {\n\n // public parameters\n val param = p.lift(NCBOrderAddressCAM.PublicParametersKey)\n .getOrElse(new NCBOrderAddressCAM.PublicParameters)\n\n // local parameters\n val paramMaskWidth = log2Up(CHIFieldSize.Size64B.sizeInBytes)\n\n def paramCAMCapacity = paramNCB.outstandingDepth\n\n\n /*\n * Port I/O: Allocate \n * \n * @io input en : Allocation Enable.\n * @io input strb : Allocation Strobe, one-hot addressing.\n * @io input mask : Allocation Address Mask, masking lower bits of maximum\n * address alignment width for overlapped comparsion.\n * @io input addr : Address Value, content-addressing.\n */\n class AllocatePort extends Bundle {\n val en = Input(Bool())\n val strb = Input(Vec(paramCAMCapacity, Bool()))\n val mask = Input(UInt(paramMaskWidth.W))\n val addr = Input(UInt(paramCHI.reqAddrWidth.W))\n }\n\n /*\n * Port I/O: Free\n * \n * @io input strb : Free Strobe, one-hot addressing.\n */\n class FreePort extends Bundle {\n val strb = Input(Vec(paramCAMCapacity, Bool()))\n }\n\n /*\n * Port I/O: Query \n * \n * @io input mask : Query Address Mask, masking lower bits of maximum\n * address alignment width for overlapped comparsion.\n * @io input addr : Query Address, content-addressing.\n * @io output resultValid : Query Result Valid.\n * @io output resultIndex : Query Result Index.\n */\n class QueryPort extends Bundle {\n val mask = Input(UInt(paramMaskWidth.W))\n val addr = Input(UInt(paramCHI.reqAddrWidth.W))\n val resultValid = Output(Bool())\n val resultIndex = Output(UInt(paramNCB.outstandingIndexWidth.W))\n }\n\n\n /*\n * Module I/O \n */\n val io = IO(new Bundle {\n // allocate port\n val allocate = new AllocatePort\n\n // free port\n val free = new FreePort\n\n // query port\n val query = new QueryPort\n })\n\n \n // CAM Registers\n class CAMEntry extends Bundle {\n val valid = Bool()\n val mask = UInt(paramMaskWidth.W)\n val addr = UInt(paramCHI.reqAddrWidth.W)\n }\n\n protected val regCAM = RegInit(init = VecInit(Seq.fill(paramCAMCapacity){\n val resetValue = Wire(new CAMEntry)\n resetValue.valid := false.B\n resetValue.mask := DontCare\n resetValue.addr := DontCare\n resetValue\n }))\n\n \n\n\n // CAM comparators\n def funcCompare(a: UInt, b: UInt, mask: UInt) = {\n\n require(a.isWidthKnown && b.isWidthKnown && mask.isWidthKnown)\n require(a.getWidth == b.getWidth)\n\n val wireUpperA = a.head(a.getWidth - mask.getWidth)\n val wireUpperB = b.head(b.getWidth - mask.getWidth)\n\n val logicLowerA = a(mask.getWidth - 1, 0) & mask\n val logicLowerB = a(mask.getWidth - 1, 0) & mask\n\n (wireUpperA === wireUpperB) && (logicLowerA === logicLowerB)\n }\n\n\n // CAM update logic\n regCAM.zipWithIndex.foreach({ case (entry, i) => {\n\n // CAM entry allocate and update\n when (io.allocate.en) {\n when (io.allocate.strb(i)) {\n entry.valid := true.B\n entry.mask := io.allocate.mask\n entry.addr := io.allocate.addr\n\n }.elsewhen (funcCompare(entry.addr, io.allocate.addr, entry.mask & io.allocate.mask)) {\n entry.valid := false.B\n }\n }\n\n // CAM entry free\n when (io.free.strb(i)) {\n entry.valid := false.B\n }\n }})\n\n\n // CAM query logic\n val logicCAMHit = regCAM.map(entry => {\n ValidMux(entry.valid, \n funcCompare(entry.addr, io.query.addr, entry.mask & io.query.mask))\n })\n\n io.query.resultValid := VecInit(logicCAMHit).asUInt.orR\n io.query.resultIndex := ParallelMux(logicCAMHit.zipWithIndex.map({ case(entry, i) => {\n (entry, i.U(paramNCB.outstandingIndexWidth.W))\n }}))\n\n\n // assertions & debugs\n /*\n * Port I/O: Debug \n */\n class DebugPort extends DebugBundle {\n val AllocateNotOneHot = Output(Bool())\n val QueryResultMultipleHit = Output(Bool())\n val DoubleAllocation = Output(Vec(paramCAMCapacity, Bool()))\n }\n\n @DebugSignal\n val debug = IO(new DebugPort)\n\n @DebugElement\n protected val debugRegCAMFreeable = RegInit(\n init = VecInit(Seq.fill(paramCAMCapacity)(false.B)))\n\n debugRegCAMFreeable.zipWithIndex.foreach({ case (entry, i) => {\n\n when (io.free.strb(i)) {\n entry := false.B\n }\n\n when (io.allocate.en & io.allocate.strb(i)) {\n entry := true.B\n }\n }})\n\n /*\n * @assertion AllocateNotOneHot \n * The allocation strobe must be one-hot. Only one exactly entry was allowed to be\n * allocated at a time.\n */\n debug.AllocateNotOneHot := io.allocate.en && PopCount(io.allocate.strb) =/= 1.U\n assert(!debug.AllocateNotOneHot,\n \"multiple or zero allocation\")\n\n /*\n * @assertion QueryResultMultipleHit\n * On query, no more than one entry was allowed to be hit.\n */\n private val debugWireQueryHit = regCAM.map(entry => {\n XZBarrier(entry.valid, funcCompare(entry.addr, io.query.addr, entry.mask & io.query.mask))\n })\n debug.QueryResultMultipleHit := PopCount(debugWireQueryHit) > 1.U\n assert(!debug.QueryResultMultipleHit,\n \"multiple query result hit\")\n\n /*\n * @assertion DoubleAllocation\n * A yet allocated entry was not allowed to be allocated again.\n */\n (0 until paramCAMCapacity).foreach(i => {\n debug.DoubleAllocation(i) := io.allocate.en && io.allocate.strb(i) && (regCAM(i).valid || debugRegCAMFreeable(i))\n assert(!debug.DoubleAllocation(i),\n", "right_context": " })\n}", "groundtruth": " s\"double allocation at [${i}]\")\n", "crossfile_context": ""}
{"task_id": "OpenNCB", "path": "OpenNCB/src/main/scala/openncb/logical/NCBTransactionQueue.scala", "left_context": "package cc.xiangshan.openncb.logical\n\nimport chisel3._\nimport chisel3.util.log2Up\nimport org.chipsalliance.cde.config.Parameters\nimport org.chipsalliance.cde.config.Field\nimport cc.xiangshan.openncb.WithNCBParameters\nimport cc.xiangshan.openncb.axi.WithAXI4Parameters\nimport cc.xiangshan.openncb.axi.field.AXI4FieldAxBURST\nimport cc.xiangshan.openncb.axi.field.AXI4FieldAxSIZE\nimport cc.xiangshan.openncb.chi.CHIConstants\nimport cc.xiangshan.openncb.chi.WithCHIParameters\nimport cc.xiangshan.openncb.util.ParallelMux\nimport cc.xiangshan.openncb.util.ValidMux\nimport cc.xiangshan.openncb.debug.DebugBundle\nimport cc.xiangshan.openncb.debug.DebugSignal\n\n\n/*\n* NCB Transaction Queue. \n*/\nobject NCBTransactionQueue {\n\n case class PublicParameters (\n )\n\n case object PublicParametersKey extends Field[PublicParameters]\n}\n\nclass NCBTransactionQueue(implicit val p: Parameters)\n extends Module with WithAXI4Parameters\n with WithCHIParameters\n with WithNCBParameters {\n\n // public parameters\n val param = p.lift(NCBTransactionQueue.PublicParametersKey)\n .getOrElse(new NCBTransactionQueue.PublicParameters)\n \n\n // local parameters\n protected def paramQueueCapacity = paramNCB.outstandingDepth\n protected def paramQueueAddressWidth = paramNCB.outstandingIndexWidth\n\n protected def paramUpstreamMaxBeatCount = CHIConstants.CHI_MAX_PACKET_DATA_BITS_WIDTH / paramCHI.dataWidth\n protected def paramUpstreamMaxBeatCountWidth = log2Up(paramUpstreamMaxBeatCount)\n\n protected def paramDownstreamMaxBeatCount = CHIConstants.CHI_MAX_PACKET_DATA_BITS_WIDTH / paramAXI4.dataWidth\n protected def paramDownstreamMaxBeatCountWidth = log2Up(paramDownstreamMaxBeatCount)\n\n\n /* \n * Bundle definitions\n */\n trait TraitTransactionOpElement {\n val valid = Bool()\n\n def ready: Bool = valid\n }\n\n class TransactionOpCHIComp extends Bundle with TraitTransactionOpElement {\n val barrier = new Bundle {\n val CHICancelOrAXIBresp = Bool()\n }\n\n override def ready: Bool = valid & !barrier.asUInt.orR\n }\n\n class TransactionOpCHIDBIDResp extends Bundle with TraitTransactionOpElement\n\n class TransactionOpCHICompDBIDResp extends Bundle with TraitTransactionOpElement \n\n class TransactionOpCHIReadReceipt extends Bundle with TraitTransactionOpElement {\n val barrier = new Bundle {\n val AXIARready = Bool()\n }\n\n override def ready: Bool = valid & !barrier.asUInt.orR\n }\n\n class TransactionOpCHICompData extends Bundle with TraitTransactionOpElement\n\n class TransactionOpAXIWriteAddress extends Bundle with TraitTransactionOpElement {\n val barrier = new Bundle {\n val CHIWriteBackData = Bool()\n }\n\n override def ready: Bool = valid & !barrier.asUInt.orR\n }\n\n class TransactionOpAXIWriteData extends Bundle with TraitTransactionOpElement\n\n class TransactionOpAXIWriteResponse extends Bundle with TraitTransactionOpElement\n\n class TransactionOpAXIReadAddress extends Bundle with TraitTransactionOpElement\n\n class TransactionOpAXIReadData extends Bundle with TraitTransactionOpElement\n\n class TransactionOp extends Bundle {\n // CHI ops\n val chi = new Bundle {\n //\n val Comp = new TransactionOpCHIComp\n val DBIDResp = new TransactionOpCHIDBIDResp\n val CompDBIDResp = new TransactionOpCHICompDBIDResp\n val ReadReceipt = new TransactionOpCHIReadReceipt\n //\n val CompData = new TransactionOpCHICompData\n\n //\n def valid = VecInit(\n getElements.map(_.asInstanceOf[TraitTransactionOpElement].valid)\n ).asUInt.orR\n }\n\n // AXI ops\n val axi = new Bundle {\n //\n val WriteAddress = new TransactionOpAXIWriteAddress\n val WriteData = new TransactionOpAXIWriteData\n val WriteResponse = new TransactionOpAXIWriteResponse\n //\n val ReadAddress = new TransactionOpAXIReadAddress\n val ReadData = new TransactionOpAXIReadData\n\n //\n def valid = VecInit(\n getElements.map(_.asInstanceOf[TraitTransactionOpElement].valid)\n ).asUInt.orR\n }\n }\n\n //\n class TransactionInfo extends Bundle {\n val QoS = UInt(paramCHI.reqQoSWidth.W)\n val TgtID = UInt(paramCHI.reqTgtIDWidth.W)\n val SrcID = UInt(paramCHI.reqSrcIDWidth.W)\n val TxnID = UInt(paramCHI.reqTxnIDWidth.W)\n val ReturnNID = UInt(paramCHI.reqReturnNIDWidth.W)\n val ReturnTxnID = UInt(paramCHI.reqReturnTxnIDWidth.W)\n }\n\n //\n class TransactionOperandCHI extends Bundle {\n val Addr = UInt(paramCHI.reqAddrWidth.W)\n //\n val WriteFull = Bool()\n val WritePtl = Bool()\n //\n val ReadRespErr = UInt(paramCHI.rspRespErrWidth.W)\n val WriteRespErr = UInt(paramCHI.datRespErrWidth.W)\n //\n val Critical = Vec(paramUpstreamMaxBeatCount, Bool())\n val Count = UInt(paramUpstreamMaxBeatCountWidth.W)\n }\n\n class TransactionOperandAXI extends Bundle {\n val Addr = UInt(paramAXI4.addrWidth.W)\n val Burst = UInt(AXI4FieldAxBURST.width.W)\n val Size = UInt(AXI4FieldAxSIZE.width.W)\n val Len = UInt(8.W)\n val Device = Bool()\n //\n val Critical = Vec(paramDownstreamMaxBeatCount, Bool())\n val Count = UInt(paramDownstreamMaxBeatCountWidth.W)\n }\n\n class TransactionOperand extends Bundle {\n // CHI operands\n val chi = new TransactionOperandCHI\n\n // AXI operands\n val axi = new TransactionOperandAXI\n }\n\n //\n class TransactionOrder extends Bundle {\n val valid = Bool()\n val index = UInt(paramQueueAddressWidth.W)\n }\n /**/\n\n //\n class QueueEntry extends Bundle {\n // operation bit entires\n val op = new TransactionOp\n\n // transaction info entries\n val info = new TransactionInfo\n\n // transaction operand entries\n val operand = new TransactionOperand\n\n // transaction order maintainence entries\n val order = new TransactionOrder\n }\n\n\n /*\n * Port I/O: Transaction Allocation\n */\n class AllocatePort extends Bundle {\n // allocation enable\n val en = Input(Bool())\n\n // allocation target strobe\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n\n // allocation transaction bits\n val bits = new Bundle {\n // operation bits\n val op = Input(new TransactionOp)\n\n // transaction infos\n val info = Input(new TransactionInfo)\n\n // transaction operands\n val operand = Input(new TransactionOperand)\n\n // transaction order maintainence\n val order = Input(new TransactionOrder)\n }\n }\n\n /*\n * Port I/O: Transaction Free \n */\n class FreePort extends Bundle {\n // free strobe\n val strb = Output(Vec(paramNCB.outstandingDepth, Bool()))\n }\n\n /*\n * Port I/O: Upstream Query (for RXDAT)\n */\n class UpstreamQueryPort extends Bundle {\n val en = Input(Bool())\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n val result = new Bundle {\n val valid = Output(Bool())\n val WriteFull = Output(Bool())\n val WritePtl = Output(Bool())\n val ReadRespErr = Output(UInt(paramCHI.rspRespErrWidth.W))\n val WriteRespErr = Output(UInt(paramCHI.datRespErrWidth.W))\n }\n }\n\n /*\n * Port I/O: Upstream Cancel Update (for RXDAT)\n */\n class UpstreamCancelPort extends Bundle {\n val en = Input(Bool())\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n }\n\n /* \n * Port I/O: Upstream Write Data Update (for RXDAT)\n */\n class UpstreamWriteDataPort extends Bundle {\n val en = Input(Bool())\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n }\n\n /*\n * Port I/O: Upstream RSP Op Valid (for TXRSP)\n */\n class UpstreamRspOpValidPort extends Bundle {\n val valid = Output(Vec(paramNCB.outstandingDepth, Bool()))\n }\n\n /*\n * Port I/O: Upstream RSP Op Read (for TXRSP) \n */\n class UpstreamRspOpReadPort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n val bits = new Bundle {\n val Comp = Output(Bool())\n val DBIDResp = Output(Bool())\n val CompDBIDResp = Output(Bool())\n val ReadReceipt = Output(Bool())\n }\n }\n\n /*\n * Port I/O: Upstream RSP Op Done (for TXRSP)\n */\n class UpstreamRspOpDonePort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n val bits = new Bundle {\n val Comp = Input(Bool())\n val DBIDResp = Input(Bool())\n val CompDBIDResp = Input(Bool())\n val ReadReceipt = Input(Bool())\n }\n }\n\n /* \n * Port I/O: Upstream RSP Info Read (for TXRSP)\n */\n class UpstreamRspInfoReadPort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n val bits = Output(new TransactionInfo)\n }\n\n /*\n * Port I/O: Upstream RSP Operand Read (for TXRSP) \n */\n class UpstreamRspOperandReadPort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n val bits = Output(new TransactionOperandCHI)\n }\n\n /*\n * Port I/O: Upstream DAT Op Valid (for TXDAT)\n */\n class UpstreamDatOpValidPort extends Bundle {\n val valid = Output(Vec(paramNCB.outstandingDepth, Bool()))\n val bits = new Bundle {\n val Critical = Output(Vec(paramNCB.outstandingDepth, Vec(paramUpstreamMaxBeatCount, Bool())))\n }\n }\n\n /*\n * Port I/O: Upstream DAT Op Read (for TXDAT) \n */\n class UpstreamDatOpReadPort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n val bits = new Bundle {\n val CompData = new Bundle {\n val valid = Output(Bool())\n }\n }\n }\n\n /* \n * Port I/O: Upstream DAT Op Done (for TXDAT)\n */\n class UpstreamDatOpDonePort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n val bits = new Bundle {\n val CompData = Input(Bool())\n }\n }\n\n /*\n * Port I/O: Upstream DAT Info Read (for TXDAT)\n */\n class UpstreamDatInfoReadPort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n val bits = Output(new TransactionInfo)\n }\n\n /*\n * Port I/O: Upstream DAT Operand Read (for TXDAT) \n */\n class UpstreamDatOperandReadPort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n val bits = Output(new TransactionOperandCHI)\n }\n\n /*\n * Port I/O: Upstream DAT Operand Write (for TXDAT)\n */\n class UpstreamDatOperandWritePort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n val bits = new Bundle {\n val Critical = Input(Vec(paramUpstreamMaxBeatCount, Bool()))\n val Count = Input(UInt(paramUpstreamMaxBeatCountWidth.W))\n }\n }\n\n /*\n * Port I/O: Downstream AW Op Valid Read \n */\n class DownstreamAWOpValidPort extends Bundle {\n val valid = Output(Vec(paramNCB.outstandingDepth, Bool()))\n }\n\n /*\n * Port I/O: Downstream AW Op Point of No Return\n */\n class DownstreamAWOpPoNRPort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n }\n\n /*\n * Port I/O: Downstream AW Op Done\n */\n class DownstreamAWOpDonePort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n }\n\n /*\n * Port I/O: Downstream AW Info Read \n */\n class DownstreamAWInfoReadPort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n val bits = Output(new TransactionInfo)\n }\n\n /*\n * Port I/O: Downstream AW Operand Read \n */\n class DownstreamAWOperandReadPort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n val bits = Output(new TransactionOperandAXI)\n }\n\n /*\n * Port I/O: Downstream W Op Point of No Return\n */\n class DownstreamWOpPoNRPort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n }\n\n /*\n * Port I/O: Downstream W Op Done\n */\n class DownstreamWOpDonePort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n }\n\n /*\n * Port I/O: Downstream W Operand Read \n */\n class DownstreamWOperandReadPort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n val bits = Output(new TransactionOperandAXI)\n }\n\n /*\n * Port I/O: Downstream W Operand Write\n */\n class DownstreamWOperandWritePort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n val bits = new Bundle {\n val Critical = Input(Vec(paramDownstreamMaxBeatCount, Bool()))\n val Count = Input(UInt(paramDownstreamMaxBeatCountWidth.W))\n }\n }\n\n /*\n * Port I/O: Downstream B Op Done \n */\n class DownstreamBOpDonePort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n }\n\n /*\n * Port I/O: Downstream B Operand Write \n */\n class DownstreamBOperandWritePort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n val bits = new Bundle {\n val WriteRespErr = Input(UInt(paramCHI.rspRespErrWidth.W))\n }\n }\n\n /*\n * Port I/O: Downstream AR Op Valid \n */\n class DownstreamAROpValidPort extends Bundle {\n val valid = Output(Vec(paramNCB.outstandingDepth, Bool()))\n }\n\n /*\n * Port I/O: Downstream AR Op Point of No Return\n */\n class DownstreamAROpPoNRPort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n }\n\n /*\n * Port I/O: Downstream AR Op Done\n */\n class DownstreamAROpDonePort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n }\n\n /*\n * Port I/O: Downstream AR Info Read \n */\n class DownstreamARInfoReadPort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n val bits = Output(new TransactionInfo)\n }\n\n /*\n * Port I/O: Downstream AR Operand Read \n */\n class DownstreamAROperandReadPort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n val bits = Output(new TransactionOperandAXI)\n }\n\n /*\n * Port I/O: Downstream R Op Done\n */\n class DownstreamROpDonePort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n }\n\n /*\n * Port I/O: Downstream R Operand Read \n */\n class DownstreamROperandReadPort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n val bits = Output(new TransactionOperandAXI)\n }\n\n /*\n * Port I/O: Downstream R Operand AXI Write\n */\n class DownstreamROperandAXIWritePort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n val bits = new Bundle {\n val Critical = Input(Vec(paramDownstreamMaxBeatCount, Bool()))\n val Count = Input(UInt(paramDownstreamMaxBeatCountWidth.W))\n }\n }\n \n /*\n * Port I/O: Downstream R Operand CHI Write\n */\n class DownstreamROperandCHIWritePort extends Bundle {\n val strb = Input(Vec(paramNCB.outstandingDepth, Bool()))\n val bits = new Bundle {\n val ReadRespErr = Input(UInt(paramCHI.datRespErrWidth.W))\n }\n }\n\n\n /*\n * Module I/O \n */\n val io = IO(new Bundle {\n // free output port\n val free = new FreePort\n\n // allocate port (for RXREQ)\n val allocate = new AllocatePort\n\n // upstream ports (for RXDAT)\n val upstreamRxDat = new Bundle {\n val query = new UpstreamQueryPort\n val cancel = new UpstreamCancelPort\n val writeData = new UpstreamWriteDataPort\n }\n\n // upstream ports (for TXRSP)\n val upstreamTxRsp = new Bundle {\n val opValid = new UpstreamRspOpValidPort\n val opRead = new UpstreamRspOpReadPort\n val opDone = new UpstreamRspOpDonePort\n val infoRead = new UpstreamRspInfoReadPort\n val operandRead = new UpstreamRspOperandReadPort\n }\n \n // upstream ports (for TXDAT)\n val upstreamTxDat = new Bundle {\n val opValid = new UpstreamDatOpValidPort\n val opRead = new UpstreamDatOpReadPort\n val opDone = new UpstreamDatOpDonePort\n val infoRead = new UpstreamDatInfoReadPort\n val operandRead = new UpstreamDatOperandReadPort\n val operandWrite = new UpstreamDatOperandWritePort\n }\n\n // downstream ports (for AXI AW)\n val downstreamAw = new Bundle {\n val opValid = new DownstreamAWOpValidPort\n val opPoNR = new DownstreamAWOpPoNRPort\n val opDone = new DownstreamAWOpDonePort\n val infoRead = new DownstreamAWInfoReadPort\n val operandRead = new DownstreamAWOperandReadPort\n }\n\n // downstream ports (for AXI W)\n val downstreamW = new Bundle {\n val opPoNR = new DownstreamWOpPoNRPort\n val opDone = new DownstreamWOpDonePort\n val operandRead = new DownstreamWOperandReadPort\n val operandWrite = new DownstreamWOperandWritePort\n }\n\n // downstream ports (for AXI B)\n val downstreamB = new Bundle {\n val opDone = new DownstreamBOpDonePort\n val operandWrite = new DownstreamBOperandWritePort\n }\n\n // downstream ports (for AXI AR)\n val downstreamAr = new Bundle {\n val opValid = new DownstreamAROpValidPort\n val opPoNR = new DownstreamAROpPoNRPort\n val opDone = new DownstreamAROpDonePort\n val infoRead = new DownstreamARInfoReadPort\n val operandRead = new DownstreamAROperandReadPort\n }\n\n // downstream ports (for AXI R)\n val downstreamR = new Bundle {\n val opDone = new DownstreamROpDonePort\n val operandRead = new DownstreamROperandReadPort\n val operandAXIWrite = new DownstreamROperandAXIWritePort\n val operandCHIWrite = new DownstreamROperandCHIWritePort\n }\n })\n\n\n /*\n * Transaction Queue Registers\n */\n protected val regQueue = RegInit(init = VecInit(Seq.fill(paramQueueCapacity){\n val resetValue = Wire(new Bundle {\n val valid = Output(Bool())\n val bits = Output(new QueueEntry)\n })\n\n resetValue.valid := false.B\n resetValue.bits := DontCare\n resetValue.bits.op := 0.U.asTypeOf(chiselTypeOf(resetValue.bits.op))\n\n resetValue\n }))\n\n // entry free logic\n protected val logicEntryFree = regQueue.map({ entry => {\n entry.valid & !entry.bits.op.chi.valid & !entry.bits.op.axi.valid\n }})\n\n io.free.strb := logicEntryFree\n \n logicEntryFree.zipWithIndex.foreach({ case (free, i) => {\n // free self\n when (free) {\n regQueue(i).valid := false.B\n }\n }})\n\n regQueue.zipWithIndex.foreach({ case (entry, i) => {\n // free order relation\n val logicOrderHit = VecInit(logicEntryFree.zipWithIndex.map({ case (free, j) => {\n if (i == j) false.B else free && entry.bits.order.index === j.U\n }})).asUInt.orR\n\n when(logicOrderHit) {\n entry.bits.order.valid := false.B\n }\n }})\n\n // entry allocate logic\n val logicAllocateOrderOrdinal = VecInit((0 until paramQueueCapacity).map(i => {\n io.allocate.bits.order.index === i.U\n }))\n\n regQueue.zipWithIndex.foreach({ case (entry, i) => {\n\n when (io.allocate.en & io.allocate.strb(i)) {\n\n val logicOrderHit = VecInit(logicEntryFree.zipWithIndex.map({ case (free, j) => {\n if (i == j) false.B else free && logicAllocateOrderOrdinal(j)\n }})).asUInt.orR\n\n entry.valid := true.B\n \n entry.bits.op := io.allocate.bits.op\n entry.bits.info := io.allocate.bits.info\n entry.bits.operand := io.allocate.bits.operand\n entry.bits.order.index := io.allocate.bits.order.index\n entry.bits.order.valid := ValidMux(!logicOrderHit, io.allocate.bits.order.valid)\n }\n }})\n\n // barrier logic: CHI.Op.Comp.CHICancelOrAXIBresp\n regQueue.zipWithIndex.foreach({ case (entry, i) => {\n\n // on CHI WriteDataCancel\n when (io.upstreamRxDat.cancel.en & io.upstreamRxDat.cancel.strb(i)) {\n // clear CHI domain barriers\n entry.bits.op.chi.Comp.barrier.CHICancelOrAXIBresp := false.B\n\n // clear AXI domain write tasks\n entry.bits.op.axi.WriteAddress .valid := false.B\n entry.bits.op.axi.WriteData .valid := false.B\n entry.bits.op.axi.WriteResponse .valid := false.B\n }\n\n // on AXI BRESP\n when (io.downstreamB.opDone.strb(i)) {\n // clear CHI domain barriers\n entry.bits.op.chi.Comp.barrier.CHICancelOrAXIBresp := false.B\n }\n }})\n\n // barrier logic: CHI.Op.ReadReceipt.AXIARready\n regQueue.zipWithIndex.foreach({ case (entry, i) => {\n\n // on AXI ARREADY\n when (io.downstreamAr.opDone.strb(i)) {\n // clear CHI domain barriers\n entry.bits.op.chi.ReadReceipt.barrier.AXIARready := false.B\n }\n }})\n\n // barrier logic: AXI.Op.WriteAddress.CHIWriteBackData\n regQueue.zipWithIndex.foreach({ case (entry, i) => {\n \n // on CHI NonCopyBackWrData\n when (io.upstreamRxDat.writeData.en & io.upstreamRxDat.writeData.strb(i)) {\n // clear AXI domain barriers\n entry.bits.op.axi.WriteAddress.barrier.CHIWriteBackData := false.B\n }\n }})\n\n // TXRSP op valid output logic\n io.upstreamTxRsp.opValid.valid.zipWithIndex.map({ case (valid, i) => {\n (valid, i, regQueue(i).bits.op, regQueue(i).bits.order)\n }}).foreach({ case (valid, i, entry, order) => {\n valid := VecInit(Seq(\n entry.chi.Comp .ready,\n entry.chi.DBIDResp .ready,\n entry.chi.CompDBIDResp .ready,\n entry.chi.ReadReceipt .ready\n )).asUInt.orR & !order.valid\n }})\n\n // TXDAT op valid output logic\n io.upstreamTxDat.opValid.valid.zipWithIndex.map({ case (valid, i) => {\n (valid, i, regQueue(i).bits.op, regQueue(i).bits.order)\n }}).foreach({ case (valid, i, entry, order) => {\n valid := VecInit(Seq(\n entry.chi.CompData .valid\n )).asUInt.orR & !order.valid\n }})\n\n io.upstreamTxDat.opValid.bits.Critical.zipWithIndex.map({ case (critical, i) => {\n (critical, regQueue(i).bits.operand.chi.Critical)\n }}).foreach({ case (critical, entry) => {\n critical := entry\n }})\n\n // AXI AW op valid output logic\n io.downstreamAw.opValid.valid.zipWithIndex.map({ case (valid, i) => {\n (valid, regQueue(i).bits.op, regQueue(i).bits.order)\n }}).foreach({ case (valid, entry, order) => {\n valid := entry.axi.WriteAddress.ready & !order.valid\n }})\n\n // AXI AR op valid output logic\n io.downstreamAr.opValid.valid.zipWithIndex.map({ case (valid, i) => {\n (valid, regQueue(i).bits.op, regQueue(i).bits.order)\n }}).foreach({ case (valid, entry, order) => {\n valid := entry.axi.ReadAddress.ready & !order.valid\n }})\n\n // TXRSP op read logic\n io.upstreamTxRsp.opRead.bits := ParallelMux(\n io.upstreamTxRsp.opRead.strb.zipWithIndex.map({ case (strb, i) => {\n (strb, regQueue(i).bits.op)\n }}).map({ case (strb, op) => {\n\n val valid = Wire(chiselTypeOf(io.upstreamTxRsp.opRead.bits))\n\n valid.Comp := op.chi.Comp .ready\n valid.DBIDResp := op.chi.DBIDResp .ready\n valid.CompDBIDResp := op.chi.CompDBIDResp .ready\n valid.ReadReceipt := op.chi.ReadReceipt .ready\n\n (strb, valid)\n }})\n )\n\n // TXDAT op read logic\n io.upstreamTxDat.opRead.bits := ParallelMux(\n io.upstreamTxDat.opRead.strb.zipWithIndex.map({ case (strb, i) => {\n (strb, regQueue(i).bits.op)\n }}).map({ case (strb, entry) => {\n\n val op = Wire(chiselTypeOf(io.upstreamTxDat.opRead.bits))\n\n op.CompData.valid := entry.chi.CompData.valid\n\n (strb, op)\n }})\n )\n\n // AXI AW op PoNR logic\n regQueue.zipWithIndex.map({ case (entry, i) => {\n (entry, io.downstreamAw.opPoNR.strb(i))\n }}).foreach({ case (entry, strb) => {\n\n when(strb) {\n entry.bits.op.axi.WriteAddress .valid := false.B\n }\n }})\n\n // AXI W op PoNR logic\n regQueue.zipWithIndex.map({ case (entry, i) => {\n (entry, io.downstreamW.opPoNR.strb(i))\n }}).foreach({ case (entry, strb) => {\n\n when (strb) {\n entry.bits.op.axi.WriteData .valid := false.B\n }\n }})\n\n // AXI AR op PoNR logic\n regQueue.zipWithIndex.map({ case (entry, i) => {\n (entry, io.downstreamAr.opPoNR.strb(i))\n }}).foreach({ case (entry, strb) => {\n\n when (strb) {\n entry.bits.op.axi.ReadAddress .valid := false.B\n }\n }})\n\n // TXRSP op done logic\n regQueue.zipWithIndex.map({ case (entry, i) => {\n (entry, io.upstreamTxRsp.opDone.strb(i), io.upstreamTxRsp.opDone.bits)\n }}).foreach({ case (entry, strb, bits) => {\n\n when (strb) {\n\n when (bits.Comp) {\n entry.bits.op.chi.Comp .valid := false.B\n }\n\n when (bits.DBIDResp) {\n entry.bits.op.chi.DBIDResp .valid := false.B\n }\n\n when (bits.CompDBIDResp) {\n entry.bits.op.chi.CompDBIDResp .valid := false.B\n }\n\n when (bits.ReadReceipt) {\n entry.bits.op.chi.ReadReceipt .valid := false.B\n }\n } \n }})\n\n // TXDAT op done logic\n regQueue.zipWithIndex.map({ case (entry, i) => {\n (entry, io.upstreamTxDat.opDone.strb(i), io.upstreamTxDat.opDone.bits)\n }}).foreach({ case (entry, strb, bits) => {\n\n when (strb) {\n\n when (bits.CompData & entry.bits.operand.chi.Count === 0.U) {\n entry.bits.op.chi.CompData .valid := false.B\n }\n }\n }})\n\n // AXI B op done logic\n regQueue.zipWithIndex.map({ case (entry, i) => {\n (entry, io.downstreamB.opDone.strb(i))\n }}).foreach({ case (entry, strb) => {\n\n when (strb) {\n entry.bits.op.axi.WriteResponse .valid := false.B\n }\n }})\n\n // AXI R op done logic\n regQueue.zipWithIndex.map({ case (entry ,i) => {\n (entry, io.downstreamR.opDone.strb(i))\n }}).foreach({ case (entry, strb) => {\n\n when (strb) {\n entry.bits.op.axi.ReadData .valid := false.B\n }\n }})\n\n // TXRSP info read logic\n io.upstreamTxRsp.infoRead.bits := ParallelMux(\n io.upstreamTxRsp.infoRead.strb.zipWithIndex.map({ case (strb, i) => {\n (strb, regQueue(i).bits.info)\n }})\n )\n\n // TXDAT info read logic\n io.upstreamTxDat.infoRead.bits := ParallelMux(\n io.upstreamTxDat.infoRead.strb.zipWithIndex.map({ case (strb, i) => {\n (strb, regQueue(i).bits.info)\n }})\n )\n\n // AXI AW info read logic\n io.downstreamAw.infoRead.bits := ParallelMux(\n io.downstreamAw.infoRead.strb.zipWithIndex.map({ case (strb, i) => {\n (strb, regQueue(i).bits.info)\n }})\n )\n\n // AXI AR info read logic\n io.downstreamAr.infoRead.bits := ParallelMux(\n io.downstreamAr.infoRead.strb.zipWithIndex.map({ case (strb, i) => {\n (strb, regQueue(i).bits.info)\n }})\n )\n\n // TXRSP operand read logic\n io.upstreamTxRsp.operandRead.bits := ParallelMux(\n io.upstreamTxDat.operandRead.strb.zipWithIndex.map({ case (strb, i) => {\n (strb, regQueue(i).bits.operand.chi)\n }})\n )\n \n // TXDAT operand read logic\n io.upstreamTxDat.operandRead.bits := ParallelMux(\n io.upstreamTxDat.operandRead.strb.zipWithIndex.map({ case (strb, i) => {\n (strb, regQueue(i).bits.operand.chi)\n }})\n )\n\n // AXI AW operand read logic\n io.downstreamAw.operandRead.bits := ParallelMux(\n io.downstreamAw.operandRead.strb.zipWithIndex.map({ case (strb, i) => {\n (strb, regQueue(i).bits.operand.axi)\n }})\n )\n\n // AXI W operand read logic\n io.downstreamW.operandRead.bits := ParallelMux(\n io.downstreamW.operandRead.strb.zipWithIndex.map({ case (strb, i) => {\n (strb, regQueue(i).bits.operand.axi)\n }})\n )\n\n // AXI AR operand read logic\n io.downstreamAr.operandRead.bits := ParallelMux(\n io.downstreamAr.operandRead.strb.zipWithIndex.map({ case (strb, i) => {\n (strb, regQueue(i).bits.operand.axi)\n }})\n )\n\n // AXI R operand read logic\n io.downstreamR.operandRead.bits := ParallelMux(\n io.downstreamR.operandRead.strb.zipWithIndex.map({ case (strb, i) => {\n (strb, regQueue(i).bits.operand.axi)\n }})\n )\n\n // TXDAT operand write logic\n regQueue.zipWithIndex.map({ case (entry, i) => {\n (entry, io.upstreamTxDat.operandWrite.strb(i))\n }}).foreach({ case (entry, strb) => {\n\n when (strb) {\n entry.bits.operand.chi.Critical := io.upstreamTxDat.operandWrite.bits.Critical\n entry.bits.operand.chi.Count := io.upstreamTxDat.operandWrite.bits.Count\n }\n }})\n\n // AXI W operand write logic\n regQueue.zipWithIndex.map({ case (entry, i) => {\n (entry, io.downstreamW.operandWrite.strb(i))\n }}).foreach({ case (entry, strb) => {\n\n when (strb) {\n entry.bits.operand.axi.Critical := io.downstreamW.operandWrite.bits.Critical\n entry.bits.operand.axi.Count := io.downstreamW.operandWrite.bits.Count\n }\n }})\n\n // AXI B operand write logic\n regQueue.zipWithIndex.map({ case (entry, i) => {\n (entry, io.downstreamB.operandWrite.strb(i))\n }}).foreach({ case (entry, strb) => {\n\n when (strb) {\n entry.bits.operand.chi.WriteRespErr := io.downstreamB.operandWrite.bits.WriteRespErr\n }\n }})\n\n // AXI R operand write logic\n regQueue.zipWithIndex.map({ case (entry, i) => {\n (entry, io.downstreamR.operandAXIWrite.strb(i))\n }}).foreach({ case (entry, strb) => {\n\n when (strb) {\n entry.bits.operand.axi.Critical := io.downstreamR.operandAXIWrite.bits.Critical\n entry.bits.operand.axi.Count := io.downstreamR.operandAXIWrite.bits.Count\n }\n }})\n\n regQueue.zipWithIndex.map({ case (entry, i) => {\n (entry, io.downstreamR.operandCHIWrite.strb(i))\n }}).foreach({ case (entry, strb) => {\n\n when (strb) {\n entry.bits.operand.chi.ReadRespErr := io.downstreamR.operandCHIWrite.bits.ReadRespErr\n }\n }})\n /**/\n\n\n // upstream query logic\n io.upstreamRxDat.query.result := ValidMux(io.upstreamRxDat.query.en, \n ParallelMux(io.upstreamRxDat.query.strb.zip(regQueue.map(entry => {\n val result = Wire(Output(chiselTypeOf(io.upstreamRxDat.query.result)))\n result.valid := entry.valid\n result.WriteFull := entry.bits.operand.chi.WriteFull\n result.WritePtl := entry.bits.operand.chi.WritePtl\n result.ReadRespErr := entry.bits.operand.chi.ReadRespErr\n result.WriteRespErr := entry.bits.operand.chi.WriteRespErr\n result\n })))\n )\n\n\n // assertions & debugs\n /*\n * Port I/O: Debug\n */\n class DebugPort extends DebugBundle {\n val DoubleAllocation = Output(Vec(paramQueueCapacity, Bool()))\n val DanglingAXIWriteResponse = Output(Vec(paramQueueCapacity, Bool()))\n }\n\n @DebugSignal\n val debug = IO(new DebugPort)\n\n /*\n * @assertion DoubleAllocation\n * One slot in Transaction Queue must only be allocated once util next free.\n */\n (0 until paramQueueCapacity).foreach(i => {\n debug.DoubleAllocation(i) := io.allocate.en && io.allocate.strb(i) && regQueue(i).valid\n assert(!debug.DoubleAllocation(i),\n", "right_context": " })\n\n /*\n * @assertion DanglingAXIWriteResponse\n * Received Write Response on AXI B channel with no corresponding transaction.\n */\n (0 until paramQueueCapacity).foreach(i => {\n debug.DanglingAXIWriteResponse(i) := io.downstreamB.opDone.strb(i) &&\n (!regQueue(i).valid || !regQueue(i).bits.op.axi.WriteResponse.valid)\n assert(!debug.DanglingAXIWriteResponse(i),\n s\"received BRESP for non-exist transaction at [${i}]\")\n })\n}\n", "groundtruth": " s\"double allocation at [${i}]\")\n", "crossfile_context": ""}
{"task_id": "OpenNCB", "path": "OpenNCB/src/main/scala/openncb/logical/NCBUpstreamRXDAT.scala", "left_context": "package cc.xiangshan.openncb.logical\n\nimport chisel3._\nimport chisel3.util.UIntToOH\nimport chisel3.experimental.BundleLiterals._\nimport org.chipsalliance.cde.config.Parameters\nimport org.chipsalliance.cde.config.Field\nimport cc.xiangshan.openncb.WithNCBParameters\nimport cc.xiangshan.openncb.chi.WithCHIParameters\nimport cc.xiangshan.openncb.chi.opcode.CHISNFOpcodesDAT\nimport cc.xiangshan.openncb.chi.channel.CHIChannelRXDAT\nimport cc.xiangshan.openncb.chi.field.CHIFieldSize\nimport cc.xiangshan.openncb.chi.CHIConstants\nimport cc.xiangshan.openncb.debug.CompanionConnection\nimport cc.xiangshan.openncb.debug.DebugBundle\nimport cc.xiangshan.openncb.debug.DebugSignal\nimport cc.xiangshan.openncb.logical.chi.CHILinkActiveBundle\nimport cc.xiangshan.openncb.logical.chi.CHILinkActiveManagerRX\nimport cc.xiangshan.openncb.logical.chi.CHILinkCreditManagerRX\nimport cc.xiangshan.openncb.util.ValidMux\n\n\n/* \n* NCB Upstream Port RXDAT\n*/\nobject NCBUpstreamRXDAT {\n\n case class PublicParameters (\n )\n\n case object PublicParametersKey extends Field[PublicParameters]\n\n // companion connections\n @CompanionConnection\n def apply(uLinkActiveManager : CHILinkActiveManagerRX,\n uTransactionQueue : NCBTransactionQueue,\n uTransactionPayload : NCBTransactionPayload)\n (implicit p: Parameters) = {\n val u = Module(new NCBUpstreamRXDAT(uLinkActiveManager,\n uTransactionQueue,\n uTransactionPayload))\n\n // companion connection: LinkActiveManager\n u.io.linkState <> uLinkActiveManager.io.linkState\n\n // companion connection: NCBTransactionQueue\n u.io.queueUpstream <> uTransactionQueue.io.upstreamRxDat\n\n // companion connection: NCBTransactionPayload\n u.io.upstreamPayloadWrite <> uTransactionPayload.io.upstream.w\n\n u\n }\n}\n\nclass NCBUpstreamRXDAT(val uLinkActiveManager : CHILinkActiveManagerRX,\n val uTransactionQueue : NCBTransactionQueue,\n val uTransactionPayload : NCBTransactionPayload)\n (implicit val p: Parameters)\n extends Module with WithCHIParameters\n with WithNCBParameters\n with CHISNFOpcodesDAT {\n\n //\n def unsupportedCHIDataWidth(width: Int) =\n", "right_context": " \n\n // public parameters\n val param = p.lift(NCBUpstreamRXDAT.PublicParametersKey)\n .getOrElse(new NCBUpstreamRXDAT.PublicParameters)\n\n // local parameters\n protected def paramMaxBeatCount = CHIConstants.CHI_MAX_PACKET_DATA_BITS_WIDTH / paramCHI.dataWidth\n\n\n /*\n * Module I/O \n */\n val io = IO(new Bundle {\n // upstream RX DAT port (CHI domain)\n val rxdat = CHIChannelRXDAT()\n\n // from LinkActiveManagerRX\n @CompanionConnection\n val linkState = Flipped(chiselTypeOf(uLinkActiveManager.io.linkState))\n\n // upstream query from NCBTransactionQueue\n @CompanionConnection\n val queueUpstream = Flipped(chiselTypeOf(uTransactionQueue.io.upstreamRxDat))\n\n // upstream write to NCBTransactionPayload\n @CompanionConnection\n val upstreamPayloadWrite = Flipped(chiselTypeOf(uTransactionPayload.io.upstream.w))\n })\n\n\n // Upstream RXDAT Input Register\n protected val regRXDAT = RegInit(init = {\n val resetValue = Wire(io.rxdat.undirectedChiselType)\n resetValue.lcrdv := false.B\n resetValue.flitpend := false.B\n resetValue.flitv := false.B\n resetValue.flit := DontCare\n resetValue\n })\n\n io.rxdat.lcrdv := regRXDAT.lcrdv\n regRXDAT.flitpend := io.rxdat.flitpend\n regRXDAT.flitv := io.rxdat.flitv\n\n when (io.rxdat.flitv) {\n regRXDAT.flit := io.rxdat.flit\n }\n\n\n // Module: Link Credit Manager\n protected val uLinkCredit = Module(new CHILinkCreditManagerRX(\n paramMaxCount = paramNCB.outstandingDepth,\n paramInitialCount = paramNCB.outstandingDepth,\n paramCycleBeforeSend = 0,\n paramEnableMonitor = true\n ))\n\n regRXDAT.lcrdv := uLinkCredit.io.lcrdv\n\n uLinkCredit.io.linkState := io.linkState\n\n // credit loop back. no credit limit required on RXDAT channel.\n val uLinkCreditProvideBuffer = uLinkCredit.attachLinkCreditProvideBuffer()\n uLinkCreditProvideBuffer.io.linkCreditProvide := regRXDAT.flitv\n\n\n // Module: CHI Opcode Decode\n protected val uDecoder = Module(new Decoder(Seq(\n // ========================\n DataLCrdReturn,\n // ------------------------\n WriteDataCancel,\n // ------------------------\n NonCopyBackWrData\n // ========================\n ), true))\n\n uDecoder.io.valid := regRXDAT.flitv\n uDecoder.io.opcode := regRXDAT.flit.Opcode.get\n\n protected val logicTransactionData = uDecoder.is(NonCopyBackWrData)\n protected val logicTransactionCancel = uDecoder.is(WriteDataCancel)\n protected val logicLCrdReturn = uDecoder.is(DataLCrdReturn)\n\n protected val logicTxnIDToStrb = VecInit(\n UIntToOH(regRXDAT.flit.TxnID.get, paramNCB.outstandingDepth).asBools)\n\n \n // link credit consume on flit valid\n uLinkCredit.io.monitorCreditConsume := regRXDAT.flitv\n\n // link credit return by DataLCrdReturn\n uLinkCredit.io.monitorCreditReturn := logicLCrdReturn\n\n\n // transaction payload write\n io.upstreamPayloadWrite.en := logicTransactionData\n io.upstreamPayloadWrite.strb := logicTxnIDToStrb\n io.upstreamPayloadWrite.index := {\n if (paramMaxBeatCount == 4) {\n VecInit(UIntToOH(regRXDAT.flit.DataID.get, 4).asBools)\n } else if (paramMaxBeatCount == 2) {\n VecInit(UIntToOH(regRXDAT.flit.DataID.get(1, 1), 2).asBools)\n } else if (paramMaxBeatCount == 1) {\n VecInit(true.B)\n } else {\n unsupportedCHIDataWidth(paramCHI.dataWidth)\n }\n }\n io.upstreamPayloadWrite.data := regRXDAT.flit.Data.get\n io.upstreamPayloadWrite.mask := regRXDAT.flit.BE.get\n\n\n // transaction queue update\n io.queueUpstream.cancel.en := logicTransactionCancel\n io.queueUpstream.cancel.strb := logicTxnIDToStrb\n\n io.queueUpstream.writeData.en := logicTransactionData\n io.queueUpstream.writeData.strb := logicTxnIDToStrb\n\n // transaction queue query (for debug)\n io.queueUpstream.query.en := regRXDAT.flitv\n io.queueUpstream.query.strb := logicTxnIDToStrb\n\n\n // assertions & debugs\n class DebugPort extends DebugBundle {\n // flat\n val TxnIDNonExist = Output(Bool())\n val TxnIDOutOfRange = Output(Bool())\n val WriteCancelOnNonPtl = Output(Bool())\n val WriteCancelNotSupported = Output(Bool())\n val WriteFullWithParitalBE = Output(Bool())\n\n // submodule\n val linkCredit = chiselTypeOf(uLinkCredit.debug)\n val linkCreditProvide = chiselTypeOf(uLinkCreditProvideBuffer.debug)\n val decoder = chiselTypeOf(uDecoder.debug)\n }\n\n @DebugSignal\n val debug = IO(new DebugPort)\n\n debug.linkCredit <> uLinkCredit.debug\n debug.linkCreditProvide <> uLinkCreditProvideBuffer.debug\n debug.decoder <> uDecoder.debug\n\n /*\n * @assertion TxnIDNonExist\n * Received a flit with TxnID with-in outstanding depth range but did not exist.\n */\n debug.TxnIDNonExist := regRXDAT.flitv && !io.queueUpstream.query.result.valid\n assert(!debug.TxnIDNonExist,\n s\"non-exist TxnID (no related transaction found)\")\n\n /*\n * @assertion TxnIDOutOfRange\n * Received a flit with TxnID out of outstanding depth range. \n */\n debug.TxnIDOutOfRange := regRXDAT.flitv && regRXDAT.flit.TxnID.get >= paramNCB.outstandingDepth.U\n assert(!debug.TxnIDOutOfRange,\n s\"non-exist TxnID (out of outstanding depth)\")\n\n /*\n * @assertion WriteCancelOnNonPtl\n * 'WriteDataCancel' reply was only allowed for 'Write*Ptl'. \n */\n debug.WriteCancelOnNonPtl := regRXDAT.flitv && logicTransactionCancel && !io.queueUpstream.query.result.WritePtl\n assert(!debug.WriteCancelOnNonPtl,\n s\"WriteDataCancel only allowed for Write*Ptl\")\n\n /*\n * @assertion WriteCancelNotSupported\n * 'WriteDataCancel' not supported when 'writeCancelable = false' configured. \n */\n debug.WriteCancelNotSupported := regRXDAT.flitv && logicTransactionCancel && !paramNCB.writeCancelable.B\n assert(!debug.WriteCancelNotSupported,\n s\"WriteDataCancel not supported (writeCancelable = false)\")\n\n /* \n * @assertion WriteFullWithParitalBE\n * 'BE' must be all asserted for 'Write*Full'.\n */\n debug.WriteFullWithParitalBE := regRXDAT.flitv && io.queueUpstream.query.result.WriteFull && !regRXDAT.flit.BE.get.andR\n assert(!debug.WriteFullWithParitalBE,\n s\"partial BE on Write*Full\")\n}\n", "groundtruth": " throw new IllegalArgumentException(s\"unsupported CHI data width: ${width}\")\n", "crossfile_context": ""}
{"task_id": "OpenNCB", "path": "OpenNCB/src/main/scala/openncb/logical/chi/AbstractCHILinkActiveManager.scala", "left_context": "package cc.xiangshan.openncb.logical.chi\n\nimport chisel3._\nimport cc.xiangshan.openncb.chi.WithCHIParameters\nimport org.chipsalliance.cde.config.Parameters\n\n", "right_context": "\n", "groundtruth": "abstract class AbstractCHILinkActiveManager extends Module\n", "crossfile_context": ""}
{"task_id": "OpenNCB", "path": "OpenNCB/src/main/scala/openncb/logical/chi/CHILinkCreditManagerTX.scala", "left_context": "package cc.xiangshan.openncb.logical.chi\n\nimport chisel3._\nimport chisel3.util.log2Up\nimport chisel3.util.RegEnable\nimport chisel3.util.PopCount\nimport org.chipsalliance.cde.config.Parameters\nimport cc.xiangshan.openncb.chi.CHIConstants._\nimport cc.xiangshan.openncb.debug.DebugBundle\nimport cc.xiangshan.openncb.debug.DebugSignal\n\n\n/* \n* CHI Link Credit Manager for TX channels. \n* \n* * Supported Link-Layer states: STOP, ACT, RUN, DEACT.\n* \n* @param maxCount Specify the maximum grantable link credit count. By default,\n* {@see cc.xiangshan.openncb.chi.CHIConstants#CHI_MAX_REASONABLE_LINK_CREIDT_COUNT}\n*/\nclass CHILinkCreditManagerTX(val paramMaxCount : Int = CHI_MAX_REASONABLE_LINK_CREDIT_COUNT)\n extends AbstractCHILinkCreditManager {\n\n // local parameters\n protected def paramLinkCreditCounterWidth: Int = log2Up(paramMaxCount + 1)\n\n\n // variable checks\n require(paramMaxCount > 0, s\"maxCount > 0: maxCount = ${paramMaxCount}\")\n\n require(paramMaxCount <= CHI_MAX_REASONABLE_LINK_CREDIT_COUNT,\n", "right_context": "\n\n /*\n * Module I/O:\n *\n * @io input linkState : Link-layer State,\n * directly comes from LinkActiveManager in general.\n * \n * @io output linkCreditCount : Granted Link Credit Count, width depends on 'maxCount'.\n * @io output linkCreditAvailable : Granted Link Credit Available.\n * @io input linkCreditConsume : Link Credit Consume, consume one granted link credit \n * when asserted for sending a normal flit.\n * @io input linkCreditReturn : Link Credit Return, return one granted link credit\n * when asserted for sending a credit return flit.\n * \n * @io input lcrdv : Link Credit Valid, connects to TX*LCRDV.\n */\n val io = IO(new Bundle {\n // implementation local link-layer state signals\n val linkState = Input(CHILinkActiveBundle())\n\n // implementation local credit signals\n val linkCreditCount = Output(UInt(paramLinkCreditCounterWidth.W))\n val linkCreditAvailable = Output(Bool())\n\n val linkCreditConsume = Input(Bool())\n val linkCreditReturn = Input(Bool())\n\n // CHI link-layer signals\n val lcrdv = Input(Bool())\n })\n\n\n // input register of Link Credit Valid\n protected val regLcrdv = RegNext(next = io.lcrdv, init = false.B)\n\n // Link Credit counter\n protected val regLinkCreditCounter = RegInit(init = 0.U(paramLinkCreditCounterWidth.W))\n\n when (regLcrdv && !io.linkCreditConsume && !io.linkCreditReturn) {\n regLinkCreditCounter := regLinkCreditCounter + 1.U\n }.elsewhen (!regLcrdv && (io.linkCreditConsume || io.linkCreditReturn)) {\n regLinkCreditCounter := regLinkCreditCounter - 1.U\n }\n\n\n // module output\n io.linkCreditCount := regLinkCreditCounter\n io.linkCreditAvailable := regLinkCreditCounter =/= 0.U\n\n\n // assertions & debugs\n /*\n * Port I/O: Debug \n */\n class DebugPort extends DebugBundle {\n val LinkActiveStateNotOneHot = Output(Bool())\n val LinkCreditConsumeOutOfRun = Output(Bool())\n val LinkCreditReturnOutOfDeactivate = Output(Bool())\n val LinkCreditValidWhenLinkStop = Output(Bool())\n val LinkCreditOverflow = Output(Bool())\n val LinkCreditUnderflow = Output(Bool())\n }\n\n @DebugSignal\n val debug = IO(new DebugPort)\n\n /*\n * @assertion LinkActiveStateNotOneHot\n * The states from Link Active must be one-hot. \n */\n private val debugLogicLinkactivePopcnt = PopCount(Seq(\n io.linkState.stop,\n io.linkState.activate,\n io.linkState.run,\n io.linkState.deactivate\n ))\n debug.LinkActiveStateNotOneHot := debugLogicLinkactivePopcnt =/= 1.U\n assert(!debug.LinkActiveStateNotOneHot,\n \"linkactive state must be one-hot\")\n\n /* \n * @assertion LinkCreditConsumeOutOfRun\n * The consuming of a Link Credit must only occur in RUN state. \n */\n debug.LinkCreditConsumeOutOfRun := !io.linkState.run && io.linkCreditConsume\n assert(!debug.LinkCreditConsumeOutOfRun,\n \"link credit consume out of RUN state\")\n\n /* \n * @assertion LinkCreditReturnOutOfDeactivate\n * The returning of a Link Credit must only occur in DEACTIVATE state.\n */\n debug.LinkCreditReturnOutOfDeactivate := !io.linkState.deactivate && io.linkCreditReturn\n assert(!debug.LinkCreditReturnOutOfDeactivate,\n \"link credit return out of DEACTIVATE state\")\n \n /*\n * @assertion LinkCreditValidWhenLinkStop\n * The 'lcrdv' was not allowed to be asserted before Link ACTIVATE (In STOP state).\n */\n debug.LinkCreditValidWhenLinkStop := io.linkState.stop && io.lcrdv\n assert(!debug.LinkCreditValidWhenLinkStop,\n \"unexpected 'lcrdv' during link STOP\")\n\n /*\n * @assertion LinkCreditOverflow\n * The 'lcrdv' was not allowed to be asserted when the Link Credit received exceeded \n * the maximum number.\n */\n debug.LinkCreditOverflow := regLinkCreditCounter === paramMaxCount.U && regLcrdv\n assert(!debug.LinkCreditOverflow,\n s\"link credit overflow (with maximum ${paramMaxCount})\")\n\n /*\n * @assertion LinkCreditUnderflow\n * The 'linkCreditConsume' was not allowed to be asserted when there was no \n * Link Credit available in the current cycle.\n */\n debug.LinkCreditUnderflow := regLinkCreditCounter === 0.U && io.linkCreditConsume\n assert(!debug.LinkCreditUnderflow,\n \"link credit underflow\")\n}\n", "groundtruth": " s\"max maximum link credit count is ${CHI_MAX_REASONABLE_LINK_CREDIT_COUNT}, but ${paramMaxCount} configured\")\n", "crossfile_context": ""}
{"task_id": "OpenNCB", "path": "OpenNCB/src/main/scala/openncb/util/AddressableReadWritePort.scala", "left_context": "package cc.xiangshan.openncb.util\n\nimport chisel3._\n\n\n/*\n* Standardized Addressable Read Write Port (1 Write, 1 Read)\n*/\n", "right_context": "}\n", "groundtruth": "class AddressableReadWritePort(val addressWidth: Int, val dataWidth: Int) extends Bundle {\n\n // Write Port\n val w = new AddressableWritePort(addressWidth, dataWidth)\n", "crossfile_context": ""}
{"task_id": "OpenNCB", "path": "OpenNCB/src/main/scala/openncb/util/AddressableWritePort.scala", "left_context": "package cc.xiangshan.openncb.util\n\nimport chisel3._\n\n\n/*\n* Standardized Addressable Write Port\n*/\nclass AddressableWritePort(val addressWidth: Int, val dataWidth: Int) extends Bundle {\n\n", "right_context": "", "groundtruth": " // Write Port\n val en = Input(Bool())\n val addr = Input(UInt(addressWidth.W))\n val data = Input(UInt(dataWidth.W))\n", "crossfile_context": ""}
{"task_id": "OpenNCB", "path": "OpenNCB/src/main/scala/openncb/util/package.scala", "left_context": "package cc.xiangshan.openncb\n\nimport chisel3._\nimport chisel3.experimental.VecLiterals._\nimport chisel3.util.IrrevocableIO\nimport chisel3.util.Irrevocable\nimport chisel3.util.DecoupledIO\nimport chisel3.util.Decoupled\n\n\npackage object util {\n\n implicit class fromBooleanToVecLiteral(boolean: Boolean) {\n\n /*\n * Boolean to Bool Vec conversion, recommended style for constants. \n * \n * @param n Width of Bool Vec\n */\n", "right_context": "\n /*\n * Boolean to Bool Vec Literal conversion, recommended style for constants. \n * \n * * Typically used for Vec.Lit\n * \n * @param n Width of Bool Vec Literal\n */\n def BVecLit(n: Int): Vec[Bool] = \n Vec(n, Bool()).Lit(Seq.fill(n)(boolean.B).zipWithIndex.map(l => l.swap) : _*)\n }\n\n implicit class sliceBitExtractionForUInt(data: UInt) {\n \n /*\n * Create a sub-slice bit extraction of the UInt by 'offset' and 'width'.\n *\n * @param offset Offset of UInt slice extraction\n * @param width Width of UInt slice extraction\n */\n def extract(offset: Int, width: Int): UInt =\n data((offset + 1) * width - 1, offset * width)\n }\n\n implicit class irrevocableIOMapFunction[+T <: Data](gen: IrrevocableIO[T]) {\n\n /** Applies the supplied functor to the bits of this interface, returning a new\n * typed IrrevocableIO interface, with direciton of:\n * B = A.mapTo(B) : \n * B.bits := A.bits\n * B.valid := A.valid\n * A.ready := B.ready \n * \n * @param f The function to apply to this IrrevocableIO's 'bits' with return type B\n * @return a new IrrevocableIO of type B\n */\n def mapTo[B <: Data](f: T => B): IrrevocableIO[B] = {\n val _map_bits = f(gen.bits)\n val _map = Wire(Irrevocable(chiselTypeOf(_map_bits)))\n _map.bits := _map_bits\n _map.valid := gen.valid\n gen.ready := _map.ready\n _map\n }\n\n /** Applies the supplied functor to the bits of this interface, returning a new\n * typed IrrevocableIO interface, with direciton of:\n * B = A.mapFrom(B) : \n * A.bits := B.bits\n * A.valid := B.valid\n * B.ready := A.ready \n * \n * @param f The function to apply to this IrrevocableIO's 'bits' with return type B\n * @return a new IrrevocableIO of type B\n */\n def mapFrom[B <: Data](f: T => B): IrrevocableIO[B] = {\n val _map_bits = f(gen.bits)\n val _map = Wire(Irrevocable(chiselTypeOf(_map_bits)))\n _map.bits := _map_bits\n gen.valid := _map.valid\n _map.ready := gen.ready\n _map\n }\n }\n\n implicit class decoupledIOMapFunction[+T <: Data](gen: DecoupledIO[T]) {\n\n /** Applies the supplied functor to the bits of this interface, returning a new\n * typed DecoupledIO interface, with direciton of:\n * A.mapTo(B) : \n * B.bits := A.bits\n * B.valid := A.valid\n * A.ready := B.ready \n * \n * @param f The function to apply to this DecoupledIO's 'bits' with return type B\n * @return a new DecoupledIO of type B\n */\n def mapTo[B <: Data](f: T => B): DecoupledIO[B] = {\n val _map_bits = f(gen.bits)\n val _map = Wire(Decoupled(chiselTypeOf(_map_bits)))\n _map.bits := _map_bits\n _map.valid := gen.valid\n gen.ready := _map.ready\n _map\n }\n\n /** Applies the supplied functor to the bits of this interface, returning a new\n * typed DecoupledIO interface, with direciton of:\n * A.mapFrom(B) : \n * A.bits := B.bits\n * A.valid := B.valid\n * B.ready := A.ready \n * \n * @param f The function to apply to this DecoupledIO's 'bits' with return type B\n * @return a new DecoupledIO of type B\n */\n def mapFrom[B <: Data](f: T => B): DecoupledIO[B] = {\n val _map_bits = f(gen.bits)\n val _map = Wire(Decoupled(chiselTypeOf(_map_bits)))\n _map.bits := _map_bits\n gen.valid := _map.valid\n _map.ready := gen.ready\n _map\n }\n }\n}\n", "groundtruth": " def BVec(n: Int): Vec[Bool] = Vec(n, boolean.B)\n", "crossfile_context": ""}
{"task_id": "sv2chisel", "path": "sv2chisel/helpers/src/main/scala/tools/ModulePreset.scala", "left_context": "package sv2chisel.helpers.tools\n\nimport chisel3.experimental.{RunFirrtlTransform}\n\nimport firrtl._\nimport firrtl.ir._\nimport firrtl.annotations._\nimport firrtl.options.Dependency\n\nimport logger.LazyLogging\n\nimport scala.collection.mutable.{ArrayBuffer, HashSet}\n\ncase class ModulePresetAnnotation(target: ModuleTarget) extends SingleTargetAnnotation[ModuleTarget] {\n override def duplicate(n: ModuleTarget): ModulePresetAnnotation = this.copy(target = n)\n}\n\ncase class ModulePresetChiselAnnotation(target: ModuleTarget) extends RunFirrtlTransform {\n def transformClass = classOf[ModulePreset] // scalastyle:off public.methods.have.type\n def toFirrtl = ModulePresetAnnotation(target) // scalastyle:off public.methods.have.type\n}\n\n/** Convert Top Reset Type of Annotated Modules For each module with expected annotation `ModulePresetAnnotation`\n * - convert reset IO of any Type into AsyncResetType\n * - add `PresetAnnotation` on this IO\n *\n * Caveats:\n * - Expected result is seen only at the emission : no more reset signal\n * - Firrtl emission will only reflect modification of the Reset into AsyncResetType\n */\nclass ModulePreset extends Transform with DependencyAPIMigration with LazyLogging {\n\n override val prerequisites = firrtl.stage.Forms.HighForm\n override val optionalPrerequisiteOf = Seq(Dependency[ModuleRename])\n override def invalidates(a: firrtl.Transform) = false\n\n /** Recursively update all annotated modules\n * - annotated modules are removed from the moduleSet\n * - instance declared inside an annotated modules are added to the moduleSet\n * - run again until moduleSet is empty\n *\n * @param circuit\n * the circuit\n * @param annotations\n * all the annotations\n * @return\n * updated annotations\n */\n def update(\n cs: CircuitState,\n presetModules: Set[ModuleTarget],\n topPresetModules: Set[ModuleTarget]\n ): CircuitState = {\n\n // Annotations to be appended and returned as result of the transform\n val annos = ArrayBuffer(cs.annotations.toSeq:_*)\n val moduleSet = HashSet(presetModules.toSeq:_*)\n val circuitTarget = CircuitTarget(cs.circuit.main)\n\n /** Update annotated module\n * - convert reset into AsyncResetType\n * - add preset annotation for top level port only (useless to add for all)\n */\n def processModule(m: DefModule): DefModule = {\n val moduleTarget = circuitTarget.module(m.name)\n\n def processPorts(port: Port): Port = {\n if (port.name == \"reset\") {\n logger.debug(s\"[debug] Update reset of ${m.name}\")\n val target = moduleTarget.ref(port.name)\n if (topPresetModules.contains(moduleTarget)) annos += PresetAnnotation(target)\n port.copy(tpe = AsyncResetType)\n } else {\n port\n }\n }\n\n def processStatements(stmt: Statement): Statement = {\n stmt match {\n case i: WDefInstance =>\n logger.debug(\n", "right_context": " )\n moduleSet += circuitTarget.module(i.module)\n i\n case _ => stmt.mapStmt(processStatements)\n }\n }\n\n if (moduleSet.contains(moduleTarget)) {\n moduleSet -= moduleTarget\n m.mapPort(processPorts).mapStmt(processStatements)\n } else {\n m\n }\n }\n // ensure that modules are processed in hierarchy order (avoid multiple runs)\n val modules = cs.circuit.modules.reverse.map(processModule)\n val circuit = cs.circuit.copy(modules = modules.reverse)\n val result = cs.copy(circuit = circuit, annotations = annos.toSeq)\n if (moduleSet.isEmpty) {\n result\n } else if(moduleSet.toSet == presetModules) {\n logger.error(s\"[fatal] Aborting module preset update! ${presetModules.map(_.prettyPrint()).mkString(\",\")}\")\n logger.error(s\"[fatal] Expect further errors if the top-level reset cannot be found.\")\n logger.error(s\"[fatal] Did you specify the right ModuleTarget?\")\n result\n } else {\n logger.warn(\"[info] Re-running ModulePreset Propagation\")\n update(result, moduleSet.toSet, topPresetModules)\n }\n }\n\n def execute(state: CircuitState): CircuitState = {\n // Collect all user-defined PresetAnnotation\n val presets = state.annotations\n .collect { case m: ModulePresetAnnotation => m }\n .groupBy(_.target)\n .keySet\n // No ModulePresetAnnotation => no need to walk the IR\n if (presets.size == 0) {\n state\n } else {\n update(state, presets, presets)\n }\n }\n}\n", "groundtruth": " s\"[debug] Registering instance ${i.name} of ${i.module} for AsyncReset Propagation\"\n", "crossfile_context": ""}
{"task_id": "sv2chisel", "path": "sv2chisel/helpers/src/test/scala/bundleconvertSpec.scala", "left_context": "// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n// Copyright 2020 The sv2chisel Authors. All rights reserved.\n\npackage sv2chiselHelpersTests\n\nimport sv2chiselHelpersTests.utils._\nimport sv2chisel.helpers.bundleconvert._\n\nimport chisel3._\nimport chisel3.stage.ChiselStage\n\nimport org.scalatest._\nimport flatspec._\n\nclass bundleconvertSpec extends AnyFlatSpec with VerilogMatchers {\n val setTestRunDir = Array(\"--target-dir\", \"test_run_dir\")\n\n behavior of \"BundleSubRangeAccess\" \n \n it should \"allow field extraction by range\" in {\n class SubRangeBundle() extends RawModule {\n class MyBundle extends Bundle {\n val a = Bool() // index (7, 7)\n val b = Bool() // index (6, 6)\n val c = UInt(5.W) // index (5, 1)\n val d = Bool() // index (0,0)\n }\n", "right_context": " out(0,0) := true.B\n out(5,1) := 4.U\n out(6,6) := true.B\n out(7,7) := false.B\n }\n val verilog = (new ChiselStage()).emitVerilog(new SubRangeBundle(), setTestRunDir)\n\n verilog should containStr (\"assign out_a = 1'h0;\")\n verilog should containStr (\"assign out_b = 1'h1;\")\n verilog should containStr (\"assign out_c = 5'h4;\")\n verilog should containStr (\"assign out_d = 1'h1;\")\n }\n\n}\n", "groundtruth": " val out = IO(Output(new MyBundle))\n", "crossfile_context": ""}
{"task_id": "sv2chisel", "path": "sv2chisel/src/main/scala/sv2chisel/ir/ExpressionToLiteral.scala", "left_context": "// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n// Copyright 2020 The sv2chisel Authors. All rights reserved.\n\npackage sv2chisel\npackage ir\n\nimport logger.{InfoLogging}\nimport org.antlr.v4.runtime.{CommonTokenStream}\n\n\npackage object expressionToLiteral {\n implicit def expToLiteral(e: Expression) = new ExpressionToLiteral(e)\n}\n\nclass ExpressionToLiteral(e: Expression) extends InfoLogging {\n var currentSourceFile : Option[SourceFile] = None\n var currentStream : Option[CommonTokenStream] = None\n implicit def svnode2Interval(n:SVNode): Interval = n.tokens\n \n val ui = UndefinedInterval\n \n def toLiteralOption(implicit currentSourceFile : Option[SourceFile], currentStream : Option[CommonTokenStream]): Option[Expression] = {\n this.currentSourceFile = currentSourceFile\n this.currentStream = currentStream\n e match {\n case n: Number => \n n.getBigInt match {\n case Some(bg) if (bg < 0) => \n n.base match {\n case NumberDecimal => Some(SIntLiteral(n.tokens, bg, n.width))\n case b =>\n warn(n, s\"[fixable] Unable to convert negative numbers with base $b to Literal\")\n None\n }\n \n case Some(bg) => Some(UIntLiteral(n.tokens, bg, n.width, n.base))\n \n case _ =>\n warn(n, s\"Unable to convert ${n.serialize} to BigInt\")\n None\n }\n \n case r: Reference => \n r.tpe match {\n case i:IntType =>\n warn(r, s\"Tech Debt: casting IntType to UIntType (TODO: proper signed management)\")\n Some(DoCast(r.tokens, e, HwExpressionKind, UIntType(UndefinedInterval, UnknownWidth(), i.base)))\n case _ => \n trace(r, s\"Reference with tpe: ${r.tpe.serialize}\")\n None\n }\n \n", "right_context": "", "groundtruth": " case _ => \n trace(e, s\"Cannot convert expression ${e.serialize} to Literal\")\n None\n }\n", "crossfile_context": ""}
{"task_id": "sv2chisel", "path": "sv2chisel/src/main/scala/sv2chisel/transforms/FlowReferences.scala", "left_context": "// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n// Copyright 2020 The sv2chisel Authors. All rights reserved.\n\n/*\n All this transform is to be redone\n - SourceFlow = RHS = some element being read, used / assign from\n - SinkFlow = LHS = some element being written / assign towards\n\n To be done in the following way\n \n NOTE: important, references shall be managed as in inferuints:\n with virtual references such as vec[_], matrix[_][_] \n \n NOTE: due to repeat, push warning into a Set, so they are all printed at once at \n the end of the the transform, without duplicate\n could use a \"done\" dictionary to lookup for and do not process/print msg for \"done\" refs \n \nRepeat until updated map is empty\n - clear updated map\n - Keep for each reference R: \n - Seq[A: assignations (R as SinkFlow)]\n - Seq[B usages (R as SourceFlow)]\n - Seq[C Unknown: R as potential Sink OR Flow] (only assigns in IOs of DefInstance)\n => NOTE: Pass#1 this is already a process path because assignations can be applied in place, as for source usage\n => NOTE: no need to count again / modify for ref in \"DONE\" \n \n - Analyse results: (A, B, C) match\n - (Seq(), Seq(), Seq()) => warn unused reference\n - (Seq(), Seq(), Seq(e)) => warn cannot conclude anything but treat as if R is assigned by e \n - (Seq(), Seq(), s) => warn cannot conclude anything and do not update anything\n - (Seq(), s, Seq(e)) => e is the place where R should be referenced as Sink (assigned by submodule output)\n - (Seq(e), _, e:_) if assumeValidVerilog => foreach elt in e => R should be treated as source in elt\n - (Seq(e), _, e:_) => warn cannot conclude anything\n - (s, Seq(), Seq()) => warn declared & assigned but left unconnected\n - (Seq(), s, Seq()) => warn undeclared ref\n - (Seq(e), s, Seq()) => // nothing to do \n - (s, _, e:_) => if asssumeValidVerilog => warn multiple assigns but assume R as Source in each elt of e\n - (s, _, e:_) => debug nothing can be deduced for now for r flow in elmts of e\n \n - Apply update\n - this might be the tricky one => how to find the right usage ?\n - well it is actually dead simple: all Reference to R in updated map with Unknown FLow in DefInstance Assign are to be updated.\n \n*/\n\n\npackage sv2chisel\npackage transforms\n\nimport sv2chisel.ir._\nimport sv2chisel.Utils._\n\nimport collection.mutable.{HashMap, HashSet, ArrayBuffer, LinkedHashMap}\n\nclass FlowReferences(\n val options: TranslationOptions, \n val assumeValidVerilog: Boolean = true) extends DescriptionBasedTransform {\n private val ui = UndefinedInterval\n \n class ModuleStore() {\n class ModulePorts(val name: String){\n val declaration = new LinkedHashMap[String, Assign]()\n val namedPorts = new LinkedHashMap[String, Assign]()\n val noNamePorts = new ArrayBuffer[Assign]()\n \n private def getPortsKind(p: Seq[Assign], expected: Option[Assign]): Assign = {\n (p, expected) match {\n case (Seq(), None) => throwInternalError(\"Unexpected empty port list\")\n case (Seq(), Some(a)) => a\n case (s, None) => getPortsKind(s.tail, Some(s.head))\n case (s, Some(e)) =>\n val exp = (e, s.head) match {\n case (_: NamedAssign, _:NamedAssign) => e\n case (_: NoNameAssign, _:NoNameAssign) => e\n case _ => throwInternalError(s\"Incompatible parameter list: got both $e and ${s.head} in same list.\")\n }\n getPortsKind(s.tail, Some(exp))\n }\n }\n \n private def getSeqFlows(s: Seq[Assign], ports: Seq[Assign]): Seq[Flow] = {\n val missingEntries = ports.size - s.size\n val ref = s ++ Seq.fill(missingEntries)(NoNameAssign(ui, UndefinedExpression(), UnknownFlow))\n\n ref.zip(ports).map(t => {\n (t._1.flow, t._2.flow) match {\n case (UnknownFlow, f2) => f2 \n case (f1, UnknownFlow) => f1\n case (f1, f2) if (f1 == f2) => f1\n case (f1, f2) if (f1 != f2) => \n critical(t._2, s\"Unexpected direction for port ${t._2} where ${t._1} was expected. (Expression are given for context, only mismatching Flows are causing this message)\")\n f1\n }\n })\n }\n \n private def getNamedFlows(s: LinkedHashMap[String, Assign], ports: Seq[Assign]): Seq[Flow] = {\n ports.map(p => {\n p match {\n case na: NamedAssign => \n s.get(na.name) match {\n case Some(a) => a.flow\n case None => UnknownFlow\n }\n case _ => throwInternalError(\"Should not be here\") \n }\n })\n }\n \n def declare(ports: Seq[Port]): Unit = {\n ports match {\n case Seq() => info(s\"Declaring actual port directions for module $name\")\n case s => info(s.head, s\"Declaring actual port directions for module $name\")\n }\n \n ports.foreach(p => {\n val flow = p.direction match {\n case _:Input => SourceFlow // NOTE: the connected expr shall be a source flow \n case _:Output => SinkFlow\n case _ => UnknownFlow\n }\n declaration += ((p.name, NamedAssign(ui, p.name, UndefinedExpression(), flow)))\n })\n }\n \n def registerInference(ports: Seq[Assign]) : Unit = {\n // do not risk error while the result won't be used anyway\n if(declaration.isEmpty){\n getPortsKind(ports, None) // just ensure they are all the same type \n ports.zipWithIndex.map(t => {\n t._1 match {\n case na: NamedAssign => \n (namedPorts.get(na.name), na.flow) match {\n // nothing to update\n case (_, UnknownFlow) => \n case (Some(a), f) if(a.flow == f) => \n \n // DO UPDATE\n case (Some(NamedAssign(_, _, _, UnknownFlow, _ ,_, _)), _) => namedPorts(na.name) = na\n case (None, _) => namedPorts += ((na.name, na))\n \n // ERROR on defined flow override\n case (Some(a), f) if(a.flow != f) => \n critical(na, s\"Ignored attempt to update direction for port ${na.name} from ${a.flow} to $f.\")\n }\n \n case na: NoNameAssign => \n (noNamePorts(t._2), na.flow) match {\n // nothing to update\n case (_, UnknownFlow) => \n case (a, f) if(a.flow == f) =>\n \n // DO UPDATE\n case (NoNameAssign(_, _, UnknownFlow, _, _, _, _), _) => \n if(t._2 < noNamePorts.size) {\n noNamePorts(t._2) = na\n } else { \n noNamePorts += na\n }\n \n // ERROR on defined flow override\n case (a, f) if(a.flow != f) => \n critical(na, s\"Ignored attempt to update direction for port ${t._2} from ${a.flow} to $f.\")\n }\n case _ => // do nothing\n }\n })\n }\n }\n \n def getExpectedFlows(ports: Seq[Assign]): Seq[Flow] = {\n //first look for actual module declaration\n val kind = getPortsKind(ports, None)\n (declaration.isEmpty, namedPorts.isEmpty, noNamePorts.isEmpty, kind) match {\n case (false, _, _, _: NamedAssign) => getNamedFlows(declaration, ports)\n case (false, _, _, _: NoNameAssign) => getSeqFlows(declaration.values.toSeq, ports)\n case (_, false, _, _: NamedAssign) => getNamedFlows(namedPorts, ports)\n case (_, false, _, _: NoNameAssign) => getSeqFlows(namedPorts.values.toSeq, ports)\n case (_, _, false, _: NamedAssign) => ports.map(_ => UnknownFlow)\n case (_, _, false, _: NoNameAssign) => getSeqFlows(noNamePorts.toSeq, ports)\n case _ => ports.map(_ => UnknownFlow)\n }\n }\n }\n \n private val store = new HashMap[String, ModulePorts]\n \n def register(m: DefModule): Unit = {\n store.get(m.name) match {\n case Some(m@_) => throwInternalError(s\"Unexpected duplicated declaration for module ${m.name}\")\n case None =>\n val mp = new ModulePorts(m.name)\n mp.declare(m.ports)\n store += ((m.name, mp))\n }\n }\n \n def registerInference(name: String, ports: Seq[Assign]) : Unit = {\n store.get(name) match {\n case Some(mp) => mp.registerInference(ports)\n case None => \n val mp = new ModulePorts(name)\n mp.registerInference(ports)\n store += ((name, mp))\n }\n }\n \n def getExpectedFlows(name: String, ports: Seq[Assign]): Seq[Flow] = { // Assign or flow ?\n store.get(name) match {\n case Some(mp) => mp.getExpectedFlows(ports)\n case None => ports.map(_ => UnknownFlow)\n }\n }\n }\n val moduleStore = new ModuleStore()\n \n override val preprocessDescription = Some(((d: Description) => {\n d match {\n case m: DefModule => moduleStore.register(m); m\n case d => d\n }\n }))\n \n def processDescription(d: Description): Description = {\n d match {\n case m: Module => processModule(m)\n case d => d\n }\n }\n \n def processModule(m: DefModule): DefModule = {\n val extAssigned = new HashMap[String, Boolean]()\n val inAssigned = new HashSet[String]()\n val implicitSources = new HashSet[String]()\n val wasInferredSink = new HashSet[String]()\n var newImplicitSources = false\n \n // Note: only useful for lhs refs (no doPrim operations except ignored concat)\n def getRef(e: Expression): Option[Reference] = {\n e match {\n case r: Reference => Some(r)\n case s: SubField => getRef(s.expr) // assuming all subfield with same dir\n case s: SubIndex => getRef(s.expr)\n case s: SubRange => getRef(s.expr)\n case _: Concat => None\n // most of it\n case _ => None\n }\n }\n \n // first pass => hashmap with assignation to references\n def visitConnect(c: Connect): Unit = {\n getRef(c.loc) match {\n case None =>\n case Some(r) => \n val ref = r.serialize\n \n extAssigned.get(ref) match {\n case Some(r@_) => // nothing to do\n // registering as inAssigned => not as strong as extAssigned\n case None => inAssigned += ref\n }\n }\n }\n \n def visitDefParam(l: DefParam): Unit = {\n if (extAssigned.contains(l.name)) {\n warn(l, s\"Multiple definitions of ${l.name}\")\n } else {\n extAssigned += ((l.name, true))\n }\n }\n \n def visitStatement(s: Statement): Unit = {\n s match {\n case c: DefParam => visitDefParam(c)\n case c: Connect => visitConnect(c)\n case p: Port => visitPort(p)\n case _ => s.foreachStmt(visitStatement)\n }\n }\n \n def visitPort(p: Port): Unit = {\n if (extAssigned.contains(p.name)) {\n warn(p, s\"Multiple definitions of ${p.name}\")\n } else {\n p.direction match {\n case _: Output => extAssigned += ((p.name, false))\n case _ => extAssigned += ((p.name, true))\n }\n }\n }\n \n // TO DO : we are missing includes here ...\n m.foreachParam(visitDefParam)\n m.foreachStmt(visitStatement)\n \n def getFlow(r: Reference, expected: Option[Flow]): Flow = {\n val ref = r.serialize\n val inAssign = inAssigned.contains(ref)\n val imply = implicitSources.contains(ref)\n val sink = wasInferredSink.contains(ref) // assume file ordering\n \n (extAssigned.get(ref), inAssign, imply, sink, expected) match {\n case (None, false, false, false, None) => UnknownFlow\n \n // back-propagated sink/source over previously UnknownFlow\n case (None, false, false, false, Some(SinkFlow)) => wasInferredSink += ref; SinkFlow\n \n // reuse of elsewhere used as sink signal\n case (None, false, _, true, None) => SourceFlow\n \n // submodule output \n case (None, false, true, false, None) => \n wasInferredSink += ref\n SinkFlow \n \n case (None, true, true, _, None) => throwInternalError(\"Impossible by design\")\n case (None, true, false, _, None) => SourceFlow\n // known inputs & params \n case (Some(true), _, _, _, Some(SinkFlow)) => SinkFlow // basically all connects\n case (Some(true), _, _, _, _) => SourceFlow\n \n // known outputs\n case (Some(false), _, _, _, Some(f)) => f // outputs signal used in computations \n case (Some(false), _, _, _, _) => SinkFlow\n \n // implicit source (from doprim, call or cast)\n case (None, false, false, _, Some(SourceFlow)) if (assumeValidVerilog) => \n debug(r, s\"Adding implicit source $ref\")\n implicitSources += ((ref))\n newImplicitSources = true\n SourceFlow\n \n case (None, _, _, _, Some(f)) => f\n }\n }\n def reduceFlow(f1: Flow, f2: Flow): Flow = { \n (f1, f2) match {\n case (SourceFlow, SourceFlow) => SourceFlow \n case (SinkFlow, SinkFlow) => SinkFlow \n case (SinkFlow, UnknownFlow) if(assumeValidVerilog) => SinkFlow \n case (UnknownFlow, SinkFlow) if(assumeValidVerilog) => SinkFlow \n case (SourceFlow, UnknownFlow) if(assumeValidVerilog) => SourceFlow \n case (UnknownFlow, SourceFlow) if(assumeValidVerilog) => SourceFlow \n case _ => UnknownFlow\n }\n }\n \n def backPropagateFlow(e: Expression, f: Flow): Expression = {\n e match {\n case r: Reference => \n (r.flow, f) match {\n", "right_context": " r.copy(flow = f)\n case s: SubField => \n val expr = backPropagateFlow(s.expr, f)\n s.copy(expr = expr, flow = expr.flow)\n \n case s: SubIndex =>\n val expr = backPropagateFlow(s.expr, f)\n s.copy(expr = expr, flow = expr.flow)\n \n case s: SubRange => \n val expr = backPropagateFlow(s.expr, f)\n s.copy(expr = expr, flow = expr.flow)\n \n case _ => e \n }\n }\n \n // SECOND PASS => apply flow to expressions\n var instCount = 0\n def processExpression(e: Expression, expected: Option[Flow]): Expression = {\n e match {\n case u: UndefinedExpression => \n // important for Port Emission (connecting DontCare to Undefined Inputs)\n expected match {\n case Some(f) => u.copy(flow = f)\n case _ => u\n }\n \n case r: Reference => r.copy(flow = getFlow(r, expected))\n case s: SubField => \n // flows should be applied only to bundle fields not whole bundle\n // additionnaly direction should be involved ? (not sure it is useful for verilog)\n // Note that for verilog this should be fine => in any field of a struct is assigned it means the whole strcut should be assigned in the same place\n // Edge case are definitely not covered though\n // struct defined within module ; 1 field assigned from input port another assigned from submodule output\n val expr = processExpression(s.expr, expected)\n s.copy(expr = expr, flow = expr.flow)\n \n case s: SubIndex =>\n // above notice concerning bundle somehow apply also here ...\n // definitely need to introduce some kind of reference target management\n val index = processExpression(s.index, Some(SourceFlow))\n val expr = processExpression(s.expr, expected)\n s.copy(expr = expr, index = index, flow = expr.flow)\n \n case s: SubRange => \n // above notice concerning bundle somehow apply also here ...\n // definitely need to introduce some kind of reference target management\n val expr = processExpression(s.expr, expected)\n val left = processExpression(s.left, Some(SourceFlow))\n val right = processExpression(s.right, Some(SourceFlow))\n s.copy(expr = expr, left = left, right = right, flow = expr.flow)\n \n case d: DoPrim => // all ops work the same\n // in valid verilog all operand of a primary operation are assumed to be SourceFlow\n // assuming valid verilog: use this information to back propagate info to reference\n val ar = d.args.map(processExpression(_, Some(SourceFlow)))\n ar.map(_.flow).reduce(reduceFlow) match {\n case SourceFlow => // fine \n case SinkFlow => critical(d, s\"Ignored SinkFlow infered for primary op : ${d.serialize}\")\n case _ => warn(d, s\"Unable to infer flow for ${d.serialize}. Note: Primary operator are always SourceFlow.\")\n }\n d.copy(args= ar)\n \n case c: Concat =>\n val ar = c.args.map(processExpression(_, expected))\n val flow = ar.map(_.flow).reduce(reduceFlow)\n // back propagate over UnknownFlow if any \n val backPropagatedArgs = (expected, flow) match {\n case (None, UnknownFlow) => ar\n case (None, SinkFlow) => ar.map(backPropagateFlow(_, SinkFlow))\n case _ => ar\n }\n c.copy(args= backPropagatedArgs, flow = flow)\n \n case a: NamedAssign => \n val expr = processExpression(a.expr, expected)\n a.copy(expr = expr, flow = expr.flow)\n \n case a: NoNameAssign => \n val expr = processExpression(a.expr, expected)\n a.copy(expr = expr, flow = expr.flow)\n \n case d: DoCast => \n d.copy(expr = processExpression(d.expr, Some(SourceFlow)))\n \n case c: ComplexValues => \n c.mapExpr(e => processExpression(e, Some(SourceFlow)))\n \n case _ => trace(e, s\"ignored flow propagation for ${e.serialize}\"); e\n }\n }\n \n def processAssign(a: Assign, expected: Option[Flow]): Assign = {\n a match {\n case _: AutoAssign => a\n case na: NamedAssign => \n val expr = processExpression(na.expr, expected)\n na.copy(expr = expr, flow = expr.flow)\n case na: NoNameAssign => \n val expr = processExpression(na.expr, expected)\n na.copy(expr = expr, flow = expr.flow)\n }\n }\n \n def processInstance(d: DefInstance): DefInstance = {\n instCount +=1\n val params = d.paramMap.map(processAssign(_, Some(SourceFlow)))\n // the whole trick to auto infer ports directions lies here \n // we need not to erase what was decided previously\n val exp = moduleStore.getExpectedFlows(d.module.serialize, d.portMap)\n val ports = d.portMap.zip(exp).map(t => {\n (t._1.flow, t._2) match {\n case (UnknownFlow, UnknownFlow) => processAssign(t._1, None) \n case (UnknownFlow, f) => processAssign(t._1, Some(f))\n case _ => t._1\n }\n })\n moduleStore.registerInference(d.module.serialize, ports)\n d.copy(paramMap = params, portMap = ports)\n }\n \n def processStatement(s: Statement): Statement = {\n s match {\n case c: Connect =>\n val loc = processExpression(c.loc, Some(SinkFlow))\n val expr = processExpression(c.expr, Some(SourceFlow))\n c.copy(loc = loc, expr = expr)\n \n case d: DefInstance => processInstance(d) \n \n case _ => s.mapExpr(processExpression(_, Some(SourceFlow))).mapStmt(processStatement)\n }\n }\n \n var result: DefModule = m.mapStmt(processStatement)\n var maxIter = 3\n while((newImplicitSources || !wasInferredSink.isEmpty) && maxIter > 0){\n info(m, s\"Running FlowReference Transform another time on module ${m.name}\")\n newImplicitSources = false\n instCount = 0\n wasInferredSink.foreach(ref => extAssigned += ((ref, true)))\n wasInferredSink.clear()\n maxIter -= 1\n result = result.mapStmt(processStatement)\n }\n if (newImplicitSources || !wasInferredSink.isEmpty) {\n critical(m, \"Unable to completely achieve FlowReference Transform within the 4 successives runs.\")\n }\n \n def debugPrintInstances(s:Statement): Unit = {\n s match {\n case d: DefInstance => debug(d, d.serialize)\n case _ => s.foreachStmt(debugPrintInstances)\n }\n }\n if(instCount > 0){\n debug(s\"### Detail of instances in module ${result.name}: \")\n result.foreachStmt(debugPrintInstances)\n } else {\n debug(s\"### No Instances in module ${result.name}.\")\n }\n result\n }\n}", "groundtruth": " case (UnknownFlow, SinkFlow) => \n wasInferredSink += (r.serialize)\n debug(e, s\" > Recording that ${r.serialize} was used as sink\")\n", "crossfile_context": ""}
{"task_id": "sv2chisel", "path": "sv2chisel/src/test/scala/BlackBoxSpec.scala", "left_context": "// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n// Copyright 2020 The sv2chisel Authors. All rights reserved.\n\npackage sv2chiselTests\n\nimport sv2chiselTests.utils._\nimport logger._\nimport sv2chisel.{TranslationOptions, ChiselizerOptions}\n\nclass BlackBoxSpec extends Sv2ChiselSpec {\n Logger.setLevel(LogLevel.Warn)\n \n behavior of \"BlackBox\" \n \n \n it should \"work with inline ports with resource\" in {\n\n val bb = wrapInModule(\"\"\"\n |input [7:0] i_a;\n |input [7:0] i_b;\n |input i_c;\n |output [7:0] o;\n |output [7:0] o_v;\n |\n |assign o = sum(i_a, i_b);\n |assign o_v = sum(i_a, i_c);\n \"\"\".stripMargin,\n \"my_black_box\"\n )\n \n val main = wrapInModule(\"\"\"\n |input [7:0] i_a;\n |input [7:0] i_b;\n |input i_c;\n |output [7:0] o;\n |output [7:0] o_v;\n |\n |my_black_box inst(\n | .i_a(i_a),\n | .i_b(i_b),\n | .i_c(i_c),\n | .o(o),\n | .o_v(o_v)\n |);\n \"\"\".stripMargin\n )\n val options = TranslationOptions().copy(\n chiselizer = ChiselizerOptions().copy(baseBlackboxRessourcePath = Some(\"./test_run_dir/resources/\"))\n )\n val result = emit(bb, main, Some(\"src/main/resources/project/hdl/my_module.sv\"), options)\n \n result should containStr ( \"import chisel3.util.HasBlackBoxResource\")\n result should containStr ( \"class my_black_box() extends BlackBox with HasBlackBoxResource {\")\n result should containStr ( \n \"val io = IO(new Bundle {\",\n \"val i_a = Input(UInt(8.W))\",\n \"val i_b = Input(UInt(8.W))\",\n \"val i_c = Input(Bool())\",\n \"val o = Output(UInt(8.W))\",\n \"val o_v = Output(UInt(8.W))\",\n \"})\"\n )\n \n result should containStr ( \n \"val inst = Module(new my_black_box)\",\n \"inst.io.i_a := i_a\",\n \"inst.io.i_b := i_b\",\n \"inst.io.i_c := i_c\",\n \"o := inst.io.o\",\n \"o_v := inst.io.o_v\"\n )\n }\n \n it should \"work with inline ports without ressource\" in {\n\n val bb = wrapInModule(\"\"\"\n |input [7:0] i_a;\n |input [7:0] i_b;\n |input i_c;\n |output [7:0] o;\n |output [7:0] o_v;\n |\n |assign o = sum(i_a, i_b);\n |assign o_v = sum(i_a, i_c);\n \"\"\".stripMargin,\n \"my_black_box\"\n )\n \n val main = wrapInModule(\"\"\"\n |input [7:0] i_a;\n |input [7:0] i_b;\n |input i_c;\n |output [7:0] o;\n |output [7:0] o_v;\n |\n |my_black_box inst(\n | .i_a(i_a),\n | .i_b(i_b),\n | .i_c(i_c),\n | .o(o),\n | .o_v(o_v)\n |);\n \"\"\".stripMargin\n )\n\n val result = emit(bb, main, None, TranslationOptions())\n \n result shouldNot containStr ( \"import chisel3.util.HasBlackBoxResource\")\n result should containStr ( \"class my_black_box() extends BlackBox {\")\n result should containStr ( \n \"val io = IO(new Bundle {\",\n \"val i_a = Input(UInt(8.W))\",\n \"val i_b = Input(UInt(8.W))\",\n \"val i_c = Input(Bool())\",\n \"val o = Output(UInt(8.W))\",\n \"val o_v = Output(UInt(8.W))\",\n \"})\"\n )\n \n result should containStr ( \n \"val inst = Module(new my_black_box)\",\n \"inst.io.i_a := i_a\",\n \"inst.io.i_b := i_b\",\n \"inst.io.i_c := i_c\",\n \"o := inst.io.o\",\n \"o_v := inst.io.o_v\"\n )\n }\n \n it should \"work with vec ports\" in {\n\n val bb = wrapInModule(\"\"\"\n |input [3:0][7:0] i;\n |output [3:0][7:0] o;\n |\n |assign o = i;\n \"\"\".stripMargin,\n \"my_black_box\"\n )\n \n val main = wrapInModule(\"\"\"\n |input [3:0][7:0] i;\n |output [3:0][7:0] o;\n |\n |my_black_box inst(\n | .i(i),\n | .o(o)\n |);\n \"\"\".stripMargin\n )\n\n val result = emit(bb, main, None, TranslationOptions())\n \n result shouldNot containStr ( \"import chisel3.util.HasBlackBoxResource\")\n result should containStr ( \"class my_black_box() extends RawModule {\",\n \"override def desiredName = \\\"my_black_boxWrapper\\\"\",\n \"\",\n \"val io = IO(new Bundle {\",\n \"val i = Input(Vec(4, UInt(8.W)))\",\n \"val o = Output(Vec(4, UInt(8.W)))\",\n \"})\"\n )\n \n result should containStr ( \n \"val inst = Module(new my_black_box)\",\n \"inst.io.i := i\",\n \"o := inst.io.o\"\n )\n result should containStr ( \"class my_black_boxBB() extends BlackBox {\",\n \"override def desiredName = \\\"my_black_box\\\"\",\n \"val io = IO(new Bundle {\",\n \"val i = Input(UInt((4*8).W))\",\n \"val o = Output(UInt((4*8).W))\",\n \"})\"\n )\n }\n \n it should \"work with parameters and ports functional-style\" in {\n\n val bb = \"\"\"\n |module my_black_box#(\n | parameter TESTI = 1,\n | parameter TESTS = \"TRUE\",\n | parameter TEST\n |)(\n | input a,\n | output b\n |);\n |assign b = TEST ? a : '0;\n |endmodule\n \"\"\".stripMargin\n \n val main = wrapInModule(\"\"\"\n |input a;\n |output b;\n |\n |my_black_box #(.TEST(1)) inst (\n | .a(a),\n | .b(b)\n |);\n \"\"\".stripMargin\n )\n\n val result = emit(bb, main, None, TranslationOptions())\n val q = \"\\\"\"\n result should containStr ( \n \"class my_black_box(\",\n \"val TESTI: Int = 1,\",\n s\"val TESTS: String = ${q}TRUE$q,\",\n \"val TEST: Int\",\n \") extends BlackBox(Map(\",\n s\"${q}TESTI$q -> TESTI,\",\n", "right_context": " s\"${q}TEST$q -> TEST\",\n \")) {\",\n \"val io = IO(new Bundle {\",\n \"val a = Input(Bool())\",\n \"val b = Output(Bool())\",\n \"})\",\n \"}\"\n )\n \n result should containStr ( \n \"val inst = Module(new my_black_box(\",\n \"TEST = 1\",\n \"))\",\n \"inst.io.a := a\",\n \"b := inst.io.b\"\n )\n }\n \n it should \"support explicit hardware parameters\" in {\n val p = wrapInPackage(s\"\"\"\n |localparam WIDTH = 5;\n |localparam logic [WIDTH-1:0] INIT_VALUE = '0;\n \"\"\".stripMargin, \"test_p\"\n )\n val inner = \"\"\"\n |\n |import test_p::WIDTH;\n |\n |module my_module #(\n | parameter logic [WIDTH-1:0] INIT_VALUE = '0,\n | parameter TEST\n |)(\n | input a,\n | output b\n |);\n |assign b = TEST ? a : '0;\n |endmodule\n \"\"\".stripMargin\n \n val main = wrapInModule(\"\"\"\n |input a;\n |input b;\n |\n |my_module #(.INIT_VALUE('0), .TEST(0)) inst(\n | .a(a),\n | .b(b)\n |);\n \"\"\".stripMargin)\n \n val result = emit(inner, p + main, None, TranslationOptions())\n debug(result)\n result should containStr (\"import chisel3._\")\n \n result should containStr (\n \"package object test_p {\",\n \"\",\n \"val WIDTH = 5\",\n \"val INIT_VALUE: UInt = 0.U\",\n \"\",\n \"}\"\n )\n \n result should containStr (\"import test_p.WIDTH\")\n\n result should containStr (\n \"class my_module(\",\n \"val INIT_VALUE: UInt = 0.U,\", // probably not the best style but compilable\n \"val TEST: Int\",\n \") extends BlackBox(Map(\",\n \"\\\"INIT_VALUE\\\" -> INIT_VALUE.litValue,\", // thanks to litValue\n \"\\\"TEST\\\" -> TEST\",\n \")) {\",\n \"val io = IO(new Bundle {\",\n \"val a = Input(Bool())\",\n \"val b = Output(Bool())\",\n \"})\"\n )\n \n result should containStr (\n \"val inst = Module(new my_module(\",\n \"INIT_VALUE = 0.U,\",\n \"TEST = 0\",\n \"))\",\n \"inst.io.a := a\",\n \"b := inst.io.b\"\n )\n\n }\n \n}", "groundtruth": " s\"${q}TESTS$q -> TESTS,\",\n", "crossfile_context": ""}
{"task_id": "sv2chisel", "path": "sv2chisel/src/test/scala/DefLogicSpec.scala", "left_context": "// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n// Copyright 2020 The sv2chisel Authors. All rights reserved.\n\npackage sv2chiselTests\n\nimport sv2chiselTests.utils._\nimport logger._\n\nclass DefLogicSpecs extends Sv2ChiselSpec {\n Logger.setLevel(LogLevel.Warn)\n \n behavior of \"InferDefLogic\"\n \n it should \"emit RegInit properly\" in {\n val result = emitInModule(s\"\"\"\n |localparam WWW = 1;\n |localparam WW = 1;\n |\n |wire clk;\n |wire change;\n |reg [WW-1:0] counter = '0;\n |reg [WWW-1:0] current = '1;\n |\n |always @(posedge clk) begin\n | if (change) begin\n | if (current < (1<>> 1;\n |assign res = $signed(a) >> 1;\n \"\"\".stripMargin\n )\n debug(result)\n result should containStr (\"class Test() extends RawModule {\")\n result should containStr (\"val a = Wire(UInt(17.W))\")\n result should containStr (\"val res = Wire(UInt(32.W))\")\n result should containStr (\"res := (a.asTypeOf(SInt(32.W)) >> 1.U).asUInt\")\n result should containStr (\"res := a.asTypeOf(SInt(32.W)).asUInt >> 1\")\n }\n \n it should \"properly manage reduction operators\" in {\n val result = emitInModule(\"\"\"\n |wire [31:0] a;\n |wire [31:0] b;\n |wire res;\n |assign b[15:0] = '1;\n |assign res = |(a & ~b);\n \"\"\".stripMargin\n )\n debug(result)\n result should containStr (\"class Test() extends RawModule {\")\n result should containStr (\"val a = Wire(UInt(32.W))\")\n result should containStr (\"val b = Wire(Vec(32, Bool()))\")\n result should containStr (\"val res = Wire(Bool())\")\n result should containStr (\"b(15,0) := 65535.U.asTypeOf(Vec(16, Bool()))\")\n result should containStr (\"res := (a&( ~b.asUInt)).orR()\")\n\n }\n \n it should \"properly manage bitwise operators on Bool\" in {\n val result = emitInModule(\"\"\"\n |wire a;\n |wire b;\n |wire c;\n |wire w, r, o;\n |assign w = a ^ b;\n |assign r = w ^ c;\n |assign o = (w & c) | (a & b);\n |assign o = (w && c) || (a && b);\n \"\"\".stripMargin\n )\n debug(result)\n result should containStr (\"class Test() extends RawModule {\")\n result should containStr ( \"w := a^b\" )\n result should containStr ( \"r := w^c\" )\n result should containStr ( \"o := (w&c)|(a&b)\" )\n result should containStr ( \"o := (w && c) || (a && b)\" )\n }\n \n it should \"manage edge cases\" in {\n val result = emitInModule(\"\"\"\n |localparam PA = 2;\n |localparam PB = 2;\n |localparam PC = 6;\n |\n |typedef struct packed {\n | logic [7:0] fieldA;\n | logic [13:0] fieldB;\n | logic [13:0] fieldC;\n |} my_struct_t;\n |\n |wire my_struct_t s;\n |// force vec bool fields \n |assign s.fieldA[0] = '1;\n |assign s.fieldB[0] = '1;\n |assign s.fieldC[0] = '1;\n |\n |wire v;\n |wire [7:0] u;\n |\n |assign u = (s.fieldA == PC ? PB : 0) + $bits(my_struct_t)/8;\n |assign u = s.fieldB + PA + (s.fieldA == PC ? PB : 0) + $bits(my_struct_t)/8;\n |\n |// NB:(Chisel error): can't create Mux with heterogeneous types class chisel3.SInt and class chisel3.UInt\n |assign v = s.fieldC >= (s.fieldB + PA + (s.fieldA == PC ? PB : 0) + $bits(my_struct_t)/8);\n |assign v = s.fieldC == (s.fieldB + PA + (s.fieldA == PC ? PB : 0) + $bits(my_struct_t)/8);\n \"\"\".stripMargin\n )\n debug(result)\n \n result should containStr (\"val v = Wire(Bool())\")\n result should containStr (\"val u = Wire(UInt(8.W))\")\n result should containStr (\n \"u := (Mux(s.fieldA.asUInt === PC.U, PB.U(8.W), 0.U))+((new my_struct_t).getWidth/8).U\",\n \"u := ((s.fieldB.asUInt+PA.U)+(Mux(s.fieldA.asUInt === PC.U, PB.U(8.W), 0.U)))+((new my_struct_t).getWidth/8).U\"\n )\n\n result should containStr (\n \"v := s.fieldC.asUInt >= (((s.fieldB.asUInt+PA.U)+(Mux(s.fieldA.asUInt === PC.U, PB.U, 0.U)))+((new my_struct_t).getWidth/8).U)\",\n \"v := s.fieldC.asUInt === (((s.fieldB.asUInt+PA.U)+(Mux(s.fieldA.asUInt === PC.U, PB.U, 0.U)))+((new my_struct_t).getWidth/8).U)\"\n )\n }\n\n it should \"properly manage arithmetic operators on Vec[Bool]\" in {\n val result = emitInModule(\"\"\"\n |wire [7:0] a;\n |wire [7:0] b;\n |wire [7:0] c;\n |// useless assign to preserve Vec[Bool] type\n |assign a[3:0] = '0;\n |assign b[3:0] = '0;\n |assign c = a + b;\n \"\"\".stripMargin\n )\n debug(result)\n result should containStr (\"val a = Wire(Vec(8, Bool()))\")\n result should containStr (\"val b = Wire(Vec(8, Bool()))\")\n result should containStr (\"val c = Wire(UInt(8.W))\")\n\n result should containStr (\"c := a.asUInt+b.asUInt\")\n\n }\n}", "groundtruth": " \"\"\".stripMargin\n )\n debug(result)\n result should containStr (\"class Test() extends RawModule {\")\n result should containStr (\"val lhsc = Wire(Vec(32, Bool()))\")\n", "crossfile_context": ""}
{"task_id": "sv2chisel", "path": "sv2chisel/src/test/scala/MacroSpecs.scala", "left_context": "// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n// Copyright 2020 The sv2chisel Authors. All rights reserved.\n\npackage sv2chiselTests\n\nimport sv2chiselTests.utils._\nimport logger._\n\nclass MacroSpec extends Sv2ChiselSpec {\n Logger.setLevel(LogLevel.Warn)\n \n behavior of \"MacroSpec\"\n \n it should \"pass lexing & parsing (TODO: produce valid Chisel)\" in {\n val result = emitInModule(s\"\"\"\n |`define TRUC 32\n |localparam TRUC = 32;\n |`define CALC(VAL1, VAL2, VAL3) \\\\\n | RESULT = VAL1 EXPR VAL2; \\\\\n | $$display(\"Result is %0d\", RESULT);\n |localparam CALC = TRUC;\n |`ifdef TRUC\n |wire [`TRUC-1:0] test = `TRUC'b1;\n |`else\n |wire [32-1:0] test = 32'b1;\n |`endif\n \"\"\".stripMargin\n )\n", "right_context": " \n }\n\n}", "groundtruth": " \n result should containStr (\"val TRUC = 32\")\n result should containStr (\"val CALC = TRUC\")\n", "crossfile_context": ""}
{"task_id": "sv2chisel", "path": "sv2chisel/src/test/scala/RemoveConcatSpec.scala", "left_context": "// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n// Copyright 2020 The sv2chisel Authors. All rights reserved.\n\npackage sv2chiselTests\n\nimport sv2chiselTests.utils._\nimport logger._\n\nclass RemoveConcatSpec extends Sv2ChiselSpec {\n Logger.setLevel(LogLevel.Warn)\n \n behavior of \"RemoveConcats\" \n \n", "right_context": " |\n |wire bool;\n |wire [DBLW-1:0][WWW:0] pack;\n |wire [DBLW-1:0][WWW-1:0] packsmall;\n |\n |generate\n | for (i = 0; i < DBLW/2; i++) begin: loop\n | assign {bool, packsmall[i][WWW-1:1], packsmall[i][0]} = pack[2*i];\n | assign pack[2*i+1] = bool ? {packsmall[i][WWW-1:0], 1'b0} : '0;\n | end\n |endgenerate\n \"\"\".stripMargin\n )\n debug(result)\n result should containStr (\"class Test() extends RawModule {\")\n result should containStr (\"val auto_concat = Wire(new Bundle {\",\n \"val bool = Bool()\",\n \"val packsmall_i_WWW_1_1 = Vec(WWW-1, Bool())\",\n \"val packsmall_i_0 = Bool()\",\n \"})\",\n \"auto_concat := pack(2*i).asTypeOf(auto_concat)\",\n \"bool := auto_concat.bool\",\n \"packsmall(i)(WWW-1,1) := auto_concat.packsmall_i_WWW_1_1\",\n \"packsmall(i)(0) := auto_concat.packsmall_i_0\")\n \n // seccond concat inline\n result should containStr (\"pack((2*i)+1) := Mux(bool, Cat(packsmall(i)(WWW-1,0).asUInt, \\\"b0\\\".U(1.W)), 0.U)\")\n \n }\n \n it should \"properly emit Cat with subrange and replicate patterns\" in {\n val result = emitInModule(s\"\"\"\n |localparam WWW = 16;\n |localparam AAA = 4;\n |\n |wire [WWW-1:0] w;\n |wire [WWW-1:0] y;\n |\n |assign w = {{(WWW-AAA){1'b0}}, y[AAA-1:0]};\n \"\"\".stripMargin\n )\n debug(result)\n result should containStr (\"import chisel3._\")\n result should containStr (\"import sv2chisel.helpers.vecconvert._\")\n result should containStr (\"import chisel3.util.Cat\")\n\n result should containStr (\"class Test() extends RawModule {\")\n result should containStr (\n \"val w = Wire(UInt(WWW.W))\",\n \"val y = Wire(Vec(WWW, Bool()))\",\n \"w := Cat((VecInit.tabulate((WWW-AAA))(_ => false.B)).asUInt, y(AAA-1,0).asUInt)\",\n )\n \n }\n \n it should \"properly emit Cat with subrange and replicate patterns in functions\" in {\n val result = emit(wrapInPackage(s\"\"\"\n |localparam WWW = 16;\n |localparam AAA = 4;\n |function [WWW-1:0] w;\n | input logic [WWW-1:0] y;\n | w = {{(WWW-AAA){1'b0}}, y[AAA-1:0]};\n |endfunction;\n \"\"\".stripMargin\n ))\n debug(result)\n result should containStr (\"import chisel3._\")\n result should containStr (\"import sv2chisel.helpers.vecconvert._\")\n result should containStr (\"import chisel3.util.Cat\")\n\n result should containStr (\n \"def w(y:Vec[Bool]): UInt = {\",\n \"Cat((VecInit.tabulate((WWW-AAA))(_ => false.B)).asUInt, y(AAA-1,0).asUInt)\",\n \"}\"\n )\n \n }\n\n}", "groundtruth": " it should \"properly remove concats or use Cat\" in {\n val result = emitInModule(s\"\"\"\n |// might containStr more than the RAM due to moves\n", "crossfile_context": ""}
{"task_id": "sv2chisel", "path": "sv2chisel/src/test/scala/UnpackedEmissionStyleSpec.scala", "left_context": "// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n// Copyright 2020 The sv2chisel Authors. All rights reserved.\n\npackage sv2chiselTests\n\nimport sv2chiselTests.utils._\nimport sv2chisel.{TranslationOptions, ChiselizerOptions}\nimport logger._\n\nclass UnpackedEmissionStyleSpec extends Sv2ChiselSpec {\n Logger.setLevel(LogLevel.Warn)\n \n // Basic Tests of Module wraper for tests\n behavior of \"UnpackedEmissionStyle\"\n \n val baseContent = wrapInModule(\n s\"\"\"\n |//Verilog wire\n |wire [1:0] w[3:0];\n |assign w[3] = '0;\n |assign w[2] = '1;\n |assign w[1] = '1;\n |assign w[0] = '0;\n |// verilog register\n |input clk;\n |reg [1:0] r[3:0];\n |always @(posedge clk) begin\n | r[3] <= '0;\n | r[2] <= '1;\n | r[1] <= '1;\n | r[0] <= '0;\n |end\n \"\"\".stripMargin\n ) \n\n it should \"support unpacked wire & reg with UnpackedEmissionStyle.Reg\" in {\n val chiselizerOpts = ChiselizerOptions().copy(\n unpackedEmissionStyle = ChiselizerOptions.UnpackedEmissionStyle.Reg\n )\n val result = emit(baseContent,\n options = TranslationOptions(chiselizer = chiselizerOpts)\n )\n debug(result)\n result should containStr (\n", "right_context": " \"val r = Reg(Vec(4, UInt(2.W)))\",\n \"r(3) := 0.U\",\n \"r(2) := 3.U\",\n \"r(1) := 3.U\",\n \"r(0) := 0.U\",\n )\n }\n \n it should \"support unpacked wire & reg with UnpackedEmissionStyle.Mem\" in {\n val chiselizerOpts = ChiselizerOptions().copy(\n unpackedEmissionStyle = ChiselizerOptions.UnpackedEmissionStyle.Mem\n )\n val result = emit(baseContent,\n options = TranslationOptions(chiselizer = chiselizerOpts)\n )\n debug(result)\n result should containStr (\n \"val w = Wire(Vec(4, UInt(2.W)))\",\n \"w(3) := 0.U\",\n \"w(2) := 3.U\",\n \"w(1) := 3.U\",\n \"w(0) := 0.U\"\n )\n result should containStr (\n \"val r = Mem(4,UInt(2.W))\",\n \"r(3) := 0.U\",\n \"r(2) := 3.U\",\n \"r(1) := 3.U\",\n \"r(0) := 0.U\",\n )\n }\n}", "groundtruth": " \"val w = Wire(Vec(4, UInt(2.W)))\",\n \"w(3) := 0.U\",\n \"w(2) := 3.U\",\n \"w(1) := 3.U\",\n", "crossfile_context": ""}
{"task_id": "riscv-boom", "path": "riscv-boom/src/main/scala/v3/exu/execution-units/fpu.scala", "left_context": "//******************************************************************************\n// Copyright (c) 2015 - 2018, The Regents of the University of California (Regents).\n// All Rights Reserved. See LICENSE and LICENSE.SiFive for license details.\n//------------------------------------------------------------------------------\n\npackage boom.v3.exu\n\nimport chisel3._\nimport chisel3.util._\nimport chisel3.experimental.dataview._\nimport org.chipsalliance.cde.config.Parameters\nimport freechips.rocketchip.tile.FPConstants._\nimport freechips.rocketchip.tile.{FPUCtrlSigs, HasFPUParameters}\nimport freechips.rocketchip.tile\nimport freechips.rocketchip.rocket\nimport freechips.rocketchip.util.uintToBitPat\nimport boom.v3.common._\nimport boom.v3.util.{ImmGenRm, ImmGenTyp}\n\n/**\n * FP Decoder for the FPU\n *\n * TODO get rid of this decoder and move into the Decode stage? Or the RRd stage?\n * most of these signals are already created, just need to be translated\n * to the Rocket FPU-speak\n */\nclass UOPCodeFPUDecoder(implicit p: Parameters) extends BoomModule with HasFPUParameters\n{\n val io = IO(new Bundle {\n val uopc = Input(Bits(UOPC_SZ.W))\n val sigs = Output(new FPUCtrlSigs())\n })\n\n // TODO change N,Y,X to BitPat(\"b1\"), BitPat(\"b0\"), and BitPat(\"b?\")\n val N = false.B\n val Y = true.B\n val X = false.B\n\n val default: List[BitPat] = List(X,X,X,X,X, X,X,X,X,X,X,X, X,X,X,X)\n\n val f_table: Array[(BitPat, List[BitPat])] =\n // Note: not all of these signals are used or necessary, but we're\n // constrained by the need to fit the rocket.FPU units' ctrl signals.\n // swap12 fma\n // | swap32 | div\n // | | typeTagIn | | sqrt\n // ldst | | | typeTagOut | | wflags\n // | wen | | | | from_int | | |\n // | | ren1 | | | | | to_int | | |\n // | | | ren2 | | | | | | fastpipe |\n // | | | | ren3 | | | | | | | | | |\n // | | | | | | | | | | | | | | | |\n Array(\n BitPat(uopFCLASS_S) -> List(X,X,Y,N,N, N,X,S,S,N,Y,N, N,N,N,N),\n BitPat(uopFMV_W_X) -> List(X,X,N,N,N, X,X,S,D,Y,N,N, N,N,N,N),\n BitPat(uopFMV_X_W) -> List(X,X,Y,N,N, N,X,D,S,N,Y,N, N,N,N,N),\n\n BitPat(uopFCVT_S_X) -> List(X,X,N,N,N, X,X,S,S,Y,N,N, N,N,N,Y),\n\n BitPat(uopFCVT_X_S) -> List(X,X,Y,N,N, N,X,S,S,N,Y,N, N,N,N,Y),\n\n BitPat(uopCMPR_S) -> List(X,X,Y,Y,N, N,N,S,S,N,Y,N, N,N,N,Y),\n\n BitPat(uopFSGNJ_S) -> List(X,X,Y,Y,N, N,N,S,S,N,N,Y, N,N,N,N),\n\n BitPat(uopFMINMAX_S)-> List(X,X,Y,Y,N, N,N,S,S,N,N,Y, N,N,N,Y),\n\n BitPat(uopFADD_S) -> List(X,X,Y,Y,N, N,Y,S,S,N,N,N, Y,N,N,Y),\n BitPat(uopFSUB_S) -> List(X,X,Y,Y,N, N,Y,S,S,N,N,N, Y,N,N,Y),\n BitPat(uopFMUL_S) -> List(X,X,Y,Y,N, N,N,S,S,N,N,N, Y,N,N,Y),\n BitPat(uopFMADD_S) -> List(X,X,Y,Y,Y, N,N,S,S,N,N,N, Y,N,N,Y),\n BitPat(uopFMSUB_S) -> List(X,X,Y,Y,Y, N,N,S,S,N,N,N, Y,N,N,Y),\n BitPat(uopFNMADD_S) -> List(X,X,Y,Y,Y, N,N,S,S,N,N,N, Y,N,N,Y),\n BitPat(uopFNMSUB_S) -> List(X,X,Y,Y,Y, N,N,S,S,N,N,N, Y,N,N,Y)\n )\n\n val d_table: Array[(BitPat, List[BitPat])] =\n Array(\n BitPat(uopFCLASS_D) -> List(X,X,Y,N,N, N,X,D,D,N,Y,N, N,N,N,N),\n BitPat(uopFMV_D_X) -> List(X,X,N,N,N, X,X,D,D,Y,N,N, N,N,N,N),\n BitPat(uopFMV_X_D) -> List(X,X,Y,N,N, N,X,D,D,N,Y,N, N,N,N,N),\n BitPat(uopFCVT_S_D) -> List(X,X,Y,N,N, N,X,D,S,N,N,Y, N,N,N,Y),\n BitPat(uopFCVT_D_S) -> List(X,X,Y,N,N, N,X,S,D,N,N,Y, N,N,N,Y),\n\n BitPat(uopFCVT_D_X) -> List(X,X,N,N,N, X,X,D,D,Y,N,N, N,N,N,Y),\n\n BitPat(uopFCVT_X_D) -> List(X,X,Y,N,N, N,X,D,D,N,Y,N, N,N,N,Y),\n\n BitPat(uopCMPR_D) -> List(X,X,Y,Y,N, N,N,D,D,N,Y,N, N,N,N,Y),\n\n BitPat(uopFSGNJ_D) -> List(X,X,Y,Y,N, N,N,D,D,N,N,Y, N,N,N,N),\n\n BitPat(uopFMINMAX_D)-> List(X,X,Y,Y,N, N,N,D,D,N,N,Y, N,N,N,Y),\n\n BitPat(uopFADD_D) -> List(X,X,Y,Y,N, N,Y,D,D,N,N,N, Y,N,N,Y),\n BitPat(uopFSUB_D) -> List(X,X,Y,Y,N, N,Y,D,D,N,N,N, Y,N,N,Y),\n BitPat(uopFMUL_D) -> List(X,X,Y,Y,N, N,N,D,D,N,N,N, Y,N,N,Y),\n\n BitPat(uopFMADD_D) -> List(X,X,Y,Y,Y, N,N,D,D,N,N,N, Y,N,N,Y),\n BitPat(uopFMSUB_D) -> List(X,X,Y,Y,Y, N,N,D,D,N,N,N, Y,N,N,Y),\n BitPat(uopFNMADD_D) -> List(X,X,Y,Y,Y, N,N,D,D,N,N,N, Y,N,N,Y),\n BitPat(uopFNMSUB_D) -> List(X,X,Y,Y,Y, N,N,D,D,N,N,N, Y,N,N,Y)\n )\n\n// val insns = fLen match {\n// case 32 => f_table\n// case 64 => f_table ++ d_table\n// }\n val insns = f_table ++ d_table\n val decoder = rocket.DecodeLogic(io.uopc, default, insns)\n\n val s = io.sigs\n val sigs = Seq(s.ldst, s.wen, s.ren1, s.ren2, s.ren3, s.swap12,\n s.swap23, s.typeTagIn, s.typeTagOut, s.fromint, s.toint, s.fastpipe, s.fma,\n s.div, s.sqrt, s.wflags)\n sigs zip decoder map {case(s,d) => s := d}\n s.vec := false.B\n}\n\n/**\n * FP fused multiple add decoder for the FPU\n */\nclass FMADecoder extends Module\n{\n val io = IO(new Bundle {\n val uopc = Input(UInt(UOPC_SZ.W))\n val cmd = Output(UInt(2.W))\n })\n\n val default: List[BitPat] = List(BitPat(\"b??\"))\n val table: Array[(BitPat, List[BitPat])] =\n Array(\n BitPat(uopFADD_S) -> List(BitPat(\"b00\")),\n BitPat(uopFSUB_S) -> List(BitPat(\"b01\")),\n BitPat(uopFMUL_S) -> List(BitPat(\"b00\")),\n BitPat(uopFMADD_S) -> List(BitPat(\"b00\")),\n BitPat(uopFMSUB_S) -> List(BitPat(\"b01\")),\n BitPat(uopFNMADD_S) -> List(BitPat(\"b11\")),\n BitPat(uopFNMSUB_S) -> List(BitPat(\"b10\")),\n BitPat(uopFADD_D) -> List(BitPat(\"b00\")),\n BitPat(uopFSUB_D) -> List(BitPat(\"b01\")),\n BitPat(uopFMUL_D) -> List(BitPat(\"b00\")),\n BitPat(uopFMADD_D) -> List(BitPat(\"b00\")),\n BitPat(uopFMSUB_D) -> List(BitPat(\"b01\")),\n BitPat(uopFNMADD_D) -> List(BitPat(\"b11\")),\n BitPat(uopFNMSUB_D) -> List(BitPat(\"b10\"))\n )\n\n val decoder = rocket.DecodeLogic(io.uopc, default, table)\n\n val (cmd: UInt) :: Nil = decoder\n io.cmd := cmd\n}\n\n/**\n * Bundle representing data to be sent to the FPU\n */\n", "right_context": "{\n val uop = new MicroOp()\n val rs1_data = Bits(65.W)\n val rs2_data = Bits(65.W)\n val rs3_data = Bits(65.W)\n val fcsr_rm = Bits(tile.FPConstants.RM_SZ.W)\n}\n\n/**\n * FPU unit that wraps the RocketChip FPU units (which in turn wrap hardfloat)\n */\nclass FPU(implicit p: Parameters) extends BoomModule with tile.HasFPUParameters\n{\n val io = IO(new Bundle {\n val req = Flipped(new ValidIO(new FpuReq))\n val resp = new ValidIO(new ExeUnitResp(65))\n })\n io.resp.bits := DontCare\n\n // all FP units are padded out to the same latency for easy scheduling of the write port\n val fpu_latency = dfmaLatency\n val io_req = io.req.bits\n\n val fp_decoder = Module(new UOPCodeFPUDecoder)\n fp_decoder.io.uopc := io_req.uop.uopc\n val fp_ctrl = fp_decoder.io.sigs\n val fp_rm = Mux(ImmGenRm(io_req.uop.imm_packed) === 7.U, io_req.fcsr_rm, ImmGenRm(io_req.uop.imm_packed))\n\n def fuInput(minT: Option[tile.FType]): tile.FPInput = {\n val req = Wire(new tile.FPInput)\n val tag = fp_ctrl.typeTagIn\n req.viewAsSupertype(new tile.FPUCtrlSigs) := fp_ctrl\n req.rm := fp_rm\n req.in1 := unbox(io_req.rs1_data, tag, minT)\n req.in2 := unbox(io_req.rs2_data, tag, minT)\n req.in3 := unbox(io_req.rs3_data, tag, minT)\n when (fp_ctrl.swap23) { req.in3 := req.in2 }\n req.typ := ImmGenTyp(io_req.uop.imm_packed)\n req.fmt := Mux(tag === S, 0.U, 1.U) // TODO support Zfh and avoid special-case below\n when (io_req.uop.uopc === uopFMV_X_W) {\n req.fmt := 0.U\n }\n\n val fma_decoder = Module(new FMADecoder)\n fma_decoder.io.uopc := io_req.uop.uopc\n req.fmaCmd := fma_decoder.io.cmd // ex_reg_inst(3,2) | (!fp_ctrl.ren3 && ex_reg_inst(27))\n req\n }\n\n val dfma = Module(new tile.FPUFMAPipe(latency = fpu_latency, t = tile.FType.D))\n dfma.io.in.valid := io.req.valid && fp_ctrl.fma && (fp_ctrl.typeTagOut === D)\n dfma.io.in.bits := fuInput(Some(dfma.t))\n\n val sfma = Module(new tile.FPUFMAPipe(latency = fpu_latency, t = tile.FType.S))\n sfma.io.in.valid := io.req.valid && fp_ctrl.fma && (fp_ctrl.typeTagOut === S)\n sfma.io.in.bits := fuInput(Some(sfma.t))\n\n val fpiu = Module(new tile.FPToInt)\n fpiu.io.in.valid := io.req.valid && (fp_ctrl.toint || (fp_ctrl.fastpipe && fp_ctrl.wflags))\n fpiu.io.in.bits := fuInput(None)\n val fpiu_out = Pipe(RegNext(fpiu.io.in.valid && !fp_ctrl.fastpipe),\n fpiu.io.out.bits, fpu_latency-1)\n val fpiu_result = Wire(new tile.FPResult)\n fpiu_result.data := fpiu_out.bits.toint\n fpiu_result.exc := fpiu_out.bits.exc\n\n val fpmu = Module(new tile.FPToFP(fpu_latency)) // latency 2 for rocket\n fpmu.io.in.valid := io.req.valid && fp_ctrl.fastpipe\n fpmu.io.in.bits := fpiu.io.in.bits\n fpmu.io.lt := fpiu.io.out.bits.lt\n val fpmu_double = Pipe(io.req.valid && fp_ctrl.fastpipe, fp_ctrl.typeTagOut === D, fpu_latency).bits\n\n // Response (all FP units have been padded out to the same latency)\n io.resp.valid := fpiu_out.valid ||\n fpmu.io.out.valid ||\n sfma.io.out.valid ||\n dfma.io.out.valid\n val fpu_out_data =\n Mux(dfma.io.out.valid, box(dfma.io.out.bits.data, true.B),\n Mux(sfma.io.out.valid, box(sfma.io.out.bits.data, false.B),\n Mux(fpiu_out.valid, fpiu_result.data,\n box(fpmu.io.out.bits.data, fpmu_double))))\n\n val fpu_out_exc =\n Mux(dfma.io.out.valid, dfma.io.out.bits.exc,\n Mux(sfma.io.out.valid, sfma.io.out.bits.exc,\n Mux(fpiu_out.valid, fpiu_result.exc,\n fpmu.io.out.bits.exc)))\n\n io.resp.bits.data := fpu_out_data\n io.resp.bits.fflags.valid := io.resp.valid\n io.resp.bits.fflags.bits.flags := fpu_out_exc\n}\n", "groundtruth": "class FpuReq()(implicit p: Parameters) extends BoomBundle\n", "crossfile_context": ""}
{"task_id": "riscv-boom", "path": "riscv-boom/src/main/scala/v3/exu/execution-units/functional-unit.scala", "left_context": "//******************************************************************************\n// Copyright (c) 2013 - 2018, The Regents of the University of California (Regents).\n// All Rights Reserved. See LICENSE and LICENSE.SiFive for license details.\n//------------------------------------------------------------------------------\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\n// Functional Units\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\n//\n// If regfile bypassing is disabled, then the functional unit must do its own\n// bypassing in here on the WB stage (i.e., bypassing the io.resp.data)\n//\n// TODO: explore possibility of conditional IO fields? if a branch unit... how to add extra to IO in subclass?\n\npackage boom.v3.exu\n\nimport chisel3._\nimport chisel3.util._\nimport chisel3.experimental.dataview._\n\nimport org.chipsalliance.cde.config.Parameters\nimport freechips.rocketchip.util._\nimport freechips.rocketchip.tile\nimport freechips.rocketchip.rocket.{PipelinedMultiplier,BP,BreakpointUnit,Causes,CSR}\n\nimport boom.v3.common._\nimport boom.v3.ifu._\nimport boom.v3.util._\n\n/**t\n * Functional unit constants\n */\nobject FUConstants\n{\n // bit mask, since a given execution pipeline may support multiple functional units\n val FUC_SZ = 10\n val FU_X = BitPat.dontCare(FUC_SZ)\n val FU_ALU = 1.U(FUC_SZ.W)\n val FU_JMP = 2.U(FUC_SZ.W)\n val FU_MEM = 4.U(FUC_SZ.W)\n val FU_MUL = 8.U(FUC_SZ.W)\n val FU_DIV = 16.U(FUC_SZ.W)\n val FU_CSR = 32.U(FUC_SZ.W)\n val FU_FPU = 64.U(FUC_SZ.W)\n val FU_FDV = 128.U(FUC_SZ.W)\n val FU_I2F = 256.U(FUC_SZ.W)\n val FU_F2I = 512.U(FUC_SZ.W)\n\n // FP stores generate data through FP F2I, and generate address through MemAddrCalc\n val FU_F2IMEM = 516.U(FUC_SZ.W)\n}\nimport FUConstants._\n\n/**\n * Class to tell the FUDecoders what units it needs to support\n *\n * @param alu support alu unit?\n * @param bru support br unit?\n * @param mem support mem unit?\n * @param muld support multiple div unit?\n * @param fpu support FP unit?\n * @param csr support csr writing unit?\n * @param fdiv support FP div unit?\n * @param ifpu support int to FP unit?\n */\nclass SupportedFuncUnits(\n val alu: Boolean = false,\n val jmp: Boolean = false,\n val mem: Boolean = false,\n val muld: Boolean = false,\n val fpu: Boolean = false,\n val csr: Boolean = false,\n val fdiv: Boolean = false,\n val ifpu: Boolean = false)\n{\n}\n\n\n/**\n * Bundle for signals sent to the functional unit\n *\n * @param dataWidth width of the data sent to the functional unit\n */\nclass FuncUnitReq(val dataWidth: Int)(implicit p: Parameters) extends BoomBundle\n with HasBoomUOP\n{\n val numOperands = 3\n\n val rs1_data = UInt(dataWidth.W)\n val rs2_data = UInt(dataWidth.W)\n val rs3_data = UInt(dataWidth.W) // only used for FMA units\n val pred_data = Bool()\n\n val kill = Bool() // kill everything\n}\n\n/**\n * Bundle for the signals sent out of the function unit\n *\n * @param dataWidth data sent from the functional unit\n */\nclass FuncUnitResp(val dataWidth: Int)(implicit p: Parameters) extends BoomBundle\n with HasBoomUOP\n{\n val predicated = Bool() // Was this response from a predicated-off instruction\n val data = UInt(dataWidth.W)\n val fflags = new ValidIO(new FFlagsResp)\n val addr = UInt((vaddrBits+1).W) // only for maddr -> LSU\n val mxcpt = new ValidIO(UInt((freechips.rocketchip.rocket.Causes.all.max+2).W)) //only for maddr->LSU\n val sfence = Valid(new freechips.rocketchip.rocket.SFenceReq) // only for mcalc\n}\n\n/**\n * Branch resolution information given from the branch unit\n */\n", "right_context": "{\n val uop = new MicroOp\n val valid = Bool()\n val mispredict = Bool()\n val taken = Bool() // which direction did the branch go?\n val cfi_type = UInt(CFI_SZ.W)\n\n // Info for recalculating the pc for this branch\n val pc_sel = UInt(2.W)\n\n val jalr_target = UInt(vaddrBitsExtended.W)\n val target_offset = SInt()\n}\n\nclass BrUpdateInfo(implicit p: Parameters) extends BoomBundle\n{\n // On the first cycle we get masks to kill registers\n val b1 = new BrUpdateMasks\n // On the second cycle we get indices to reset pointers\n val b2 = new BrResolutionInfo\n}\n\nclass BrUpdateMasks(implicit p: Parameters) extends BoomBundle\n{\n val resolve_mask = UInt(maxBrCount.W)\n val mispredict_mask = UInt(maxBrCount.W)\n}\n\n\n/**\n * Abstract top level functional unit class that wraps a lower level hand made functional unit\n *\n * @param isPipelined is the functional unit pipelined?\n * @param numStages how many pipeline stages does the functional unit have\n * @param numBypassStages how many bypass stages does the function unit have\n * @param dataWidth width of the data being operated on in the functional unit\n * @param hasBranchUnit does this functional unit have a branch unit?\n */\nabstract class FunctionalUnit(\n val isPipelined: Boolean,\n val numStages: Int,\n val numBypassStages: Int,\n val dataWidth: Int,\n val isJmpUnit: Boolean = false,\n val isAluUnit: Boolean = false,\n val isMemAddrCalcUnit: Boolean = false,\n val needsFcsr: Boolean = false)\n (implicit p: Parameters) extends BoomModule\n{\n val io = IO(new Bundle {\n val req = Flipped(new DecoupledIO(new FuncUnitReq(dataWidth)))\n val resp = (new DecoupledIO(new FuncUnitResp(dataWidth)))\n\n val brupdate = Input(new BrUpdateInfo())\n\n val bypass = Output(Vec(numBypassStages, Valid(new ExeUnitResp(dataWidth))))\n\n // only used by the fpu unit\n val fcsr_rm = if (needsFcsr) Input(UInt(tile.FPConstants.RM_SZ.W)) else null\n\n // only used by branch unit\n val brinfo = if (isAluUnit) Output(new BrResolutionInfo()) else null\n val get_ftq_pc = if (isJmpUnit) Flipped(new GetPCFromFtqIO()) else null\n val status = if (isMemAddrCalcUnit) Input(new freechips.rocketchip.rocket.MStatus()) else null\n\n // only used by memaddr calc unit\n val bp = if (isMemAddrCalcUnit) Input(Vec(nBreakpoints, new BP)) else null\n val mcontext = if (isMemAddrCalcUnit) Input(UInt(coreParams.mcontextWidth.W)) else null\n val scontext = if (isMemAddrCalcUnit) Input(UInt(coreParams.scontextWidth.W)) else null\n\n })\n\n io.bypass.foreach { b => b.valid := false.B; b.bits := DontCare }\n\n io.resp.valid := false.B\n io.resp.bits := DontCare\n\n if (isJmpUnit) {\n io.get_ftq_pc.ftq_idx := DontCare\n }\n}\n\n/**\n * Abstract top level pipelined functional unit\n *\n * Note: this helps track which uops get killed while in intermediate stages,\n * but it is the job of the consumer to check for kills on the same cycle as consumption!!!\n *\n * @param numStages how many pipeline stages does the functional unit have\n * @param numBypassStages how many bypass stages does the function unit have\n * @param earliestBypassStage first stage that you can start bypassing from\n * @param dataWidth width of the data being operated on in the functional unit\n * @param hasBranchUnit does this functional unit have a branch unit?\n */\nabstract class PipelinedFunctionalUnit(\n numStages: Int,\n numBypassStages: Int,\n earliestBypassStage: Int,\n dataWidth: Int,\n isJmpUnit: Boolean = false,\n isAluUnit: Boolean = false,\n isMemAddrCalcUnit: Boolean = false,\n needsFcsr: Boolean = false\n )(implicit p: Parameters) extends FunctionalUnit(\n isPipelined = true,\n numStages = numStages,\n numBypassStages = numBypassStages,\n dataWidth = dataWidth,\n isJmpUnit = isJmpUnit,\n isAluUnit = isAluUnit,\n isMemAddrCalcUnit = isMemAddrCalcUnit,\n needsFcsr = needsFcsr)\n{\n // Pipelined functional unit is always ready.\n io.req.ready := true.B\n\n if (numStages > 0) {\n val r_valids = RegInit(VecInit(Seq.fill(numStages) { false.B }))\n val r_uops = Reg(Vec(numStages, new MicroOp()))\n\n // handle incoming request\n r_valids(0) := io.req.valid && !IsKilledByBranch(io.brupdate, io.req.bits.uop) && !io.req.bits.kill\n r_uops(0) := io.req.bits.uop\n r_uops(0).br_mask := GetNewBrMask(io.brupdate, io.req.bits.uop)\n\n // handle middle of the pipeline\n for (i <- 1 until numStages) {\n r_valids(i) := r_valids(i-1) && !IsKilledByBranch(io.brupdate, r_uops(i-1)) && !io.req.bits.kill\n r_uops(i) := r_uops(i-1)\n r_uops(i).br_mask := GetNewBrMask(io.brupdate, r_uops(i-1))\n\n if (numBypassStages > 0) {\n io.bypass(i-1).bits.uop := r_uops(i-1)\n }\n }\n\n // handle outgoing (branch could still kill it)\n // consumer must also check for pipeline flushes (kills)\n io.resp.valid := r_valids(numStages-1) && !IsKilledByBranch(io.brupdate, r_uops(numStages-1))\n io.resp.bits.predicated := false.B\n io.resp.bits.uop := r_uops(numStages-1)\n io.resp.bits.uop.br_mask := GetNewBrMask(io.brupdate, r_uops(numStages-1))\n\n // bypassing (TODO allow bypass vector to have a different size from numStages)\n if (numBypassStages > 0 && earliestBypassStage == 0) {\n io.bypass(0).bits.uop := io.req.bits.uop\n\n for (i <- 1 until numBypassStages) {\n io.bypass(i).bits.uop := r_uops(i-1)\n }\n }\n } else {\n require (numStages == 0)\n // pass req straight through to response\n\n // valid doesn't check kill signals, let consumer deal with it.\n // The LSU already handles it and this hurts critical path.\n io.resp.valid := io.req.valid && !IsKilledByBranch(io.brupdate, io.req.bits.uop)\n io.resp.bits.predicated := false.B\n io.resp.bits.uop := io.req.bits.uop\n io.resp.bits.uop.br_mask := GetNewBrMask(io.brupdate, io.req.bits.uop)\n }\n}\n\n/**\n * Functional unit that wraps RocketChips ALU\n *\n * @param isBranchUnit is this a branch unit?\n * @param numStages how many pipeline stages does the functional unit have\n * @param dataWidth width of the data being operated on in the functional unit\n */\nclass ALUUnit(isJmpUnit: Boolean = false, numStages: Int = 1, dataWidth: Int)(implicit p: Parameters)\n extends PipelinedFunctionalUnit(\n numStages = numStages,\n numBypassStages = numStages,\n isAluUnit = true,\n earliestBypassStage = 0,\n dataWidth = dataWidth,\n isJmpUnit = isJmpUnit)\n with boom.v3.ifu.HasBoomFrontendParameters\n{\n val uop = io.req.bits.uop\n\n // immediate generation\n val imm_xprlen = ImmGen(uop.imm_packed, uop.ctrl.imm_sel)\n\n // operand 1 select\n var op1_data: UInt = null\n if (isJmpUnit) {\n // Get the uop PC for jumps\n val block_pc = AlignPCToBoundary(io.get_ftq_pc.pc, icBlockBytes)\n val uop_pc = (block_pc | uop.pc_lob) - Mux(uop.edge_inst, 2.U, 0.U)\n\n op1_data = Mux(uop.ctrl.op1_sel.asUInt === OP1_RS1 , io.req.bits.rs1_data,\n Mux(uop.ctrl.op1_sel.asUInt === OP1_PC , Sext(uop_pc, xLen),\n 0.U))\n } else {\n op1_data = Mux(uop.ctrl.op1_sel.asUInt === OP1_RS1 , io.req.bits.rs1_data,\n 0.U)\n }\n\n // operand 2 select\n val op2_data = Mux(uop.ctrl.op2_sel === OP2_IMM, Sext(imm_xprlen.asUInt, xLen),\n Mux(uop.ctrl.op2_sel === OP2_IMMC, io.req.bits.uop.prs1(4,0),\n Mux(uop.ctrl.op2_sel === OP2_RS2 , io.req.bits.rs2_data,\n Mux(uop.ctrl.op2_sel === OP2_NEXT, Mux(uop.is_rvc, 2.U, 4.U),\n 0.U))))\n\n val alu = Module(new freechips.rocketchip.rocket.ALU())\n\n alu.io.in1 := op1_data.asUInt\n alu.io.in2 := op2_data.asUInt\n alu.io.fn := uop.ctrl.op_fcn\n alu.io.dw := uop.ctrl.fcn_dw\n\n\n // Did I just get killed by the previous cycle's branch,\n // or by a flush pipeline?\n val killed = WireInit(false.B)\n when (io.req.bits.kill || IsKilledByBranch(io.brupdate, uop)) {\n killed := true.B\n }\n\n val rs1 = io.req.bits.rs1_data\n val rs2 = io.req.bits.rs2_data\n val br_eq = (rs1 === rs2)\n val br_ltu = (rs1.asUInt < rs2.asUInt)\n val br_lt = (~(rs1(xLen-1) ^ rs2(xLen-1)) & br_ltu |\n rs1(xLen-1) & ~rs2(xLen-1)).asBool\n\n val pc_sel = MuxLookup(uop.ctrl.br_type, PC_PLUS4)(\n Seq( BR_N -> PC_PLUS4,\n BR_NE -> Mux(!br_eq, PC_BRJMP, PC_PLUS4),\n BR_EQ -> Mux( br_eq, PC_BRJMP, PC_PLUS4),\n BR_GE -> Mux(!br_lt, PC_BRJMP, PC_PLUS4),\n BR_GEU -> Mux(!br_ltu, PC_BRJMP, PC_PLUS4),\n BR_LT -> Mux( br_lt, PC_BRJMP, PC_PLUS4),\n BR_LTU -> Mux( br_ltu, PC_BRJMP, PC_PLUS4),\n BR_J -> PC_BRJMP,\n BR_JR -> PC_JALR\n ))\n\n val is_taken = io.req.valid &&\n !killed &&\n (uop.is_br || uop.is_jalr || uop.is_jal) &&\n (pc_sel =/= PC_PLUS4)\n\n // \"mispredict\" means that a branch has been resolved and it must be killed\n val mispredict = WireInit(false.B)\n\n val is_br = io.req.valid && !killed && uop.is_br && !uop.is_sfb\n val is_jal = io.req.valid && !killed && uop.is_jal\n val is_jalr = io.req.valid && !killed && uop.is_jalr\n\n when (is_br || is_jalr) {\n if (!isJmpUnit) {\n assert (pc_sel =/= PC_JALR)\n }\n when (pc_sel === PC_PLUS4) {\n mispredict := uop.taken\n }\n when (pc_sel === PC_BRJMP) {\n mispredict := !uop.taken\n }\n }\n\n val brinfo = Wire(new BrResolutionInfo)\n\n // note: jal doesn't allocate a branch-mask, so don't clear a br-mask bit\n brinfo.valid := is_br || is_jalr\n brinfo.mispredict := mispredict\n brinfo.uop := uop\n brinfo.cfi_type := Mux(is_jalr, CFI_JALR,\n Mux(is_br , CFI_BR, CFI_X))\n brinfo.taken := is_taken\n brinfo.pc_sel := pc_sel\n\n brinfo.jalr_target := DontCare\n\n\n // Branch/Jump Target Calculation\n // For jumps we read the FTQ, and can calculate the target\n // For branches we emit the offset for the core to redirect if necessary\n val target_offset = imm_xprlen(20,0).asSInt\n brinfo.jalr_target := DontCare\n if (isJmpUnit) {\n def encodeVirtualAddress(a0: UInt, ea: UInt) = if (vaddrBitsExtended == vaddrBits) {\n ea\n } else {\n // Efficient means to compress 64-bit VA into vaddrBits+1 bits.\n // (VA is bad if VA(vaddrBits) != VA(vaddrBits-1)).\n val a = a0.asSInt >> vaddrBits\n val msb = Mux(a === 0.S || a === -1.S, ea(vaddrBits), !ea(vaddrBits-1))\n Cat(msb, ea(vaddrBits-1,0))\n }\n\n\n val jalr_target_base = io.req.bits.rs1_data.asSInt\n val jalr_target_xlen = Wire(UInt(xLen.W))\n jalr_target_xlen := (jalr_target_base + target_offset).asUInt\n val jalr_target = (encodeVirtualAddress(jalr_target_xlen, jalr_target_xlen).asSInt & -2.S).asUInt\n\n brinfo.jalr_target := jalr_target\n val cfi_idx = ((uop.pc_lob ^ Mux(io.get_ftq_pc.entry.start_bank === 1.U, 1.U << log2Ceil(bankBytes), 0.U)))(log2Ceil(fetchWidth),1)\n\n when (pc_sel === PC_JALR) {\n mispredict := !io.get_ftq_pc.next_val ||\n (io.get_ftq_pc.next_pc =/= jalr_target) ||\n !io.get_ftq_pc.entry.cfi_idx.valid ||\n (io.get_ftq_pc.entry.cfi_idx.bits =/= cfi_idx)\n }\n }\n\n brinfo.target_offset := target_offset\n\n\n io.brinfo := brinfo\n\n\n\n// Response\n// TODO add clock gate on resp bits from functional units\n// io.resp.bits.data := RegEnable(alu.io.out, io.req.valid)\n// val reg_data = Reg(outType = Bits(width = xLen))\n// reg_data := alu.io.out\n// io.resp.bits.data := reg_data\n\n val r_val = RegInit(VecInit(Seq.fill(numStages) { false.B }))\n val r_data = Reg(Vec(numStages, UInt(xLen.W)))\n val r_pred = Reg(Vec(numStages, Bool()))\n val alu_out = Mux(io.req.bits.uop.is_sfb_shadow && io.req.bits.pred_data,\n Mux(io.req.bits.uop.ldst_is_rs1, io.req.bits.rs1_data, io.req.bits.rs2_data),\n Mux(io.req.bits.uop.uopc === uopMOV, io.req.bits.rs2_data, alu.io.out))\n r_val (0) := io.req.valid\n r_data(0) := Mux(io.req.bits.uop.is_sfb_br, pc_sel === PC_BRJMP, alu_out)\n r_pred(0) := io.req.bits.uop.is_sfb_shadow && io.req.bits.pred_data\n for (i <- 1 until numStages) {\n r_val(i) := r_val(i-1)\n r_data(i) := r_data(i-1)\n r_pred(i) := r_pred(i-1)\n }\n io.resp.bits.data := r_data(numStages-1)\n io.resp.bits.predicated := r_pred(numStages-1)\n // Bypass\n // for the ALU, we can bypass same cycle as compute\n require (numStages >= 1)\n require (numBypassStages >= 1)\n io.bypass(0).valid := io.req.valid\n io.bypass(0).bits.data := Mux(io.req.bits.uop.is_sfb_br, pc_sel === PC_BRJMP, alu_out)\n for (i <- 1 until numStages) {\n io.bypass(i).valid := r_val(i-1)\n io.bypass(i).bits.data := r_data(i-1)\n }\n\n // Exceptions\n io.resp.bits.fflags.valid := false.B\n}\n\n/**\n * Functional unit that passes in base+imm to calculate addresses, and passes store data\n * to the LSU.\n * For floating point, 65bit FP store-data needs to be decoded into 64bit FP form\n */\nclass MemAddrCalcUnit(implicit p: Parameters)\n extends PipelinedFunctionalUnit(\n numStages = 0,\n numBypassStages = 0,\n earliestBypassStage = 0,\n dataWidth = 65, // TODO enable this only if FP is enabled?\n isMemAddrCalcUnit = true)\n with freechips.rocketchip.rocket.constants.MemoryOpConstants\n with freechips.rocketchip.rocket.constants.ScalarOpConstants\n{\n // perform address calculation\n val sum = (io.req.bits.rs1_data.asSInt + io.req.bits.uop.imm_packed(19,8).asSInt).asUInt\n val ea_sign = Mux(sum(vaddrBits-1), ~sum(63,vaddrBits) === 0.U,\n sum(63,vaddrBits) =/= 0.U)\n val effective_address = Cat(ea_sign, sum(vaddrBits-1,0)).asUInt\n\n val store_data = io.req.bits.rs2_data\n\n io.resp.bits.addr := effective_address\n io.resp.bits.data := store_data\n\n if (dataWidth > 63) {\n assert (!(io.req.valid && io.req.bits.uop.ctrl.is_std &&\n io.resp.bits.data(64).asBool === true.B), \"65th bit set in MemAddrCalcUnit.\")\n\n assert (!(io.req.valid && io.req.bits.uop.ctrl.is_std && io.req.bits.uop.fp_val),\n \"FP store-data should now be going through a different unit.\")\n }\n\n assert (!(io.req.bits.uop.fp_val && io.req.valid && io.req.bits.uop.uopc =/=\n uopLD && io.req.bits.uop.uopc =/= uopSTA),\n \"[maddrcalc] assert we never get store data in here.\")\n\n // Handle misaligned exceptions\n val size = io.req.bits.uop.mem_size\n val misaligned =\n (size === 1.U && (effective_address(0) =/= 0.U)) ||\n (size === 2.U && (effective_address(1,0) =/= 0.U)) ||\n (size === 3.U && (effective_address(2,0) =/= 0.U))\n\n val bkptu = Module(new BreakpointUnit(nBreakpoints))\n bkptu.io.status := io.status\n bkptu.io.bp := io.bp\n bkptu.io.pc := DontCare\n bkptu.io.ea := effective_address\n bkptu.io.mcontext := io.mcontext\n bkptu.io.scontext := io.scontext\n\n val ma_ld = io.req.valid && io.req.bits.uop.uopc === uopLD && misaligned\n val ma_st = io.req.valid && (io.req.bits.uop.uopc === uopSTA || io.req.bits.uop.uopc === uopAMO_AG) && misaligned\n val dbg_bp = io.req.valid && ((io.req.bits.uop.uopc === uopLD && bkptu.io.debug_ld) ||\n (io.req.bits.uop.uopc === uopSTA && bkptu.io.debug_st))\n val bp = io.req.valid && ((io.req.bits.uop.uopc === uopLD && bkptu.io.xcpt_ld) ||\n (io.req.bits.uop.uopc === uopSTA && bkptu.io.xcpt_st))\n\n def checkExceptions(x: Seq[(Bool, UInt)]) =\n (x.map(_._1).reduce(_||_), PriorityMux(x))\n val (xcpt_val, xcpt_cause) = checkExceptions(List(\n (ma_ld, (Causes.misaligned_load).U),\n (ma_st, (Causes.misaligned_store).U),\n (dbg_bp, (CSR.debugTriggerCause).U),\n (bp, (Causes.breakpoint).U)))\n\n io.resp.bits.mxcpt.valid := xcpt_val\n io.resp.bits.mxcpt.bits := xcpt_cause\n assert (!(ma_ld && ma_st), \"Mutually-exclusive exceptions are firing.\")\n\n io.resp.bits.sfence.valid := io.req.valid && io.req.bits.uop.mem_cmd === M_SFENCE\n io.resp.bits.sfence.bits.rs1 := io.req.bits.uop.mem_size(0)\n io.resp.bits.sfence.bits.rs2 := io.req.bits.uop.mem_size(1)\n io.resp.bits.sfence.bits.addr := io.req.bits.rs1_data\n io.resp.bits.sfence.bits.asid := io.req.bits.rs2_data\n}\n\n\n/**\n * Functional unit to wrap lower level FPU\n *\n * Currently, bypassing is unsupported!\n * All FP instructions are padded out to the max latency unit for easy\n * write-port scheduling.\n */\nclass FPUUnit(implicit p: Parameters)\n extends PipelinedFunctionalUnit(\n numStages = p(tile.TileKey).core.fpu.get.dfmaLatency,\n numBypassStages = 0,\n earliestBypassStage = 0,\n dataWidth = 65,\n needsFcsr = true)\n{\n val fpu = Module(new FPU())\n fpu.io.req.valid := io.req.valid\n fpu.io.req.bits.uop := io.req.bits.uop\n fpu.io.req.bits.rs1_data := io.req.bits.rs1_data\n fpu.io.req.bits.rs2_data := io.req.bits.rs2_data\n fpu.io.req.bits.rs3_data := io.req.bits.rs3_data\n fpu.io.req.bits.fcsr_rm := io.fcsr_rm\n\n io.resp.bits.data := fpu.io.resp.bits.data\n io.resp.bits.fflags.valid := fpu.io.resp.bits.fflags.valid\n io.resp.bits.fflags.bits.uop := io.resp.bits.uop\n io.resp.bits.fflags.bits.flags := fpu.io.resp.bits.fflags.bits.flags // kill me now\n}\n\n/**\n * Int to FP conversion functional unit\n *\n * @param latency the amount of stages to delay by\n */\nclass IntToFPUnit(latency: Int)(implicit p: Parameters)\n extends PipelinedFunctionalUnit(\n numStages = latency,\n numBypassStages = 0,\n earliestBypassStage = 0,\n dataWidth = 65,\n needsFcsr = true)\n with tile.HasFPUParameters\n{\n val fp_decoder = Module(new UOPCodeFPUDecoder) // TODO use a simpler decoder\n val io_req = io.req.bits\n fp_decoder.io.uopc := io_req.uop.uopc\n val fp_ctrl = fp_decoder.io.sigs\n val fp_rm = Mux(ImmGenRm(io_req.uop.imm_packed) === 7.U, io.fcsr_rm, ImmGenRm(io_req.uop.imm_packed))\n val req = Wire(new tile.FPInput)\n val tag = fp_ctrl.typeTagIn\n\n req.viewAsSupertype(new tile.FPUCtrlSigs) := fp_ctrl\n\n req.rm := fp_rm\n req.in1 := unbox(io_req.rs1_data, tag, None)\n req.in2 := unbox(io_req.rs2_data, tag, None)\n req.in3 := DontCare\n req.typ := ImmGenTyp(io_req.uop.imm_packed)\n req.fmt := DontCare // FIXME: this may not be the right thing to do here\n req.fmaCmd := DontCare\n\n assert (!(io.req.valid && fp_ctrl.fromint && req.in1(xLen).asBool),\n \"[func] IntToFP integer input has 65th high-order bit set!\")\n\n assert (!(io.req.valid && !fp_ctrl.fromint),\n \"[func] Only support fromInt micro-ops.\")\n\n val ifpu = Module(new tile.IntToFP(intToFpLatency))\n ifpu.io.in.valid := io.req.valid\n ifpu.io.in.bits := req\n ifpu.io.in.bits.in1 := io_req.rs1_data\n val out_double = Pipe(io.req.valid, fp_ctrl.typeTagOut === D, intToFpLatency).bits\n\n//io.resp.bits.data := box(ifpu.io.out.bits.data, !io.resp.bits.uop.fp_single)\n io.resp.bits.data := box(ifpu.io.out.bits.data, out_double)\n io.resp.bits.fflags.valid := ifpu.io.out.valid\n io.resp.bits.fflags.bits.uop := io.resp.bits.uop\n io.resp.bits.fflags.bits.flags := ifpu.io.out.bits.exc\n}\n\n/**\n * Iterative/unpipelined functional unit, can only hold a single MicroOp at a time\n * assumes at least one register between request and response\n *\n * TODO allow up to N micro-ops simultaneously.\n *\n * @param dataWidth width of the data to be passed into the functional unit\n */\nabstract class IterativeFunctionalUnit(dataWidth: Int)(implicit p: Parameters)\n extends FunctionalUnit(\n isPipelined = false,\n numStages = 1,\n numBypassStages = 0,\n dataWidth = dataWidth)\n{\n val r_uop = Reg(new MicroOp())\n\n val do_kill = Wire(Bool())\n do_kill := io.req.bits.kill // irrelevant default\n\n when (io.req.fire) {\n // update incoming uop\n do_kill := IsKilledByBranch(io.brupdate, io.req.bits.uop) || io.req.bits.kill\n r_uop := io.req.bits.uop\n r_uop.br_mask := GetNewBrMask(io.brupdate, io.req.bits.uop)\n } .otherwise {\n do_kill := IsKilledByBranch(io.brupdate, r_uop) || io.req.bits.kill\n r_uop.br_mask := GetNewBrMask(io.brupdate, r_uop)\n }\n\n // assumes at least one pipeline register between request and response\n io.resp.bits.uop := r_uop\n}\n\n/**\n * Divide functional unit.\n *\n * @param dataWidth data to be passed into the functional unit\n */\nclass DivUnit(dataWidth: Int)(implicit p: Parameters)\n extends IterativeFunctionalUnit(dataWidth)\n{\n\n // We don't use the iterative multiply functionality here.\n // Instead we use the PipelinedMultiplier\n val div = Module(new freechips.rocketchip.rocket.MulDiv(mulDivParams, width = dataWidth))\n\n // request\n div.io.req.valid := io.req.valid && !this.do_kill\n div.io.req.bits.dw := io.req.bits.uop.ctrl.fcn_dw\n div.io.req.bits.fn := io.req.bits.uop.ctrl.op_fcn\n div.io.req.bits.in1 := io.req.bits.rs1_data\n div.io.req.bits.in2 := io.req.bits.rs2_data\n div.io.req.bits.tag := DontCare\n io.req.ready := div.io.req.ready\n\n // handle pipeline kills and branch misspeculations\n div.io.kill := this.do_kill\n\n // response\n io.resp.valid := div.io.resp.valid && !this.do_kill\n div.io.resp.ready := io.resp.ready\n io.resp.bits.data := div.io.resp.bits.data\n}\n\n/**\n * Pipelined multiplier functional unit that wraps around the RocketChip pipelined multiplier\n *\n * @param numStages number of pipeline stages\n * @param dataWidth size of the data being passed into the functional unit\n */\nclass PipelinedMulUnit(numStages: Int, dataWidth: Int)(implicit p: Parameters)\n extends PipelinedFunctionalUnit(\n numStages = numStages,\n numBypassStages = 0,\n earliestBypassStage = 0,\n dataWidth = dataWidth)\n{\n val imul = Module(new PipelinedMultiplier(xLen, numStages))\n // request\n imul.io.req.valid := io.req.valid\n imul.io.req.bits.fn := io.req.bits.uop.ctrl.op_fcn\n imul.io.req.bits.dw := io.req.bits.uop.ctrl.fcn_dw\n imul.io.req.bits.in1 := io.req.bits.rs1_data\n imul.io.req.bits.in2 := io.req.bits.rs2_data\n imul.io.req.bits.tag := DontCare\n // response\n io.resp.bits.data := imul.io.resp.bits.data\n}\n", "groundtruth": "class BrResolutionInfo(implicit p: Parameters) extends BoomBundle\n", "crossfile_context": ""}
{"task_id": "riscv-boom", "path": "riscv-boom/src/main/scala/v3/exu/fp-pipeline.scala", "left_context": "//******************************************************************************\n// Copyright (c) 2015 - 2018, The Regents of the University of California (Regents).\n// All Rights Reserved. See LICENSE and LICENSE.SiFive for license details.\n//------------------------------------------------------------------------------\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\n// Floating Point Datapath Pipeline\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\n\npackage boom.v3.exu\n\nimport chisel3._\nimport chisel3.util._\n\nimport org.chipsalliance.cde.config.{Parameters}\nimport freechips.rocketchip.rocket\nimport freechips.rocketchip.tile\n\nimport boom.v3.exu.FUConstants._\nimport boom.v3.common._\nimport boom.v3.util.{BoomCoreStringPrefix}\n\n/**\n * Top level datapath that wraps the floating point issue window, regfile, and arithmetic units.\n */\n", "right_context": "{\n val fpIssueParams = issueParams.find(_.iqType == IQT_FP.litValue).get\n val dispatchWidth = fpIssueParams.dispatchWidth\n val numLlPorts = memWidth\n val numWakeupPorts = fpIssueParams.issueWidth + numLlPorts\n val fpPregSz = log2Ceil(numFpPhysRegs)\n\n val io = IO(new Bundle {\n val brupdate = Input(new BrUpdateInfo())\n val flush_pipeline = Input(Bool())\n val fcsr_rm = Input(UInt(width=freechips.rocketchip.tile.FPConstants.RM_SZ.W))\n val status = Input(new freechips.rocketchip.rocket.MStatus())\n\n val dis_uops = Vec(dispatchWidth, Flipped(Decoupled(new MicroOp)))\n\n // +1 for recoding.\n val ll_wports = Flipped(Vec(memWidth, Decoupled(new ExeUnitResp(fLen+1))))// from memory unit\n val from_int = Flipped(Decoupled(new ExeUnitResp(fLen+1)))// from integer RF\n val to_sdq = Decoupled(new ExeUnitResp(fLen)) // to Load/Store Unit\n val to_int = Decoupled(new ExeUnitResp(xLen)) // to integer RF\n\n val wakeups = Vec(numWakeupPorts, Valid(new ExeUnitResp(fLen+1)))\n val wb_valids = Input(Vec(numWakeupPorts, Bool()))\n val wb_pdsts = Input(Vec(numWakeupPorts, UInt(width=fpPregSz.W)))\n\n val debug_tsc_reg = Input(UInt(width=xLen.W))\n val debug_wb_wdata = Output(Vec(numWakeupPorts, UInt((fLen+1).W)))\n })\n\n //**********************************\n // construct all of the modules\n\n val exe_units = new boom.v3.exu.ExecutionUnits(fpu=true)\n val issue_unit = Module(new IssueUnitCollapsing(\n issueParams.find(_.iqType == IQT_FP.litValue).get,\n numWakeupPorts))\n issue_unit.suggestName(\"fp_issue_unit\")\n val fregfile = Module(new RegisterFileSynthesizable(numFpPhysRegs,\n exe_units.numFrfReadPorts,\n exe_units.numFrfWritePorts + memWidth,\n fLen+1,\n // No bypassing for any FP units, + memWidth for ll_wb\n Seq.fill(exe_units.numFrfWritePorts + memWidth){ false }\n ))\n val fregister_read = Module(new RegisterRead(\n issue_unit.issueWidth,\n exe_units.withFilter(_.readsFrf).map(_.supportedFuncUnits).toSeq,\n exe_units.numFrfReadPorts,\n exe_units.withFilter(_.readsFrf).map(x => 3).toSeq,\n 0, // No bypass for FP\n 0,\n fLen+1))\n\n require (exe_units.count(_.readsFrf) == issue_unit.issueWidth)\n require (exe_units.numFrfWritePorts + numLlPorts == numWakeupPorts)\n\n //*************************************************************\n // Issue window logic\n\n val iss_valids = Wire(Vec(exe_units.numFrfReaders, Bool()))\n val iss_uops = Wire(Vec(exe_units.numFrfReaders, new MicroOp()))\n\n issue_unit.io.tsc_reg := io.debug_tsc_reg\n issue_unit.io.brupdate := io.brupdate\n issue_unit.io.flush_pipeline := io.flush_pipeline\n // Don't support ld-hit speculation to FP window.\n for (w <- 0 until memWidth) {\n issue_unit.io.spec_ld_wakeup(w).valid := false.B\n issue_unit.io.spec_ld_wakeup(w).bits := 0.U\n }\n issue_unit.io.ld_miss := false.B\n\n require (exe_units.numTotalBypassPorts == 0)\n\n //-------------------------------------------------------------\n // **** Dispatch Stage ****\n //-------------------------------------------------------------\n\n // Input (Dispatch)\n for (w <- 0 until dispatchWidth) {\n issue_unit.io.dis_uops(w) <> io.dis_uops(w)\n }\n\n //-------------------------------------------------------------\n // **** Issue Stage ****\n //-------------------------------------------------------------\n\n // Output (Issue)\n for (i <- 0 until issue_unit.issueWidth) {\n iss_valids(i) := issue_unit.io.iss_valids(i)\n iss_uops(i) := issue_unit.io.iss_uops(i)\n\n var fu_types = exe_units(i).io.fu_types\n if (exe_units(i).supportedFuncUnits.fdiv) {\n val fdiv_issued = iss_valids(i) && iss_uops(i).fu_code_is(FU_FDV)\n fu_types = fu_types & RegNext(~Mux(fdiv_issued, FU_FDV, 0.U))\n }\n issue_unit.io.fu_types(i) := fu_types\n\n require (exe_units(i).readsFrf)\n }\n\n // Wakeup\n for ((writeback, issue_wakeup) <- io.wakeups zip issue_unit.io.wakeup_ports) {\n issue_wakeup.valid := writeback.valid\n issue_wakeup.bits.pdst := writeback.bits.uop.pdst\n issue_wakeup.bits.poisoned := false.B\n }\n issue_unit.io.pred_wakeup_port.valid := false.B\n issue_unit.io.pred_wakeup_port.bits := DontCare\n\n //-------------------------------------------------------------\n // **** Register Read Stage ****\n //-------------------------------------------------------------\n\n // Register Read <- Issue (rrd <- iss)\n fregister_read.io.rf_read_ports <> fregfile.io.read_ports\n fregister_read.io.prf_read_ports map { port => port.data := false.B }\n\n fregister_read.io.iss_valids <> iss_valids\n fregister_read.io.iss_uops := iss_uops\n\n fregister_read.io.brupdate := io.brupdate\n fregister_read.io.kill := io.flush_pipeline\n\n //-------------------------------------------------------------\n // **** Execute Stage ****\n //-------------------------------------------------------------\n\n exe_units.map(_.io.brupdate := io.brupdate)\n\n for ((ex,w) <- exe_units.withFilter(_.readsFrf).map(x=>x).zipWithIndex) {\n ex.io.req <> fregister_read.io.exe_reqs(w)\n require (!ex.bypassable)\n }\n require (exe_units.numTotalBypassPorts == 0)\n\n //-------------------------------------------------------------\n // **** Writeback Stage ****\n //-------------------------------------------------------------\n\n val ll_wbarb = Module(new Arbiter(new ExeUnitResp(fLen+1), 2))\n\n\n // Hookup load writeback -- and recode FP values.\n ll_wbarb.io.in(0) <> io.ll_wports(0)\n ll_wbarb.io.in(0).bits.data := recode(io.ll_wports(0).bits.data,\n io.ll_wports(0).bits.uop.mem_size =/= 2.U)\n\n val ifpu_resp = io.from_int\n ll_wbarb.io.in(1) <> ifpu_resp\n\n\n // Cut up critical path by delaying the write by a cycle.\n // Wakeup signal is sent on cycle S0, write is now delayed until end of S1,\n // but Issue happens on S1 and RegRead doesn't happen until S2 so we're safe.\n fregfile.io.write_ports(0) := RegNext(WritePort(ll_wbarb.io.out, fpregSz, fLen+1, RT_FLT))\n\n assert (ll_wbarb.io.in(0).ready) // never backpressure the memory unit.\n when (ifpu_resp.valid) { assert (ifpu_resp.bits.uop.rf_wen && ifpu_resp.bits.uop.dst_rtype === RT_FLT) }\n\n var w_cnt = 1\n for (i <- 1 until memWidth) {\n fregfile.io.write_ports(w_cnt) := RegNext(WritePort(io.ll_wports(i), fpregSz, fLen+1, RT_FLT))\n fregfile.io.write_ports(w_cnt).bits.data := RegNext(recode(io.ll_wports(i).bits.data,\n io.ll_wports(i).bits.uop.mem_size =/= 2.U))\n w_cnt += 1\n }\n for (eu <- exe_units) {\n if (eu.writesFrf) {\n fregfile.io.write_ports(w_cnt).valid := eu.io.fresp.valid && eu.io.fresp.bits.uop.rf_wen\n fregfile.io.write_ports(w_cnt).bits.addr := eu.io.fresp.bits.uop.pdst\n fregfile.io.write_ports(w_cnt).bits.data := eu.io.fresp.bits.data\n eu.io.fresp.ready := true.B\n when (eu.io.fresp.valid) {\n assert(eu.io.fresp.ready, \"No backpressuring the FPU\")\n assert(eu.io.fresp.bits.uop.rf_wen, \"rf_wen must be high here\")\n assert(eu.io.fresp.bits.uop.dst_rtype === RT_FLT, \"wb type must be FLT for fpu\")\n }\n w_cnt += 1\n }\n }\n require (w_cnt == fregfile.io.write_ports.length)\n\n val fpiu_unit = exe_units.fpiu_unit\n val fpiu_is_sdq = fpiu_unit.io.ll_iresp.bits.uop.uopc === uopSTA\n io.to_int.valid := fpiu_unit.io.ll_iresp.fire && !fpiu_is_sdq\n io.to_sdq.valid := fpiu_unit.io.ll_iresp.fire && fpiu_is_sdq\n io.to_int.bits := fpiu_unit.io.ll_iresp.bits\n io.to_sdq.bits := fpiu_unit.io.ll_iresp.bits\n fpiu_unit.io.ll_iresp.ready := io.to_sdq.ready && io.to_int.ready\n\n //-------------------------------------------------------------\n //-------------------------------------------------------------\n // **** Commit Stage ****\n //-------------------------------------------------------------\n //-------------------------------------------------------------\n\n io.wakeups(0).valid := ll_wbarb.io.out.valid\n io.wakeups(0).bits := ll_wbarb.io.out.bits\n ll_wbarb.io.out.ready := true.B\n\n w_cnt = 1\n for (i <- 1 until memWidth) {\n io.wakeups(w_cnt) := io.ll_wports(i)\n io.wakeups(w_cnt).bits.data := recode(io.ll_wports(i).bits.data,\n io.ll_wports(i).bits.uop.mem_size =/= 2.U)\n w_cnt += 1\n }\n for (eu <- exe_units) {\n if (eu.writesFrf) {\n val exe_resp = eu.io.fresp\n val wb_uop = eu.io.fresp.bits.uop\n val wport = io.wakeups(w_cnt)\n wport.valid := exe_resp.valid && wb_uop.dst_rtype === RT_FLT\n wport.bits := exe_resp.bits\n\n w_cnt += 1\n\n assert(!(exe_resp.valid && wb_uop.uses_ldq))\n assert(!(exe_resp.valid && wb_uop.uses_stq))\n assert(!(exe_resp.valid && wb_uop.is_amo))\n }\n }\n\n for ((wdata, wakeup) <- io.debug_wb_wdata zip io.wakeups) {\n wdata := ieee(wakeup.bits.data)\n }\n\n exe_units.map(_.io.fcsr_rm := io.fcsr_rm)\n exe_units.map(_.io.status := io.status)\n\n //-------------------------------------------------------------\n // **** Flush Pipeline ****\n //-------------------------------------------------------------\n // flush on exceptions, miniexeptions, and after some special instructions\n\n for (w <- 0 until exe_units.length) {\n exe_units(w).io.req.bits.kill := io.flush_pipeline\n }\n\n override def toString: String =\n (BoomCoreStringPrefix(\"===FP Pipeline===\") + \"\\n\"\n + fregfile.toString\n + BoomCoreStringPrefix(\n \"Num Wakeup Ports : \" + numWakeupPorts,\n \"Num Bypass Ports : \" + exe_units.numTotalBypassPorts))\n}\n", "groundtruth": "class FpPipeline(implicit p: Parameters) extends BoomModule with tile.HasFPUParameters\n", "crossfile_context": ""}
{"task_id": "riscv-boom", "path": "riscv-boom/src/main/scala/v3/exu/rename/rename-maptable.scala", "left_context": "//******************************************************************************\n// Copyright (c) 2015 - 2019, The Regents of the University of California (Regents).\n// All Rights Reserved. See LICENSE and LICENSE.SiFive for license details.\n//------------------------------------------------------------------------------\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\n// Rename Map Table\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\n\npackage boom.v3.exu\n\nimport chisel3._\nimport chisel3.util._\nimport boom.v3.common._\nimport boom.v3.util._\nimport org.chipsalliance.cde.config.Parameters\n\nclass MapReq(val lregSz: Int) extends Bundle\n{\n val lrs1 = UInt(lregSz.W)\n val lrs2 = UInt(lregSz.W)\n val lrs3 = UInt(lregSz.W)\n val ldst = UInt(lregSz.W)\n}\n\nclass MapResp(val pregSz: Int) extends Bundle\n{\n val prs1 = UInt(pregSz.W)\n val prs2 = UInt(pregSz.W)\n val prs3 = UInt(pregSz.W)\n val stale_pdst = UInt(pregSz.W)\n}\n\nclass RemapReq(val lregSz: Int, val pregSz: Int) extends Bundle\n{\n val ldst = UInt(lregSz.W)\n val pdst = UInt(pregSz.W)\n val valid = Bool()\n}\n\nclass RenameMapTable(\n val plWidth: Int,\n val numLregs: Int,\n val numPregs: Int,\n val bypass: Boolean,\n val float: Boolean)\n (implicit p: Parameters) extends BoomModule\n{\n val pregSz = log2Ceil(numPregs)\n\n val io = IO(new BoomBundle()(p) {\n // Logical sources -> physical sources.\n val map_reqs = Input(Vec(plWidth, new MapReq(lregSz)))\n val map_resps = Output(Vec(plWidth, new MapResp(pregSz)))\n\n // Remapping an ldst to a newly allocated pdst?\n val remap_reqs = Input(Vec(plWidth, new RemapReq(lregSz, pregSz)))\n\n // Dispatching branches: need to take snapshots of table state.\n val ren_br_tags = Input(Vec(plWidth, Valid(UInt(brTagSz.W))))\n\n // Signals for restoring state following misspeculation.\n val brupdate = Input(new BrUpdateInfo)\n val rollback = Input(Bool())\n })\n\n // The map table register array and its branch snapshots.\n val map_table = RegInit(VecInit(Seq.fill(numLregs){0.U(pregSz.W)}))\n val br_snapshots = Reg(Vec(maxBrCount, Vec(numLregs, UInt(pregSz.W))))\n\n // The intermediate states of the map table following modification by each pipeline slot.\n val remap_table = Wire(Vec(plWidth+1, Vec(numLregs, UInt(pregSz.W))))\n\n // Uops requesting changes to the map table.\n val remap_pdsts = io.remap_reqs map (_.pdst)\n val remap_ldsts_oh = io.remap_reqs map (req => UIntToOH(req.ldst) & Fill(numLregs, req.valid.asUInt))\n\n // Figure out the new mappings seen by each pipeline slot.\n for (i <- 0 until numLregs) {\n if (i == 0 && !float) {\n for (j <- 0 until plWidth+1) {\n remap_table(j)(i) := 0.U\n }\n } else {\n val remapped_row = (remap_ldsts_oh.map(ldst => ldst(i)) zip remap_pdsts)\n .scanLeft(map_table(i)) {case (pdst, (ldst, new_pdst)) => Mux(ldst, new_pdst, pdst)}\n\n for (j <- 0 until plWidth+1) {\n remap_table(j)(i) := remapped_row(j)\n }\n }\n }\n\n // Create snapshots of new mappings.\n for (i <- 0 until plWidth) {\n when (io.ren_br_tags(i).valid) {\n br_snapshots(io.ren_br_tags(i).bits) := remap_table(i+1)\n }\n }\n\n when (io.brupdate.b2.mispredict) {\n // Restore the map table to a branch snapshot.\n map_table := br_snapshots(io.brupdate.b2.uop.br_tag)\n } .otherwise {\n // Update mappings.\n map_table := remap_table(plWidth)\n }\n\n // Read out mappings.\n for (i <- 0 until plWidth) {\n io.map_resps(i).prs1 := (0 until i).foldLeft(map_table(io.map_reqs(i).lrs1)) ((p,k) =>\n Mux(bypass.B && io.remap_reqs(k).valid && io.remap_reqs(k).ldst === io.map_reqs(i).lrs1, io.remap_reqs(k).pdst, p))\n io.map_resps(i).prs2 := (0 until i).foldLeft(map_table(io.map_reqs(i).lrs2)) ((p,k) =>\n Mux(bypass.B && io.remap_reqs(k).valid && io.remap_reqs(k).ldst === io.map_reqs(i).lrs2, io.remap_reqs(k).pdst, p))\n io.map_resps(i).prs3 := (0 until i).foldLeft(map_table(io.map_reqs(i).lrs3)) ((p,k) =>\n Mux(bypass.B && io.remap_reqs(k).valid && io.remap_reqs(k).ldst === io.map_reqs(i).lrs3, io.remap_reqs(k).pdst, p))\n io.map_resps(i).stale_pdst := (0 until i).foldLeft(map_table(io.map_reqs(i).ldst)) ((p,k) =>\n Mux(bypass.B && io.remap_reqs(k).valid && io.remap_reqs(k).ldst === io.map_reqs(i).ldst, io.remap_reqs(k).pdst, p))\n\n", "right_context": " }\n\n // Don't flag the creation of duplicate 'p0' mappings during rollback.\n // These cases may occur soon after reset, as all maptable entries are initialized to 'p0'.\n io.remap_reqs map (req => (req.pdst, req.valid)) foreach {case (p,r) =>\n assert (!r || !map_table.contains(p) || p === 0.U && io.rollback, \"[maptable] Trying to write a duplicate mapping.\")}\n}\n", "groundtruth": " if (!float) io.map_resps(i).prs3 := DontCare\n", "crossfile_context": ""}
{"task_id": "riscv-boom", "path": "riscv-boom/src/main/scala/v3/ifu/bpd/bim.scala", "left_context": "package boom.v3.ifu\n\nimport chisel3._\nimport chisel3.util._\n\nimport org.chipsalliance.cde.config.{Field, Parameters}\nimport freechips.rocketchip.diplomacy._\nimport freechips.rocketchip.tilelink._\n\nimport boom.v3.common._\nimport boom.v3.util.{BoomCoreStringPrefix, WrapInc}\nimport scala.math.min\n\n\n\n", "right_context": " with HasBoomFrontendParameters\n{\n val bims = Vec(bankWidth, UInt(2.W))\n}\n\ncase class BoomBIMParams(\n nSets: Int = 2048\n)\n\nclass BIMBranchPredictorBank(params: BoomBIMParams = BoomBIMParams())(implicit p: Parameters) extends BranchPredictorBank()(p)\n{\n override val nSets = params.nSets\n\n require(isPow2(nSets))\n\n val nWrBypassEntries = 2\n\n def bimWrite(v: UInt, taken: Bool): UInt = {\n val old_bim_sat_taken = v === 3.U\n val old_bim_sat_ntaken = v === 0.U\n Mux(old_bim_sat_taken && taken, 3.U,\n Mux(old_bim_sat_ntaken && !taken, 0.U,\n Mux(taken, v + 1.U, v - 1.U)))\n }\n val s2_meta = Wire(new BIMMeta)\n override val metaSz = s2_meta.asUInt.getWidth\n\n val doing_reset = RegInit(true.B)\n val reset_idx = RegInit(0.U(log2Ceil(nSets).W))\n reset_idx := reset_idx + doing_reset\n when (reset_idx === (nSets-1).U) { doing_reset := false.B }\n\n\n val data = SyncReadMem(nSets, Vec(bankWidth, UInt(2.W)))\n\n val mems = Seq((\"bim\", nSets, bankWidth * 2))\n\n val s2_req_rdata = RegNext(data.read(s0_idx , s0_valid))\n\n val s2_resp = Wire(Vec(bankWidth, Bool()))\n\n for (w <- 0 until bankWidth) {\n\n s2_resp(w) := s2_valid && s2_req_rdata(w)(1) && !doing_reset\n s2_meta.bims(w) := s2_req_rdata(w)\n }\n\n\n val s1_update_wdata = Wire(Vec(bankWidth, UInt(2.W)))\n val s1_update_wmask = Wire(Vec(bankWidth, Bool()))\n val s1_update_meta = s1_update.bits.meta.asTypeOf(new BIMMeta)\n val s1_update_index = s1_update_idx\n\n val wrbypass_idxs = Reg(Vec(nWrBypassEntries, UInt(log2Ceil(nSets).W)))\n val wrbypass = Reg(Vec(nWrBypassEntries, Vec(bankWidth, UInt(2.W))))\n val wrbypass_enq_idx = RegInit(0.U(log2Ceil(nWrBypassEntries).W))\n\n val wrbypass_hits = VecInit((0 until nWrBypassEntries) map { i =>\n !doing_reset &&\n wrbypass_idxs(i) === s1_update_index(log2Ceil(nSets)-1,0)\n })\n val wrbypass_hit = wrbypass_hits.reduce(_||_)\n val wrbypass_hit_idx = PriorityEncoder(wrbypass_hits)\n\n\n\n for (w <- 0 until bankWidth) {\n s1_update_wmask(w) := false.B\n s1_update_wdata(w) := DontCare\n\n val update_pc = s1_update.bits.pc + (w << 1).U\n\n when (s1_update.bits.br_mask(w) ||\n (s1_update.bits.cfi_idx.valid && s1_update.bits.cfi_idx.bits === w.U)) {\n val was_taken = (\n s1_update.bits.cfi_idx.valid &&\n (s1_update.bits.cfi_idx.bits === w.U) &&\n (\n (s1_update.bits.cfi_is_br && s1_update.bits.br_mask(w) && s1_update.bits.cfi_taken) ||\n s1_update.bits.cfi_is_jal\n )\n )\n val old_bim_value = Mux(wrbypass_hit, wrbypass(wrbypass_hit_idx)(w), s1_update_meta.bims(w))\n\n s1_update_wmask(w) := true.B\n\n s1_update_wdata(w) := bimWrite(old_bim_value, was_taken)\n }\n\n\n }\n\n when (doing_reset || (s1_update.valid && s1_update.bits.is_commit_update)) {\n data.write(\n Mux(doing_reset, reset_idx, s1_update_index),\n Mux(doing_reset, VecInit(Seq.fill(bankWidth) { 2.U }), s1_update_wdata),\n Mux(doing_reset, (~(0.U(bankWidth.W))), s1_update_wmask.asUInt).asBools\n )\n }\n when (s1_update_wmask.reduce(_||_) && s1_update.valid && s1_update.bits.is_commit_update) {\n when (wrbypass_hit) {\n wrbypass(wrbypass_hit_idx) := s1_update_wdata\n } .otherwise {\n wrbypass(wrbypass_enq_idx) := s1_update_wdata\n wrbypass_idxs(wrbypass_enq_idx) := s1_update_index\n wrbypass_enq_idx := WrapInc(wrbypass_enq_idx, nWrBypassEntries)\n }\n }\n\n for (w <- 0 until bankWidth) {\n io.resp.f2(w).taken := s2_resp(w)\n io.resp.f3(w).taken := RegNext(io.resp.f2(w).taken)\n }\n io.f3_meta := RegNext(s2_meta.asUInt)\n}\n", "groundtruth": "class BIMMeta(implicit p: Parameters) extends BoomBundle()(p)\n", "crossfile_context": ""}
{"task_id": "riscv-boom", "path": "riscv-boom/src/main/scala/v3/ifu/bpd/loop.scala", "left_context": "package boom.v3.ifu\n\nimport chisel3._\nimport chisel3.util._\n\nimport org.chipsalliance.cde.config.{Field, Parameters}\nimport freechips.rocketchip.diplomacy._\nimport freechips.rocketchip.tilelink._\n\nimport boom.v3.common._\nimport boom.v3.util.{BoomCoreStringPrefix}\n\nimport scala.math.min\n\ncase class BoomLoopPredictorParams(\n nWays: Int = 4,\n threshold: Int = 7\n)\n\nclass LoopBranchPredictorBank(implicit p: Parameters) extends BranchPredictorBank()(p)\n{\n val tagSz = 10\n override val nSets = 16\n\n\n\n class LoopMeta extends Bundle {\n val s_cnt = UInt(10.W)\n }\n\n class LoopEntry extends Bundle {\n val tag = UInt(tagSz.W)\n val conf = UInt(3.W)\n val age = UInt(3.W)\n val p_cnt = UInt(10.W)\n val s_cnt = UInt(10.W)\n }\n\n class LoopBranchPredictorColumn extends Module {\n\n\n\n val io = IO(new Bundle {\n val f2_req_valid = Input(Bool())\n val f2_req_idx = Input(UInt())\n val f3_req_fire = Input(Bool())\n\n val f3_pred_in = Input(Bool())\n val f3_pred = Output(Bool())\n val f3_meta = Output(new LoopMeta)\n\n val update_mispredict = Input(Bool())\n val update_repair = Input(Bool())\n val update_idx = Input(UInt())\n val update_resolve_dir = Input(Bool())\n val update_meta = Input(new LoopMeta)\n })\n\n val doing_reset = RegInit(true.B)\n val reset_idx = RegInit(0.U(log2Ceil(nSets).W))\n reset_idx := reset_idx + doing_reset\n", "right_context": "\n\n val entries = Reg(Vec(nSets, new LoopEntry))\n val f2_entry = WireInit(entries(io.f2_req_idx))\n when (io.update_repair && io.update_idx === io.f2_req_idx) {\n f2_entry.s_cnt := io.update_meta.s_cnt\n } .elsewhen (io.update_mispredict && io.update_idx === io.f2_req_idx) {\n f2_entry.s_cnt := 0.U\n }\n val f3_entry = RegNext(f2_entry)\n val f3_scnt = Mux(io.update_repair && io.update_idx === RegNext(io.f2_req_idx),\n io.update_meta.s_cnt,\n f3_entry.s_cnt)\n val f3_tag = RegNext(io.f2_req_idx(tagSz+log2Ceil(nSets)-1,log2Ceil(nSets)))\n\n io.f3_pred := io.f3_pred_in\n io.f3_meta.s_cnt := f3_scnt\n\n when (f3_entry.tag === f3_tag) {\n when (f3_scnt === f3_entry.p_cnt && f3_entry.conf === 7.U) {\n io.f3_pred := !io.f3_pred_in\n }\n }\n\n\n val f4_fire = RegNext(io.f3_req_fire)\n val f4_entry = RegNext(f3_entry)\n val f4_tag = RegNext(f3_tag)\n val f4_scnt = RegNext(f3_scnt)\n val f4_idx = RegNext(RegNext(io.f2_req_idx))\n\n\n when (f4_fire) {\n when (f4_entry.tag === f4_tag) {\n when (f4_scnt === f4_entry.p_cnt && f4_entry.conf === 7.U) {\n entries(f4_idx).age := 7.U\n entries(f4_idx).s_cnt := 0.U\n } .otherwise {\n entries(f4_idx).s_cnt := f4_scnt + 1.U\n entries(f4_idx).age := Mux(f4_entry.age === 7.U, 7.U, f4_entry.age + 1.U)\n }\n }\n }\n\n\n val entry = entries(io.update_idx)\n val tag = io.update_idx(tagSz+log2Ceil(nSets)-1,log2Ceil(nSets))\n val tag_match = entry.tag === tag\n val ctr_match = entry.p_cnt === io.update_meta.s_cnt\n val wentry = WireInit(entry)\n\n when (io.update_mispredict && !doing_reset) {\n\n // Learned, tag match -> decrement confidence\n when (entry.conf === 7.U && tag_match) {\n wentry.s_cnt := 0.U\n wentry.conf := 0.U\n\n // Learned, no tag match -> do nothing? Don't evict super-confident entries?\n } .elsewhen (entry.conf === 7.U && !tag_match) {\n\n // Confident, tag match, ctr_match -> increment confidence, reset counter\n } .elsewhen (entry.conf =/= 0.U && tag_match && ctr_match) {\n wentry.conf := entry.conf + 1.U\n wentry.s_cnt := 0.U\n\n // Confident, tag match, no ctr match -> zero confidence, reset counter, set previous counter\n } .elsewhen (entry.conf =/= 0.U && tag_match && !ctr_match) {\n wentry.conf := 0.U\n wentry.s_cnt := 0.U\n wentry.p_cnt := io.update_meta.s_cnt\n\n // Confident, no tag match, age is 0 -> replace this entry with our own, set our age high to avoid ping-pong\n } .elsewhen (entry.conf =/= 0.U && !tag_match && entry.age === 0.U) {\n wentry.tag := tag\n wentry.conf := 1.U\n wentry.s_cnt := 0.U\n wentry.p_cnt := io.update_meta.s_cnt\n\n // Confident, no tag match, age > 0 -> decrement age\n } .elsewhen (entry.conf =/= 0.U && !tag_match && entry.age =/= 0.U) {\n wentry.age := entry.age - 1.U\n\n // Unconfident, tag match, ctr match -> increment confidence\n } .elsewhen (entry.conf === 0.U && tag_match && ctr_match) {\n wentry.conf := 1.U\n wentry.age := 7.U\n wentry.s_cnt := 0.U\n\n // Unconfident, tag match, no ctr match -> set previous counter\n } .elsewhen (entry.conf === 0.U && tag_match && !ctr_match) {\n wentry.p_cnt := io.update_meta.s_cnt\n wentry.age := 7.U\n wentry.s_cnt := 0.U\n\n // Unconfident, no tag match -> set previous counter and tag\n } .elsewhen (entry.conf === 0.U && !tag_match) {\n wentry.tag := tag\n wentry.conf := 1.U\n wentry.age := 7.U\n wentry.s_cnt := 0.U\n wentry.p_cnt := io.update_meta.s_cnt\n }\n\n entries(io.update_idx) := wentry\n } .elsewhen (io.update_repair && !doing_reset) {\n when (tag_match && !(f4_fire && io.update_idx === f4_idx)) {\n wentry.s_cnt := io.update_meta.s_cnt\n entries(io.update_idx) := wentry\n }\n }\n\n when (doing_reset) {\n entries(reset_idx) := (0.U).asTypeOf(new LoopEntry)\n }\n\n }\n\n\n val columns = Seq.fill(bankWidth) { Module(new LoopBranchPredictorColumn) }\n val mems = Nil // TODO fix\n val f3_meta = Wire(Vec(bankWidth, new LoopMeta))\n override val metaSz = f3_meta.asUInt.getWidth\n\n val update_meta = s1_update.bits.meta.asTypeOf(Vec(bankWidth, new LoopMeta))\n\n for (w <- 0 until bankWidth) {\n columns(w).io.f2_req_valid := s2_valid\n columns(w).io.f2_req_idx := s2_idx\n columns(w).io.f3_req_fire := (s3_valid && s3_mask(w) && io.f3_fire &&\n RegNext(io.resp_in(0).f2(w).predicted_pc.valid && io.resp_in(0).f2(w).is_br))\n\n columns(w).io.f3_pred_in := io.resp_in(0).f3(w).taken\n io.resp.f3(w).taken := columns(w).io.f3_pred\n\n columns(w).io.update_mispredict := (s1_update.valid &&\n s1_update.bits.br_mask(w) &&\n s1_update.bits.is_mispredict_update &&\n s1_update.bits.cfi_mispredicted)\n columns(w).io.update_repair := (s1_update.valid &&\n s1_update.bits.br_mask(w) &&\n s1_update.bits.is_repair_update)\n columns(w).io.update_idx := s1_update_idx\n columns(w).io.update_resolve_dir := s1_update.bits.cfi_taken\n columns(w).io.update_meta := update_meta(w)\n\n f3_meta(w) := columns(w).io.f3_meta\n }\n\n io.f3_meta := f3_meta.asUInt\n\n}\n", "groundtruth": " when (reset_idx === (nSets-1).U) { doing_reset := false.B }\n", "crossfile_context": ""}
{"task_id": "riscv-boom", "path": "riscv-boom/src/main/scala/v3/ifu/bpd/sw_predictor.scala", "left_context": "package boom.v3.ifu\n\nimport chisel3._\nimport chisel3.util._\n\nimport org.chipsalliance.cde.config.{Field, Parameters}\nimport freechips.rocketchip.diplomacy._\nimport freechips.rocketchip.tilelink._\n\nimport boom.v3.common._\nimport boom.v3.exu.{CommitExceptionSignals}\nimport boom.v3.util.{BoomCoreStringPrefix}\n\n\nclass SwBranchPredictorBank(implicit p: Parameters) extends BranchPredictorBank()(p)\n{\n val mems = Nil\n for (w <- 0 until bankWidth) {\n val btb_harness = Module(new BTBHarness)\n val pred_harness = Module(new BranchPredictorHarness)\n\n btb_harness.io.clock := clock\n btb_harness.io.reset := reset.asBool\n\n pred_harness.io.clock := clock\n pred_harness.io.reset := reset.asBool\n\n\n btb_harness.io.req_valid := s1_valid\n btb_harness.io.req_pc := bankAlign(s1_pc) + (w << 1).U\n btb_harness.io.req_hist := io.f1_ghist\n\n pred_harness.io.req_valid := s1_valid\n pred_harness.io.req_pc := bankAlign(s1_pc) + (w << 1).U\n pred_harness.io.req_hist := io.f1_ghist\n\n btb_harness.io.update_valid := io.update.valid && io.update.bits.is_commit_update && io.update.bits.cfi_idx.valid && (w == 0).B\n btb_harness.io.update_pc := io.update.bits.pc + (io.update.bits.cfi_idx.bits << 1)\n btb_harness.io.update_hist := io.update.bits.ghist\n btb_harness.io.update_target := io.update.bits.target\n btb_harness.io.update_is_br := io.update.bits.cfi_is_br\n btb_harness.io.update_is_jal := io.update.bits.cfi_is_jal\n\n pred_harness.io.update_valid := io.update.valid && io.update.bits.is_commit_update && io.update.bits.br_mask(w)\n pred_harness.io.update_pc := io.update.bits.pc + (w << 1).U\n pred_harness.io.update_hist := io.update.bits.ghist\n pred_harness.io.update_taken := w.U === io.update.bits.cfi_idx.bits &&\n io.update.bits.cfi_idx.valid && io.update.bits.cfi_taken\n\n\n io.resp.f2(w).taken := pred_harness.io.req_taken\n io.resp.f2(w).predicted_pc.valid := btb_harness.io.req_target_valid\n io.resp.f2(w).predicted_pc.bits := btb_harness.io.req_target_pc\n io.resp.f2(w).is_br := btb_harness.io.req_is_br && btb_harness.io.req_target_valid\n io.resp.f2(w).is_jal := btb_harness.io.req_is_jal && btb_harness.io.req_target_valid\n\n // The Harness to software assumes output comes out in f2\n io.resp.f3(w).is_br := RegNext(pred_harness.io.req_taken)\n io.resp.f3(w).taken := RegNext(pred_harness.io.req_taken)\n }\n}\n\nclass BranchPredictorHarness(implicit p: Parameters)\n extends BlackBox with HasBlackBoxResource {\n val io = IO(new Bundle {\n val clock = Input(Clock())\n val reset = Input(Bool())\n\n val req_valid = Input(Bool())\n val req_pc = Input(UInt(64.W))\n val req_hist = Input(UInt(64.W))\n val req_taken = Output(Bool())\n\n val update_valid = Input(Bool())\n val update_pc = Input(UInt(64.W))\n val update_hist = Input(UInt(64.W))\n val update_taken = Input(Bool())\n })\n\n", "right_context": " extends BlackBox with HasBlackBoxResource {\n val io = IO(new Bundle {\n val clock = Input(Clock())\n val reset = Input(Bool())\n\n val req_valid = Input(Bool())\n val req_pc = Input(UInt(64.W))\n val req_hist = Input(UInt(64.W))\n val req_target_valid = Output(Bool())\n val req_target_pc = Output(UInt(64.W))\n val req_is_br = Output(Bool())\n val req_is_jal = Output(Bool())\n\n val update_valid = Input(Bool())\n val update_pc = Input(UInt(64.W))\n val update_hist = Input(UInt(64.W))\n val update_target = Input(UInt(64.W))\n val update_is_br = Input(Bool())\n val update_is_jal = Input(Bool())\n })\n\n addResource(\"/vsrc/btb_harness.v\")\n addResource(\"/csrc/btb_sw.cc\")\n}\n", "groundtruth": " addResource(\"/vsrc/predictor_harness.v\")\n addResource(\"/csrc/predictor_sw.cc\")\n}\n", "crossfile_context": ""}
{"task_id": "riscv-boom", "path": "riscv-boom/src/main/scala/v3/util/util.scala", "left_context": "//******************************************************************************\n// Copyright (c) 2015 - 2019, The Regents of the University of California (Regents).\n// All Rights Reserved. See LICENSE and LICENSE.SiFive for license details.\n//------------------------------------------------------------------------------\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\n// Utility Functions\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\n\npackage boom.v3.util\n\nimport chisel3._\nimport chisel3.util._\n\nimport freechips.rocketchip.rocket.Instructions._\nimport freechips.rocketchip.rocket._\nimport freechips.rocketchip.util.{Str}\nimport org.chipsalliance.cde.config.{Parameters}\nimport freechips.rocketchip.tile.{TileKey}\n\nimport boom.v3.common.{MicroOp}\nimport boom.v3.exu.{BrUpdateInfo}\n\n/**\n * Object to XOR fold a input register of fullLength into a compressedLength.\n */\nobject Fold\n{\n def apply(input: UInt, compressedLength: Int, fullLength: Int): UInt = {\n val clen = compressedLength\n val hlen = fullLength\n if (hlen <= clen) {\n input\n } else {\n var res = 0.U(clen.W)\n var remaining = input.asUInt\n for (i <- 0 to hlen-1 by clen) {\n val len = if (i + clen > hlen ) (hlen - i) else clen\n require(len > 0)\n res = res(clen-1,0) ^ remaining(len-1,0)\n remaining = remaining >> len.U\n }\n res\n }\n }\n}\n\n/**\n * Object to check if MicroOp was killed due to a branch mispredict.\n * Uses \"Fast\" branch masks\n */\nobject IsKilledByBranch\n{\n def apply(brupdate: BrUpdateInfo, uop: MicroOp): Bool = {\n return maskMatch(brupdate.b1.mispredict_mask, uop.br_mask)\n }\n\n def apply(brupdate: BrUpdateInfo, uop_mask: UInt): Bool = {\n return maskMatch(brupdate.b1.mispredict_mask, uop_mask)\n }\n}\n\n/**\n * Object to return new MicroOp with a new BR mask given a MicroOp mask\n * and old BR mask.\n */\nobject GetNewUopAndBrMask\n{\n def apply(uop: MicroOp, brupdate: BrUpdateInfo)\n (implicit p: Parameters): MicroOp = {\n val newuop = WireInit(uop)\n newuop.br_mask := uop.br_mask & ~brupdate.b1.resolve_mask\n newuop\n }\n}\n\n/**\n * Object to return a BR mask given a MicroOp mask and old BR mask.\n */\nobject GetNewBrMask\n{\n def apply(brupdate: BrUpdateInfo, uop: MicroOp): UInt = {\n return uop.br_mask & ~brupdate.b1.resolve_mask\n }\n\n def apply(brupdate: BrUpdateInfo, br_mask: UInt): UInt = {\n return br_mask & ~brupdate.b1.resolve_mask\n }\n}\n\nobject UpdateBrMask\n{\n def apply(brupdate: BrUpdateInfo, uop: MicroOp): MicroOp = {\n val out = WireInit(uop)\n out.br_mask := GetNewBrMask(brupdate, uop)\n out\n }\n def apply[T <: boom.v3.common.HasBoomUOP](brupdate: BrUpdateInfo, bundle: T): T = {\n val out = WireInit(bundle)\n out.uop.br_mask := GetNewBrMask(brupdate, bundle.uop.br_mask)\n out\n }\n def apply[T <: boom.v3.common.HasBoomUOP](brupdate: BrUpdateInfo, bundle: Valid[T]): Valid[T] = {\n val out = WireInit(bundle)\n out.bits.uop.br_mask := GetNewBrMask(brupdate, bundle.bits.uop.br_mask)\n out.valid := bundle.valid && !IsKilledByBranch(brupdate, bundle.bits.uop.br_mask)\n out\n }\n}\n\n/**\n * Object to check if at least 1 bit matches in two masks\n */\nobject maskMatch\n{\n def apply(msk1: UInt, msk2: UInt): Bool = (msk1 & msk2) =/= 0.U\n}\n\n/**\n * Object to clear one bit in a mask given an index\n */\nobject clearMaskBit\n{\n def apply(msk: UInt, idx: UInt): UInt = (msk & ~(1.U << idx))(msk.getWidth-1, 0)\n}\n\n/**\n * Object to shift a register over by one bit and concat a new one\n */\nobject PerformShiftRegister\n{\n def apply(reg_val: UInt, new_bit: Bool): UInt = {\n reg_val := Cat(reg_val(reg_val.getWidth-1, 0).asUInt, new_bit.asUInt).asUInt\n reg_val\n }\n}\n\n/**\n * Object to shift a register over by one bit, wrapping the top bit around to the bottom\n * (XOR'ed with a new-bit), and evicting a bit at index HLEN.\n * This is used to simulate a longer HLEN-width shift register that is folded\n * down to a compressed CLEN.\n */\nobject PerformCircularShiftRegister\n{\n def apply(csr: UInt, new_bit: Bool, evict_bit: Bool, hlen: Int, clen: Int): UInt = {\n val carry = csr(clen-1)\n val newval = Cat(csr, new_bit ^ carry) ^ (evict_bit << (hlen % clen).U)\n newval\n }\n}\n\n/**\n * Object to increment an input value, wrapping it if\n * necessary.\n */\nobject WrapAdd\n{\n // \"n\" is the number of increments, so we wrap at n-1.\n def apply(value: UInt, amt: UInt, n: Int): UInt = {\n if (isPow2(n)) {\n (value + amt)(log2Ceil(n)-1,0)\n } else {\n val sum = Cat(0.U(1.W), value) + Cat(0.U(1.W), amt)\n Mux(sum >= n.U,\n sum - n.U,\n sum)\n }\n }\n}\n\n/**\n * Object to decrement an input value, wrapping it if\n * necessary.\n */\nobject WrapSub\n{\n // \"n\" is the number of increments, so we wrap to n-1.\n def apply(value: UInt, amt: Int, n: Int): UInt = {\n if (isPow2(n)) {\n (value - amt.U)(log2Ceil(n)-1,0)\n } else {\n val v = Cat(0.U(1.W), value)\n val b = Cat(0.U(1.W), amt.U)\n Mux(value >= amt.U,\n value - amt.U,\n n.U - amt.U + value)\n }\n }\n}\n\n/**\n * Object to increment an input value, wrapping it if\n * necessary.\n */\nobject WrapInc\n{\n // \"n\" is the number of increments, so we wrap at n-1.\n def apply(value: UInt, n: Int): UInt = {\n if (isPow2(n)) {\n (value + 1.U)(log2Ceil(n)-1,0)\n } else {\n val wrap = (value === (n-1).U)\n Mux(wrap, 0.U, value + 1.U)\n }\n }\n}\n\n/**\n * Object to decrement an input value, wrapping it if\n * necessary.\n */\nobject WrapDec\n{\n // \"n\" is the number of increments, so we wrap at n-1.\n def apply(value: UInt, n: Int): UInt = {\n if (isPow2(n)) {\n (value - 1.U)(log2Ceil(n)-1,0)\n } else {\n val wrap = (value === 0.U)\n Mux(wrap, (n-1).U, value - 1.U)\n }\n }\n}\n\n/**\n * Object to mask off lower bits of a PC to align to a \"b\"\n * Byte boundary.\n */\nobject AlignPCToBoundary\n{\n def apply(pc: UInt, b: Int): UInt = {\n // Invert for scenario where pc longer than b\n // (which would clear all bits above size(b)).\n ~(~pc | (b-1).U)\n }\n}\n\n/**\n * Object to rotate a signal left by one\n */\nobject RotateL1\n{\n def apply(signal: UInt): UInt = {\n val w = signal.getWidth\n val out = Cat(signal(w-2,0), signal(w-1))\n\n return out\n }\n}\n\n/**\n * Object to sext a value to a particular length.\n */\nobject Sext\n{\n def apply(x: UInt, length: Int): UInt = {\n if (x.getWidth == length) return x\n else return Cat(Fill(length-x.getWidth, x(x.getWidth-1)), x)\n }\n}\n\n/**\n * Object to translate from BOOM's special \"packed immediate\" to a 32b signed immediate\n * Asking for U-type gives it shifted up 12 bits.\n */\nobject ImmGen\n{\n import boom.v3.common.{LONGEST_IMM_SZ, IS_B, IS_I, IS_J, IS_S, IS_U}\n def apply(ip: UInt, isel: UInt): SInt = {\n val sign = ip(LONGEST_IMM_SZ-1).asSInt\n val i30_20 = Mux(isel === IS_U, ip(18,8).asSInt, sign)\n val i19_12 = Mux(isel === IS_U || isel === IS_J, ip(7,0).asSInt, sign)\n val i11 = Mux(isel === IS_U, 0.S,\n Mux(isel === IS_J || isel === IS_B, ip(8).asSInt, sign))\n val i10_5 = Mux(isel === IS_U, 0.S, ip(18,14).asSInt)\n val i4_1 = Mux(isel === IS_U, 0.S, ip(13,9).asSInt)\n val i0 = Mux(isel === IS_S || isel === IS_I, ip(8).asSInt, 0.S)\n\n return Cat(sign, i30_20, i19_12, i11, i10_5, i4_1, i0).asSInt\n }\n}\n\n/**\n * Object to get the FP rounding mode out of a packed immediate.\n */\nobject ImmGenRm { def apply(ip: UInt): UInt = { return ip(2,0) } }\n\n/**\n * Object to get the FP function fype from a packed immediate.\n * Note: only works if !(IS_B or IS_S)\n */\nobject ImmGenTyp { def apply(ip: UInt): UInt = { return ip(9,8) } }\n\n/**\n * Object to see if an instruction is a JALR.\n */\nobject DebugIsJALR\n{\n def apply(inst: UInt): Bool = {\n // TODO Chisel not sure why this won't compile\n// val is_jalr = rocket.DecodeLogic(inst, List(Bool(false)),\n// Array(\n// JALR -> Bool(true)))\n inst(6,0) === \"b1100111\".U\n }\n}\n\n/**\n * Object to take an instruction and output its branch or jal target. Only used\n * for a debug assert (no where else would we jump straight from instruction\n * bits to a target).\n */\nobject DebugGetBJImm\n{\n def apply(inst: UInt): UInt = {\n // TODO Chisel not sure why this won't compile\n //val csignals =\n //rocket.DecodeLogic(inst,\n // List(Bool(false), Bool(false)),\n // Array(\n // BEQ -> List(Bool(true ), Bool(false)),\n // BNE -> List(Bool(true ), Bool(false)),\n // BGE -> List(Bool(true ), Bool(false)),\n // BGEU -> List(Bool(true ), Bool(false)),\n // BLT -> List(Bool(true ), Bool(false)),\n // BLTU -> List(Bool(true ), Bool(false))\n // ))\n //val is_br :: nothing :: Nil = csignals\n\n val is_br = (inst(6,0) === \"b1100011\".U)\n\n val br_targ = Cat(Fill(12, inst(31)), Fill(8,inst(31)), inst(7), inst(30,25), inst(11,8), 0.U(1.W))\n val jal_targ= Cat(Fill(12, inst(31)), inst(19,12), inst(20), inst(30,25), inst(24,21), 0.U(1.W))\n\n Mux(is_br, br_targ, jal_targ)\n }\n}\n\n/**\n * Object to return the lowest bit position after the head.\n */\nobject AgePriorityEncoder\n{\n def apply(in: Seq[Bool], head: UInt): UInt = {\n val n = in.size\n val width = log2Ceil(in.size)\n val n_padded = 1 << width\n val temp_vec = (0 until n_padded).map(i => if (i < n) in(i) && i.U >= head else false.B) ++ in\n val idx = PriorityEncoder(temp_vec)\n idx(width-1, 0) //discard msb\n }\n}\n\n/**\n * Object to determine whether queue\n * index i0 is older than index i1.\n */\nobject IsOlder\n{\n def apply(i0: UInt, i1: UInt, head: UInt) = ((i0 < i1) ^ (i0 < head) ^ (i1 < head))\n}\n\n/**\n * Set all bits at or below the highest order '1'.\n */\nobject MaskLower\n{\n def apply(in: UInt) = {\n val n = in.getWidth\n (0 until n).map(i => in >> i.U).reduce(_|_)\n }\n}\n\n/**\n * Set all bits at or above the lowest order '1'.\n */\nobject MaskUpper\n{\n def apply(in: UInt) = {\n val n = in.getWidth\n (0 until n).map(i => (in << i.U)(n-1,0)).reduce(_|_)\n }\n}\n\n/**\n * Transpose a matrix of Chisel Vecs.\n */\nobject Transpose\n{\n def apply[T <: chisel3.Data](in: Vec[Vec[T]]) = {\n val n = in(0).size\n VecInit((0 until n).map(i => VecInit(in.map(row => row(i)))))\n }\n}\n\n/**\n * N-wide one-hot priority encoder.\n */\nobject SelectFirstN\n{\n def apply(in: UInt, n: Int) = {\n val sels = Wire(Vec(n, UInt(in.getWidth.W)))\n var mask = in\n\n for (i <- 0 until n) {\n sels(i) := PriorityEncoderOH(mask)\n mask = mask & ~sels(i)\n }\n\n sels\n }\n}\n\n/**\n * Connect the first k of n valid input interfaces to k output interfaces.\n */\nclass Compactor[T <: chisel3.Data](n: Int, k: Int, gen: T) extends Module\n{\n require(n >= k)\n\n val io = IO(new Bundle {\n val in = Vec(n, Flipped(DecoupledIO(gen)))\n val out = Vec(k, DecoupledIO(gen))\n })\n\n if (n == k) {\n io.out <> io.in\n } else {\n val counts = io.in.map(_.valid).scanLeft(1.U(k.W)) ((c,e) => Mux(e, (c<<1)(k-1,0), c))\n val sels = Transpose(VecInit(counts map (c => VecInit(c.asBools)))) map (col =>\n (col zip io.in.map(_.valid)) map {case (c,v) => c && v})\n val in_readys = counts map (row => (row.asBools zip io.out.map(_.ready)) map {case (c,r) => c && r} reduce (_||_))\n val out_valids = sels map (col => col.reduce(_||_))\n val out_data = sels map (s => Mux1H(s, io.in.map(_.bits)))\n\n in_readys zip io.in foreach {case (r,i) => i.ready := r}\n out_valids zip out_data zip io.out foreach {case ((v,d),o) => o.valid := v; o.bits := d}\n }\n}\n\n/**\n * Create a queue that can be killed with a branch kill signal.\n * Assumption: enq.valid only high if not killed by branch (so don't check IsKilled on io.enq).\n */\nclass BranchKillableQueue[T <: boom.v3.common.HasBoomUOP](gen: T, entries: Int, flush_fn: boom.v3.common.MicroOp => Bool = u => true.B, flow: Boolean = true)\n (implicit p: org.chipsalliance.cde.config.Parameters)\n extends boom.v3.common.BoomModule()(p)\n with boom.v3.common.HasBoomCoreParameters\n{\n val io = IO(new Bundle {\n val enq = Flipped(Decoupled(gen))\n val deq = Decoupled(gen)\n\n val brupdate = Input(new BrUpdateInfo())\n val flush = Input(Bool())\n\n val empty = Output(Bool())\n val count = Output(UInt(log2Ceil(entries).W))\n })\n\n val ram = Mem(entries, gen)\n val valids = RegInit(VecInit(Seq.fill(entries) {false.B}))\n val uops = Reg(Vec(entries, new MicroOp))\n\n val enq_ptr = Counter(entries)\n val deq_ptr = Counter(entries)\n val maybe_full = RegInit(false.B)\n\n val ptr_match = enq_ptr.value === deq_ptr.value\n io.empty := ptr_match && !maybe_full\n val full = ptr_match && maybe_full\n val do_enq = WireInit(io.enq.fire)\n val do_deq = WireInit((io.deq.ready || !valids(deq_ptr.value)) && !io.empty)\n\n for (i <- 0 until entries) {\n val mask = uops(i).br_mask\n val uop = uops(i)\n valids(i) := valids(i) && !IsKilledByBranch(io.brupdate, mask) && !(io.flush && flush_fn(uop))\n when (valids(i)) {\n uops(i).br_mask := GetNewBrMask(io.brupdate, mask)\n }\n }\n\n when (do_enq) {\n ram(enq_ptr.value) := io.enq.bits\n valids(enq_ptr.value) := true.B //!IsKilledByBranch(io.brupdate, io.enq.bits.uop)\n uops(enq_ptr.value) := io.enq.bits.uop\n uops(enq_ptr.value).br_mask := GetNewBrMask(io.brupdate, io.enq.bits.uop)\n enq_ptr.inc()\n }\n\n when (do_deq) {\n valids(deq_ptr.value) := false.B\n deq_ptr.inc()\n }\n\n when (do_enq =/= do_deq) {\n maybe_full := do_enq\n }\n\n io.enq.ready := !full\n\n val out = Wire(gen)\n out := ram(deq_ptr.value)\n out.uop := uops(deq_ptr.value)\n io.deq.valid := !io.empty && valids(deq_ptr.value) && !IsKilledByBranch(io.brupdate, out.uop) && !(io.flush && flush_fn(out.uop))\n io.deq.bits := out\n io.deq.bits.uop.br_mask := GetNewBrMask(io.brupdate, out.uop)\n\n // For flow queue behavior.\n if (flow) {\n when (io.empty) {\n io.deq.valid := io.enq.valid //&& !IsKilledByBranch(io.brupdate, io.enq.bits.uop)\n io.deq.bits := io.enq.bits\n io.deq.bits.uop.br_mask := GetNewBrMask(io.brupdate, io.enq.bits.uop)\n\n do_deq := false.B\n when (io.deq.ready) { do_enq := false.B }\n }\n }\n private val ptr_diff = enq_ptr.value - deq_ptr.value\n if (isPow2(entries)) {\n io.count := Cat(maybe_full && ptr_match, ptr_diff)\n }\n else {\n io.count := Mux(ptr_match,\n Mux(maybe_full,\n entries.asUInt, 0.U),\n Mux(deq_ptr.value > enq_ptr.value,\n entries.asUInt + ptr_diff, ptr_diff))\n }\n}\n\n// ------------------------------------------\n// Printf helper functions\n// ------------------------------------------\n\nobject BoolToChar\n{\n /**\n * Take in a Chisel Bool and convert it into a Str\n * based on the Chars given\n *\n * @param c_bool Chisel Bool\n * @param trueChar Scala Char if bool is true\n * @param falseChar Scala Char if bool is false\n * @return UInt ASCII Char for \"trueChar\" or \"falseChar\"\n */\n def apply(c_bool: Bool, trueChar: Char, falseChar: Char = '-'): UInt = {\n Mux(c_bool, Str(trueChar), Str(falseChar))\n }\n}\n\nobject CfiTypeToChars\n{\n /**\n * Get a Vec of Strs that can be used for printing\n *\n * @param cfi_type specific cfi type\n * @return Vec of Strs (must be indexed to get specific char)\n */\n def apply(cfi_type: UInt) = {\n val strings = Seq(\"----\", \"BR \", \"JAL \", \"JALR\")\n val multiVec = VecInit(for(string <- strings) yield { VecInit(for (c <- string) yield { Str(c) }) })\n multiVec(cfi_type)\n }\n}\n\nobject BpdTypeToChars\n{\n /**\n * Get a Vec of Strs that can be used for printing\n *\n * @param bpd_type specific bpd type\n * @return Vec of Strs (must be indexed to get specific char)\n */\n def apply(bpd_type: UInt) = {\n val strings = Seq(\"BR \", \"JUMP\", \"----\", \"RET \", \"----\", \"CALL\", \"----\", \"----\")\n val multiVec = VecInit(for(string <- strings) yield { VecInit(for (c <- string) yield { Str(c) }) })\n multiVec(bpd_type)\n }\n}\n\nobject RobTypeToChars\n{\n /**\n * Get a Vec of Strs that can be used for printing\n *\n * @param rob_type specific rob type\n * @return Vec of Strs (must be indexed to get specific char)\n */\n def apply(rob_type: UInt) = {\n val strings = Seq(\"RST\", \"NML\", \"RBK\", \" WT\")\n val multiVec = VecInit(for(string <- strings) yield { VecInit(for (c <- string) yield { Str(c) }) })\n multiVec(rob_type)\n }\n}\n\nobject XRegToChars\n{\n /**\n * Get a Vec of Strs that can be used for printing\n *\n * @param xreg specific register number\n * @return Vec of Strs (must be indexed to get specific char)\n */\n def apply(xreg: UInt) = {\n val strings = Seq(\" x0\", \" ra\", \" sp\", \" gp\",\n \" tp\", \" t0\", \" t1\", \" t2\",\n \" s0\", \" s1\", \" a0\", \" a1\",\n \" a2\", \" a3\", \" a4\", \" a5\",\n \" a6\", \" a7\", \" s2\", \" s3\",\n \" s4\", \" s5\", \" s6\", \" s7\",\n \" s8\", \" s9\", \"s10\", \"s11\",\n \" t3\", \" t4\", \" t5\", \" t6\")\n val multiVec = VecInit(for(string <- strings) yield { VecInit(for (c <- string) yield { Str(c) }) })\n multiVec(xreg)\n }\n}\n\n", "right_context": "{\n /**\n * Get a Vec of Strs that can be used for printing\n *\n * @param fpreg specific register number\n * @return Vec of Strs (must be indexed to get specific char)\n */\n def apply(fpreg: UInt) = {\n val strings = Seq(\" ft0\", \" ft1\", \" ft2\", \" ft3\",\n \" ft4\", \" ft5\", \" ft6\", \" ft7\",\n \" fs0\", \" fs1\", \" fa0\", \" fa1\",\n \" fa2\", \" fa3\", \" fa4\", \" fa5\",\n \" fa6\", \" fa7\", \" fs2\", \" fs3\",\n \" fs4\", \" fs5\", \" fs6\", \" fs7\",\n \" fs8\", \" fs9\", \"fs10\", \"fs11\",\n \" ft8\", \" ft9\", \"ft10\", \"ft11\")\n val multiVec = VecInit(for(string <- strings) yield { VecInit(for (c <- string) yield { Str(c) }) })\n multiVec(fpreg)\n }\n}\n\nobject BoomCoreStringPrefix\n{\n /**\n * Add prefix to BOOM strings (currently only adds the hartId)\n *\n * @param strs list of strings\n * @return String combining the list with the prefix per line\n */\n def apply(strs: String*)(implicit p: Parameters) = {\n val prefix = \"[C\" + s\"${p(TileKey).tileId}\" + \"] \"\n strs.map(str => prefix + str + \"\\n\").mkString(\"\")\n }\n}\n", "groundtruth": "object FPRegToChars\n", "crossfile_context": ""}
{"task_id": "riscv-boom", "path": "riscv-boom/src/main/scala/v4/exu/issue-units/issue-unit.scala", "left_context": "//******************************************************************************\n// Copyright (c) 2015 - 2018, The Regents of the University of California (Regents).\n// All Rights Reserved. See LICENSE and LICENSE.SiFive for license details.\n//------------------------------------------------------------------------------\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\n// RISCV Processor Issue Logic\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\n\npackage boom.v4.exu\n\nimport chisel3._\nimport chisel3.util._\n\nimport org.chipsalliance.cde.config.Parameters\nimport freechips.rocketchip.util.{Str}\n\nimport boom.v4.common._\nimport boom.v4.util.{BoolToChar}\n\ncase class IssueParams(\n dispatchWidth: Int = 1,\n issueWidth: Int = 1,\n numEntries: Int = 8,\n useFullIssueSel: Boolean = true,\n numSlowEntries: Int = 0,\n useMatrixIssue: Boolean = true,\n iqType: Int\n)\n\n\nabstract class IssueUnit(\n val params: IssueParams,\n val numWakeupPorts: Int\n)(implicit p: Parameters)\n extends BoomModule\n{\n val numIssueSlots = params.numEntries\n val issueWidth = params.issueWidth\n val iqType = params.iqType\n val dispatchWidth = params.dispatchWidth\n\n val io = IO(new Bundle {\n val dis_uops = Vec(dispatchWidth, Flipped(Decoupled(new MicroOp)))\n\n val iss_uops = Output(Vec(issueWidth, Valid(new MicroOp())))\n val wakeup_ports = Flipped(Vec(numWakeupPorts, Valid(new Wakeup)))\n val pred_wakeup_port = Flipped(Valid(UInt(log2Ceil(ftqSz).W)))\n\n val child_rebusys = Input(UInt(aluWidth.W))\n\n // tell the issue unit what each execution pipeline has in terms of functional units\n val fu_types = Input(Vec(issueWidth, Vec(FC_SZ, Bool())))\n\n val brupdate = Input(new BrUpdateInfo())\n val flush_pipeline = Input(Bool())\n val squash_grant = Input(Bool())\n\n val tsc_reg = Input(UInt(xLen.W))\n\n // For the speculative non-interference (SNI) implementation\n val rob_head = Input(UInt(robAddrSz.W))\n val rob_pnr_idx = Input(UInt(robAddrSz.W))\n })\n\n\n //-------------------------------------------------------------\n\n\n def getType: String =\n if (iqType == IQ_ALU) \"alu\"\n else if (iqType == IQ_MEM) \"mem\"\n else if (iqType == IQ_FP) \" fp\"\n else if (iqType == IQ_UNQ) \"unique\"\n else \"unknown\"\n}\n\n", "right_context": "{\n def apply(params: IssueParams, numWakeupPorts: Int, useColumnIssueUnit: Boolean, useSingleWideDispatch: Boolean)(implicit p: Parameters): IssueUnit = {\n if (useColumnIssueUnit)\n Module(new IssueUnitBanked(params, numWakeupPorts, useSingleWideDispatch))\n else\n if (params.useMatrixIssue) {\n Module(new IssueUnitAgeMatrix(params, numWakeupPorts)) \n } else {\n Module(new IssueUnitCollapsing(params, numWakeupPorts)) \n }\n }\n\n}\n", "groundtruth": "object IssueUnit\n", "crossfile_context": ""}
{"task_id": "riscv-boom", "path": "riscv-boom/src/main/scala/v4/exu/rename/rename-maptable.scala", "left_context": "//******************************************************************************\n// Copyright (c) 2015 - 2019, The Regents of the University of California (Regents).\n// All Rights Reserved. See LICENSE and LICENSE.SiFive for license details.\n//------------------------------------------------------------------------------\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\n// Rename Map Table\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\n\npackage boom.v4.exu\n\nimport chisel3._\nimport chisel3.util._\nimport boom.v4.common._\nimport boom.v4.util._\nimport org.chipsalliance.cde.config.Parameters\n\nclass MapReq(val lregSz: Int) extends Bundle\n{\n val lrs1 = UInt(lregSz.W)\n val lrs2 = UInt(lregSz.W)\n val lrs3 = UInt(lregSz.W)\n val ldst = UInt(lregSz.W)\n}\n\nclass MapResp(val pregSz: Int) extends Bundle\n{\n val prs1 = UInt(pregSz.W)\n val prs2 = UInt(pregSz.W)\n val prs3 = UInt(pregSz.W)\n val stale_pdst = UInt(pregSz.W)\n}\n\nclass RemapReq(val lregSz: Int, val pregSz: Int) extends Bundle\n{\n val ldst = UInt(lregSz.W)\n val pdst = UInt(pregSz.W)\n val valid = Bool()\n}\n\nclass RenameMapTable(\n val plWidth: Int,\n val numLregs: Int,\n val numPregs: Int,\n val bypass: Boolean,\n val float: Boolean)\n (implicit p: Parameters) extends BoomModule\n{\n val pregSz = log2Ceil(numPregs)\n\n val io = IO(new BoomBundle()(p) {\n // Logical sources -> physical sources.\n val map_reqs = Input(Vec(plWidth, new MapReq(lregSz)))\n val map_resps = Output(Vec(plWidth, new MapResp(pregSz)))\n\n // Remapping an ldst to a newly allocated pdst?\n val remap_reqs = Input(Vec(plWidth, new RemapReq(lregSz, pregSz)))\n val com_remap_reqs = Input(Vec(plWidth, new RemapReq(lregSz, pregSz)))\n\n // Dispatching branches: need to take snapshots of table state.\n val ren_br_tags = Input(Vec(plWidth+1, Valid(UInt(brTagSz.W))))\n\n // Signals for restoring state following misspeculation.\n val brupdate = Input(new BrUpdateInfo)\n val rollback = Input(Bool())\n })\n\n // The map table register array and its branch snapshots.\n val map_table = RegInit(VecInit((0 until numLregs) map { i => i.U(pregSz.W) }))\n", "right_context": " val br_snapshots = Reg(Vec(maxBrCount, Vec(numLregs, UInt(pregSz.W))))\n\n // The intermediate states of the map table following modification by each pipeline slot.\n val remap_table = Wire(Vec(plWidth+1, Vec(numLregs, UInt(pregSz.W))))\n val com_remap_table = Wire(Vec(plWidth+1, Vec(numLregs, UInt(pregSz.W))))\n\n // Uops requesting changes to the map table.\n val remap_pdsts = io.remap_reqs map (_.pdst)\n val remap_ldsts_oh = io.remap_reqs map (req => UIntToOH(req.ldst) & Fill(numLregs, req.valid.asUInt))\n\n val com_remap_pdsts = io.com_remap_reqs map (_.pdst)\n val com_remap_ldsts_oh = io.com_remap_reqs map (req => UIntToOH(req.ldst) & Fill(numLregs, req.valid.asUInt))\n\n // Figure out the new mappings seen by each pipeline slot.\n for (i <- 0 until numLregs) {\n val remapped_row = (remap_ldsts_oh.map(ldst => ldst(i)) zip remap_pdsts)\n .scanLeft(map_table(i)) {case (pdst, (ldst, new_pdst)) => Mux(ldst, new_pdst, pdst)}\n\n val com_remapped_row = (com_remap_ldsts_oh.map(ldst => ldst(i)) zip com_remap_pdsts)\n .scanLeft(com_map_table(i)) {case (pdst, (ldst, new_pdst)) => Mux(ldst, new_pdst, pdst)}\n\n for (j <- 0 until plWidth+1) {\n remap_table(j)(i) := remapped_row(j)\n com_remap_table(j)(i) := com_remapped_row(j)\n }\n }\n\n // Create snapshots of new mappings.\n if (enableSuperscalarSnapshots) {\n for (i <- 0 until plWidth+1) {\n when (io.ren_br_tags(i).valid) {\n br_snapshots(io.ren_br_tags(i).bits) := remap_table(i)\n }\n }\n } else {\n assert(PopCount(io.ren_br_tags.map(_.valid)) <= 1.U)\n val do_br_snapshot = io.ren_br_tags.map(_.valid).reduce(_||_)\n val br_snapshot_tag = Mux1H(io.ren_br_tags.map(_.valid), io.ren_br_tags.map(_.bits))\n val br_snapshot_table = Mux1H(io.ren_br_tags.map(_.valid), remap_table)\n when (do_br_snapshot) {\n br_snapshots(br_snapshot_tag) := br_snapshot_table\n }\n }\n\n when (io.brupdate.b2.mispredict) {\n // Restore the map table to a branch snapshot.\n map_table := br_snapshots(io.brupdate.b2.uop.br_tag)\n } .elsewhen (io.rollback) {\n map_table := com_map_table\n } .otherwise {\n // Update mappings.\n map_table := remap_table(plWidth)\n }\n com_map_table := com_remap_table(plWidth)\n\n // Read out mappings.\n for (i <- 0 until plWidth) {\n io.map_resps(i).prs1 := (0 until i).foldLeft(map_table(io.map_reqs(i).lrs1)) ((p,k) =>\n Mux(bypass.B && io.remap_reqs(k).valid && io.remap_reqs(k).ldst === io.map_reqs(i).lrs1, io.remap_reqs(k).pdst, p))\n io.map_resps(i).prs2 := (0 until i).foldLeft(map_table(io.map_reqs(i).lrs2)) ((p,k) =>\n Mux(bypass.B && io.remap_reqs(k).valid && io.remap_reqs(k).ldst === io.map_reqs(i).lrs2, io.remap_reqs(k).pdst, p))\n io.map_resps(i).prs3 := (0 until i).foldLeft(map_table(io.map_reqs(i).lrs3)) ((p,k) =>\n Mux(bypass.B && io.remap_reqs(k).valid && io.remap_reqs(k).ldst === io.map_reqs(i).lrs3, io.remap_reqs(k).pdst, p))\n io.map_resps(i).stale_pdst := (0 until i).foldLeft(map_table(io.map_reqs(i).ldst)) ((p,k) =>\n Mux(bypass.B && io.remap_reqs(k).valid && io.remap_reqs(k).ldst === io.map_reqs(i).ldst, io.remap_reqs(k).pdst, p))\n\n if (!float) io.map_resps(i).prs3 := DontCare\n }\n\n // Don't flag the creation of duplicate 'p0' mappings during rollback.\n // These cases may occur soon after reset, as all maptable entries are initialized to 'p0'.\n io.remap_reqs map (req => (req.pdst, req.valid)) foreach {case (p,r) =>\n assert (!r || !map_table.contains(p), \"[maptable] Trying to write a duplicate mapping.\")}\n}\n", "groundtruth": " val com_map_table = RegInit(VecInit((0 until numLregs) map { i => i.U(pregSz.W) }))\n", "crossfile_context": ""}
{"task_id": "riscv-boom", "path": "riscv-boom/src/main/scala/v4/util/ParallelFindOne.scala", "left_context": "//> using scala \"2.13.16\"\n//> using repository sonatype-s01:snapshots\n//> using dep \"org.chipsalliance::chisel::7.0.0-M2+508-57ab35eb-SNAPSHOT\"\n//> using plugin \"org.chipsalliance:::chisel-plugin::7.0.0-M2+508-57ab35eb-SNAPSHOT\"\n//> using options \"-unchecked\", \"-deprecation\", \"-language:reflectiveCalls\", \"-feature\", \"-Xcheckinit\", \"-Xfatal-warnings\", \"-Ywarn-dead-code\", \"-Ywarn-unused\", \"-Ymacro-annotations\"\n\npackage boom.v4.util\n\nimport chisel3._\nimport chisel3.util.{log2Ceil,log2Floor, Cat,Mux1H}\nimport chisel3.experimental.hierarchy.{Definition, Instance, instantiable, public}\nimport circt.stage.ChiselStage\n\n@instantiable\nclass ParallelFindOne(decodeWidth : Int, favor: Boolean) extends Module {\n\n", "right_context": " @public val bitmask = IO(Input(UInt(decodeWidth.W)))\n @public val success = IO(Output(new Bool()))\n @public val index = IO(Output(UInt(log2Ceil(decodeWidth).W)))\n\n // must be log of 2\n require(log2Ceil(decodeWidth) == log2Floor(decodeWidth))\n\n if (decodeWidth ==2 ) {\n success := bitmask.orR\n if (favor) {\n index := bitmask(1)\n } else {\n index := !bitmask(0)\n }\n // index := Mux1H(Seq(\n // bitmask(1) -> 1.U(1.W),\n // bitmask(0) -> 0.U(1.W)\n // )) // Note: not truly parallel for lack of X\n } else {\n val decoder_def = Definition(new ParallelFindOne(decodeWidth / 2, favor))\n val lower_dec = Instance(decoder_def)\n val upper_dec = Instance(decoder_def)\n\n val lower_success = Wire(Bool())\n val upper_success = Wire(Bool())\n val lower_index = Wire(UInt((log2Ceil(decodeWidth)-1).W))\n val upper_index = Wire(UInt((log2Ceil(decodeWidth)-1).W))\n lower_dec.bitmask := bitmask(decodeWidth/2-1, 0)\n upper_dec.bitmask := bitmask(decodeWidth-1, decodeWidth/2)\n lower_success := lower_dec.success\n upper_success := upper_dec.success\n lower_index := lower_dec.index\n upper_index := upper_dec.index\n success := lower_success | upper_success\n if (favor) {\n index := Mux(upper_success, Cat(1.U(1.W), upper_index), Cat(0.U(1.W), lower_index))\n } else {\n index := Mux(lower_success, Cat(0.U(1.W), lower_index), Cat(1.U(1.W), upper_index))\n }\n // index := Mux1H(Seq(\n // upper_success ->Cat(1.U(1.W), upper_index),\n // lower_success -> Cat(0.U(1.W), lower_index)\n // ))\n }\n}\n\nobject ParallelFindOne {\n def apply(bv: UInt, favor: Boolean) : (Bool, UInt) = {\n val widthRoundUp = scala.math.pow(2, (log2Ceil(bv.getWidth))).intValue\n val pfo = Module(new ParallelFindOne(widthRoundUp, favor))\n pfo.bitmask := bv\n// assert(pfo.index < bv.getWidth.U,\"non-pow2 index out of range\")\n (pfo.success, pfo.index)\n }\n}\n\nclass testmodule extends Module {\n val input = IO(Input(UInt(4.W)))\n val success = IO(Output(Bool()))\n val index = IO(Output(UInt(2.W)))\n\n val (a, b) = ParallelFindOne(input, true)\n success := a\n index := b\n\n// (success, index) := \n}\n\nobject Elaborate extends App {\n\n println(ChiselStage.emitSystemVerilog(new testmodule))\n// println(ChiselStage.emitFIRRTLDialect(new ParallelFindOne(4)))\n// println(ChiselStage.emitSystemVerilog(new PrefixedMux))\n\n}\n", "groundtruth": " override val desiredName = s\"Parallel_${decodeWidth}_f${favor}_FindOne\"\n", "crossfile_context": ""}
{"task_id": "homemade-riscv-en", "path": "homemade-riscv-en/chap04/01_LogicGatesVec/src/main/scala/LogicGatesVev.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\n\n/**\n * Logic gate (Vector version)\n */\nclass LogicGatesVec extends Module {\n val io = IO(new Bundle {\n /** Input from switch */\n val switches = Input(Vec(2, Bool()))\n /** Output to LED */\n val leds = Output(Vec(7, Bool()))\n })\n\n io.leds(0) := ~io.switches(0) // NOT\n", "right_context": " io.leds(6) := ~(io.switches(0) ^ io.switches(1)) // NXOR\n}\n\nobject LogicGatesVec extends App {\n chisel3.Driver.execute(args, () => new LogicGatesVec())\n}\n", "groundtruth": " io.leds(1) := io.switches(0) & io.switches(1) // AND\n io.leds(2) := io.switches(0) | io.switches(1) // OR\n io.leds(3) := ~(io.switches(0) & io.switches(1)) // NAND\n", "crossfile_context": ""}
{"task_id": "homemade-riscv-en", "path": "homemade-riscv-en/chap04/02_IntCompare/src/main/scala/IntCompare.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\n\n/**\n * Compare operation\n */\nclass IntCompare extends Module {\n val io = IO(new Bundle {\n val a = Input(UInt(4.W)) // Input A\n val b = Input(UInt(4.W)) // Input B\n val bit_ope = Output(Bool())\n val bit_reduction = Output(Bool())\n val equal_ope = Output(Bool())\n val equal_5 = Output(Bool())\n val not_5 = Output(Bool())\n })\n\n // Compare by bit, if there is even one difference, they are not equal\n io.bit_ope := ~(io.a(0) ^ io.b(0) | io.a(1) ^ io.b(1) | io.a(2) ^ io.b(2) | io.a(3) ^ io.b(3))\n\n // Bitwise comparison of \"a\" and \"b\" can be done like \"a ^ b\".\n // Since it is hard to write like \"a (0) | a (1) | a (2) | a (3)\", the \". orR\" operator is defined.\n io.bit_reduction := ~((io.a ^ io.b).orR)\n\n // Since Chisel also has an equality operator, it does not actually do the troublesome thing like the above.\n io.equal_ope := io.a === io.b\n\n // You can also compare with numeric literals. Match the missing bits to the larger one.\n io.equal_5 := io.a === 5.U\n\n", "right_context": "\nobject IntCompare extends App {\n chisel3.Driver.execute(args, () => new IntCompare())\n}\n", "groundtruth": " // Inequality operator is \"=/=\".\n io.not_5 := io.a =/= 5.U\n", "crossfile_context": ""}
{"task_id": "homemade-riscv-en", "path": "homemade-riscv-en/chap04/13_Shifter/src/main/scala/LeftShift.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\nimport chisel3.util._\n\n/** Left shifter\n */\nclass LeftShifter extends Module {\n val io = IO(new Bundle {\n val in = Input(UInt(4.W))\n // Since the input is 4 bits, 2 bits are sufficient for\n // specifying the shift amount\n val shiftAmount = Input(UInt(2.W))\n val out = Output(UInt(4.W))\n })\n\n // The output of the least significant bit becomes the least \n // significant bit of input when the shift amount is 0, and \n // becomes 0 otherwise.\n val mux0 = Module(new Mux4)\n mux0.io.selector := io.shiftAmount\n mux0.io.in_0 := io.in(0)\n mux0.io.in_1 := 0.U\n mux0.io.in_2 := 0.U\n mux0.io.in_3 := 0.U\n\n val mux1 = Module(new Mux4)\n mux1.io.selector := io.shiftAmount\n mux1.io.in_0 := io.in(1)\n mux1.io.in_1 := io.in(0)\n mux1.io.in_2 := 0.U\n mux1.io.in_3 := 0.U\n\n val mux2 = Module(new Mux4)\n mux2.io.selector := io.shiftAmount\n mux2.io.in_0 := io.in(2)\n mux2.io.in_1 := io.in(1)\n mux2.io.in_2 := io.in(0)\n mux2.io.in_3 := 0.U\n\n val mux3 = Module(new Mux4)\n mux3.io.selector := io.shiftAmount\n mux3.io.in_0 := io.in(3)\n mux3.io.in_1 := io.in(2)\n mux3.io.in_2 := io.in(1)\n mux3.io.in_3 := io.in(0)\n\n io.out := Cat(mux3.io.out, mux2.io.out, mux1.io.out, mux0.io.out)\n}\n\n/**\n * Object to output Verilog file of Mux4.\n */\n", "right_context": "", "groundtruth": "object LeftShifter extends App {\n chisel3.Driver.execute(args, () => new LeftShifter)\n}\n", "crossfile_context": ""}
{"task_id": "homemade-riscv-en", "path": "homemade-riscv-en/chap04/13_Shifter/src/main/scala/Mux2.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\n\n/** Multiplexer.\n * If selecter is 0, output the value of in_0, otherwise in_1.\n */\nclass Mux2 extends Module {\n val io = IO(new Bundle {\n val selector = Input(UInt(1.W))\n val in_0 = Input(UInt(1.W))\n val in_1 = Input(UInt(1.W))\n val out = Output(UInt(1.W))\n })\n\n io.out := (~io.selector & io.in_0) | (io.selector & io.in_1)\n}\n\n/** Companion object of Mux2\n */\nobject Mux2 {\n/** Multiplexer\n * @param selector 1-bit select signal\n * @param in_0 1-bit input signal\n * @param in_1 1-bit input signal\n * \n * @return If selecter is 0, output the value of in_0, otherwise in_1.\n */\n def apply(selector: UInt, in_0: UInt, in_1: UInt): UInt = {\n val mux2 = Module(new Mux2())\n", "right_context": "", "groundtruth": " mux2.io.selector := selector\n mux2.io.in_0 := in_0\n mux2.io.in_1 := in_1\n mux2.io.out\n", "crossfile_context": ""}
{"task_id": "homemade-riscv-en", "path": "homemade-riscv-en/chap04/14_Multiplier/src/main/scala/Addr4Bit.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\nimport chisel3.util._\n\n/** Adder (4bit)\n */\nclass Adder4Bit extends Module {\n val io = IO(new Bundle {\n val a = Input(UInt(4.W))\n val b = Input(UInt(4.W))\n\n /* By connecting the adders together, it is possible to create a more multi-bit adder. */\n val carryIn = Input(UInt(1.W))\n\n val sum = Output(UInt(4.W))\n val carryOut = Output(UInt(1.W))\n })\n\n /*\n * Generate Adders for 4 bits.\n */\n val adder0 = Module(new FullAdder)\n adder0.io.a := io.a(0)\n adder0.io.b := io.b(0)\n adder0.io.carryIn := io.carryIn\n\n val adder1 = Module(new FullAdder)\n adder1.io.a := io.a(1)\n adder1.io.b := io.b(1)\n adder1.io.carryIn := adder0.io.carryOut // The carry output of the lower digit propagates\n\n val adder2 = Module(new FullAdder)\n adder2.io.a := io.a(2)\n adder2.io.b := io.b(2)\n adder2.io.carryIn := adder1.io.carryOut\n\n val adder3 = Module(new FullAdder)\n adder3.io.a := io.a(3)\n adder3.io.b := io.b(3)\n adder3.io.carryIn := adder2.io.carryOut\n\n // Concatenate the sum of each digit\n io.sum := Cat(adder3.io.sum, adder2.io.sum, adder1.io.sum, adder0.io.sum)\n\n io.carryOut := adder3.io.carryOut\n}\n\n/** Adder (4bit). \"for loop\" version\n */\nclass Adder4BitFor extends Module {\n val io = IO(new Bundle {\n val a = Input(UInt(4.W))\n val b = Input(UInt(4.W))\n val carryIn = Input(UInt(1.W))\n val sum = Output(UInt(4.W))\n val carryOut = Output(UInt(1.W))\n })\n\n val fullAdders = VecInit(Seq.fill(4){ Module(new FullAdder).io }) // [Caution] we pass \"io\"\n val carries = Wire(Vec(5, UInt(1.W)))\n val sum = Wire(Vec(4, UInt(1.W)))\n\n carries(0) := io.carryIn\n\n for (i <- 0 until 4) {\n fullAdders(i).a := io.a(i)\n fullAdders(i).b := io.b(i)\n fullAdders(i).carryIn := carries(i)\n sum(i) := fullAdders(i).sum\n carries(i + 1) := fullAdders(i).carryOut\n }\n\n io.sum := sum.asUInt\n io.carryOut := carries(4)\n}\n\n/** adder\n * \n * @param n bit width\n */\nclass Adder(n: Int) extends Module {\n val io = IO(new Bundle {\n val a = Input(UInt(n.W))\n val b = Input(UInt(n.W))\n val carryIn = Input(UInt(1.W))\n val sum = Output(UInt(n.W))\n val carryOut = Output(UInt(1.W))\n })\n\n /** contructor with default bit width\n */\n def this() = this(4)\n\n", "right_context": " val carries = Wire(Vec(n + 1, UInt(1.W)))\n val sum = Wire(Vec(n, UInt(1.W)))\n\n carries(0) := io.carryIn\n\n for (i <- 0 until n) {\n fullAdders(i).a := io.a(i)\n fullAdders(i).b := io.b(i)\n fullAdders(i).carryIn := carries(i)\n sum(i) := fullAdders(i).sum\n carries(i + 1) := fullAdders(i).carryOut\n }\n\n io.sum := sum.asUInt\n io.carryOut := carries(n)\n}\n\nclass AdderLED extends Module {\n val io = IO(new Bundle {\n val a = Input(UInt(4.W))\n val b = Input(UInt(4.W))\n val seg7LEDBundle = Output(new Seg7LEDBundle)\n val overflowLED = Output(UInt(1.W)) // Lights the LED when overflow occurs\n })\n\n val seg7LED = Module(new Seg7LED1Digit)\n val adder = Module(new Adder4Bit)\n adder.io.a := io.a\n adder.io.b := io.b\n // Since there is no carry input of the least significant digit, 0 is assigned\n adder.io.carryIn := 0.U\n\n seg7LED.io.num := adder.io.sum\n\n io.seg7LEDBundle := seg7LED.io.seg7led\n io.overflowLED := adder.io.carryOut\n}\n\nclass AdderLEDFor extends Module {\n val io = IO(new Bundle {\n val a = Input(UInt(4.W))\n val b = Input(UInt(4.W))\n val seg7LEDBundle = Output(new Seg7LEDBundle)\n val overflowLED = Output(UInt(1.W)) // light LED when overflow occur\n })\n\n val seg7LED = Module(new Seg7LED1Digit)\n val adder = Module(new Adder4BitFor)\n adder.io.a := io.a\n adder.io.b := io.b\n // Since there is no carry input of the least significant digit, 0 is assigned\n adder.io.carryIn := 0.U\n\n seg7LED.io.num := adder.io.sum\n\n io.seg7LEDBundle := seg7LED.io.seg7led\n io.overflowLED := adder.io.carryOut\n}\n\n/**\n * Objcect to output Verilog file\n */\nobject AdderLED extends App {\n chisel3.Driver.execute(args, () => new AdderLED)\n}\n\nobject AdderLEDFor extends App {\n chisel3.Driver.execute(args, () => new AdderLEDFor)\n}\n\nobject Adder extends App {\n // generate 8 bit adder.\n chisel3.Driver.execute(args, () => new Adder(8))\n}\n\n", "groundtruth": " val fullAdders = VecInit(Seq.fill(n){ Module(new FullAdder).io })\n", "crossfile_context": ""}
{"task_id": "homemade-riscv-en", "path": "homemade-riscv-en/chap05/00_SRLatch/src/main/scala/SRLatch.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\n\n/** SR Latch\n */\nclass SRLatch extends Module {\n val io = IO(new Bundle {\n val set = Input(Bool())\n val reset = Input(Bool())\n val q = Output(Bool())\n val notQ = Output(Bool())\n })\n\n io.q := ~(io.reset | io.notQ)\n io.notQ := ~(io.set | io.q)\n}\n\n", "right_context": "", "groundtruth": "object SRLatch extends App {\n chisel3.Driver.execute(args, () => new SRLatch)\n}\n", "crossfile_context": ""}
{"task_id": "homemade-riscv-en", "path": "homemade-riscv-en/chap05/01_DLatch/src/main/scala/SRLatch.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\n\n/** SR Latch\n */\nclass SRLatch extends Module {\n val io = IO(new Bundle {\n", "right_context": " val notQ = Output(Bool())\n })\n\n io.q := ~(io.reset | io.notQ)\n io.notQ := ~(io.set | io.q)\n}\n\nobject SRLatch extends App {\n chisel3.Driver.execute(args, () => new SRLatch)\n}\n", "groundtruth": " val set = Input(Bool())\n val reset = Input(Bool())\n", "crossfile_context": ""}
{"task_id": "homemade-riscv-en", "path": "homemade-riscv-en/chap05/04_EnRstFF/src/main/scala/SRLatch.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\n\n/** SR Latch\n */\nclass SRLatch extends Module {\n val io = IO(new Bundle {\n val set = Input(Bool())\n val reset = Input(Bool())\n val q = Output(Bool())\n val notQ = Output(Bool())\n })\n\n io.q := ~(io.reset | io.notQ)\n io.notQ := ~(io.set | io.q)\n}\n\n", "right_context": "", "groundtruth": "object SRLatch extends App {\n chisel3.Driver.execute(args, () => new SRLatch)\n}\n", "crossfile_context": ""}
{"task_id": "homemade-riscv-en", "path": "homemade-riscv-en/chap05/12_UART/src/main/scala/Seg7LED.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\nimport chisel3.util._\n\n/** Bundle for 7-segment LED\n */\nclass Seg7LEDBundle extends Bundle {\n /** For glowing each segment. Make 0 to 7 correspond to CA to CG. It lights when it is 0, and goes out when it is 1. */\n", "right_context": " /** For digit selection. The digit which is 1 glows up. */\n val anodes = Output(UInt(8.W))\n}\n\n/** 7 segment LED (8 digit)\n */\nclass Seg7LED extends Module {\n val io = IO(new Bundle {\n // allocate 8 digit 4 bit values.\n val digits = Input(Vec(8, UInt(4.W))) \n val seg7led = Output(new Seg7LEDBundle)\n })\n\n /* Counter of time to switch each digit.\n * First argument is condition to count up.\n * Second argument is the number counting up. (n, count from 0 to n-1)\n * Return value is taple of number of counter and \n * signal that becomes ture.B when counter equals to n - 1.\n * If condition is true.B, count every clock. */\n val (digitChangeCount, digitChange) = Counter(true.B, 100000) \n\n val (digitIndex, digitWrap) = Counter(digitChange, 8) // Digit to display\n val digitNum = io.digits(digitIndex) // number of display digit\n\n io.seg7led.cathodes := MuxCase(\"b111_1111\".U,\n Array( // gfe_dcba is order of cathodes\n (digitNum === \"h0\".U) -> \"b100_0000\".U,\n (digitNum === \"h1\".U) -> \"b111_1001\".U,\n (digitNum === \"h2\".U) -> \"b010_0100\".U,\n (digitNum === \"h3\".U) -> \"b011_0000\".U,\n (digitNum === \"h4\".U) -> \"b001_1001\".U,\n (digitNum === \"h5\".U) -> \"b001_0010\".U,\n (digitNum === \"h6\".U) -> \"b000_0010\".U,\n (digitNum === \"h7\".U) -> \"b101_1000\".U,\n (digitNum === \"h8\".U) -> \"b000_0000\".U,\n (digitNum === \"h9\".U) -> \"b001_0000\".U,\n (digitNum === \"ha\".U) -> \"b000_1000\".U,\n (digitNum === \"hb\".U) -> \"b000_0011\".U,\n (digitNum === \"hc\".U) -> \"b100_0110\".U,\n (digitNum === \"hd\".U) -> \"b010_0001\".U,\n (digitNum === \"he\".U) -> \"b000_0110\".U,\n (digitNum === \"hf\".U) -> \"b000_1110\".U))\n\n val anodes = RegInit(\"b1111_1110\".U(8.W))\n when (digitChange) {\n // Rotate shift when switching display digit\n anodes := Cat(anodes(6, 0), anodes(7))\n }\n io.seg7led.anodes := anodes\n\n io.seg7led.decimalPoint := 1.U // Do not light the decimal point.\n}\n", "groundtruth": " val cathodes = Output(UInt(7.W))\n /** For decimal point. It lights when it is 0, and goes out when it is 1. */\n", "crossfile_context": ""}
{"task_id": "homemade-riscv-en", "path": "homemade-riscv-en/chap05/14_VgaUartDisp/src/main/scala/CharVramWriter.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\nimport chisel3.util._\n\nclass CharDispBundle extends Bundle {\n val row = Input(UInt(5.W))\n val col = Input(UInt(7.W))\n val charCode = Input(UInt(8.W))\n val color = Input(UInt(8.W))\n}\n\nclass CharVramWriter extends Module {\n val io = IO(new Bundle{\n val charData = Flipped(Decoupled(new CharDispBundle))\n val vramData = Decoupled(new VramDataBundle)\n })\n\n /* State machine definition */\n val sIdle :: sRomRead :: sShiftRegLoad :: sVramWrite :: Nil = Enum(4)\n val state = RegInit(sIdle)\n\n // Coordinates in the character being processed\n val xInChar = RegInit(0.U(3.W))\n val yInChar = RegInit(0.U(4.W))\n\n val charRom = Module(new CharRom)\n charRom.io.clka := clock\n charRom.io.ena := true.B\n charRom.io.addra := io.charData.bits.charCode * 16.U + yInChar\n\n val pxShiftReg = Module(new ShiftRegisterPISO(8))\n pxShiftReg.io.d := charRom.io.douta\n pxShiftReg.io.load := state === sShiftRegLoad\n pxShiftReg.io.enable := state === sVramWrite\n\n // State transition\n switch (state) {\n is (sIdle) {\n", "right_context": " }\n is (sShiftRegLoad) {\n state := sVramWrite\n xInChar := 0.U\n }\n is (sVramWrite) {\n when (xInChar === 7.U) {\n when (yInChar === 15.U) {\n state := sIdle\n } .otherwise {\n state := sRomRead\n yInChar := yInChar + 1.U\n }\n } .otherwise {\n xInChar := xInChar + 1.U\n }\n }\n }\n\n // VRAM address of upper left point of character\n val pxBaseAddr = (VGA.hDispMax * 16).U * io.charData.bits.row + 8.U * io.charData.bits.col\n io.vramData.bits.addr := pxBaseAddr + VGA.hDispMax.U * yInChar + xInChar\n io.vramData.bits.data := Mux(pxShiftReg.io.shiftOut, io.charData.bits.color, 0.U)\n io.vramData.valid := state === sVramWrite\n\n io.charData.ready := state === sIdle\n}\n", "groundtruth": " when (io.charData.valid) {\n state := sRomRead\n yInChar := 0.U\n }\n", "crossfile_context": ""}
{"task_id": "homemade-riscv-en", "path": "homemade-riscv-en/chap07/01_PencilRocketII/src/main/scala/Uart.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\nimport chisel3.util._\n\nobject Uart {\n val clock_freq = 70000000\n val trans_bps = 115200\n}\n\nimport Uart._\n\n/** UART\n */\nclass Uart extends Module {\n val io = IO(new Bundle {\n val rxData = Input(Bool())\n val txData = Output(Bool())\n val rts = Output(Bool())\n val cts = Input(Bool())\n val receiveData = Decoupled(UInt(8.W))\n val sendData = Flipped(Decoupled(UInt(8.W)))\n })\n\n val uartRx = Module(new UartRx)\n uartRx.io.rxData := io.rxData\n io.receiveData <> uartRx.io.receiveData\n\n val txQueue = Module(new Queue(UInt(8.W), 64))\n txQueue.io.enq <> io.sendData\n\n val uartTx = Module(new UartTx)\n io.txData := uartTx.io.txData\n uartTx.io.sendData <> txQueue.io.deq\n\n io.rts := false.B\n}\n\n/** UART Transmitter\n */\nclass UartTx extends Module {\n val io = IO(new Bundle {\n val sendData = Flipped(Decoupled(UInt(8.W)))\n val txData = Output(Bool())\n })\n\n /* State machine definition */\n val sIdle :: sStartBit :: sSend :: sStopBit :: Nil = Enum(4)\n val state = RegInit(sIdle)\n\n // Counter for state transition\n val (txCount, txEnable) = Counter(true.B, clock_freq / trans_bps)\n // Counter for 8-bit transmission\n val sendCount = Reg(UInt(3.W))\n // Shift register for transmission data\n val shiftReg = Module(new ShiftRegisterPISO(8))\n shiftReg.io.d := Reverse(io.sendData.bits)\n shiftReg.io.load := state === sIdle && io.sendData.valid\n shiftReg.io.enable := state === sSend && txEnable\n\n // State transition\n when (state === sIdle && io.sendData.valid) {\n state := sStartBit\n txCount := 0.U\n } .elsewhen (txEnable) {\n switch (state) {\n is (sStartBit) {\n state := sSend\n sendCount := 0.U\n }\n is (sSend) {\n when (sendCount === 7.U) {\n state := sStopBit\n", "right_context": " state := sIdle\n }\n }\n }\n\n io.sendData.ready := state === sIdle\n \n io.txData := MuxCase(true.B, Array(\n (state === sStartBit) -> false.B,\n (state === sSend) -> shiftReg.io.shiftOut,\n (state === sStopBit) -> true.B))\n}\n\n/** UART receiver\n */\nclass UartRx extends Module {\n val io = IO(new Bundle {\n val rxData = Input(Bool())\n val receiveData = Decoupled(UInt(8.W))\n })\n\n /* State machine definition */\n val sIdle :: sStartBit :: sReceive :: sStopBit :: Nil = Enum(4)\n val state = RegInit(sIdle)\n\n // Counter for state transition \n val (rxCount, rxEnable) = Counter(true.B, clock_freq / trans_bps)\n // Counter for half a cycle of 1 bit\n val (rxHalfCount, rxHalfEnable) = Counter(true.B, clock_freq / trans_bps / 2)\n // Counter for 8-bit receiving\n val receiveCount = Reg(UInt(3.W))\n\n val shiftReg = Module(new ShiftRegisterSIPO(8))\n shiftReg.io.shiftIn := io.rxData\n shiftReg.io.enable := state === sReceive && rxEnable\n\n val rDataValid = RegInit(false.B)\n val start = NegEdge(Synchronizer(io.rxData))\n\n // State transition\n when (state === sIdle && start) {\n state := sStartBit\n rxHalfCount := 0.U\n } .elsewhen (state === sStartBit && rxHalfEnable) {\n state := sReceive\n rxCount := 0.U\n receiveCount := 0.U\n } .elsewhen (rxEnable) {\n switch (state) {\n is (sReceive) {\n when (receiveCount === 7.U) {\n state := sStopBit\n } .otherwise {\n receiveCount := receiveCount + 1.U\n }\n }\n is (sStopBit) {\n when (rxEnable) {\n state := sIdle\n }\n }\n }\n }\n\n when (state === sStopBit && rxEnable) {\n rDataValid := true.B\n } .elsewhen (io.receiveData.ready) {\n rDataValid := false.B\n }\n\n io.receiveData.bits := Reverse(shiftReg.io.q)\n io.receiveData.valid := rDataValid\n}\n", "groundtruth": " } .otherwise {\n sendCount := sendCount + 1.U\n }\n", "crossfile_context": ""}
{"task_id": "homemade-riscv", "path": "homemade-riscv/chap04/01_LogicGatesVec/src/main/scala/LogicGatesVev.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\n\n/**\n * 各種論理演算(ベクトル版)\n */\nclass LogicGatesVec extends Module {\n val io = IO(new Bundle {\n /** スイッチの入力 */\n val switches = Input(Vec(2, Bool()))\n /** LEDへの出力 */\n val leds = Output(Vec(7, Bool()))\n })\n\n io.leds(0) := ~io.switches(0) // NOT\n io.leds(1) := io.switches(0) & io.switches(1) // AND\n io.leds(2) := io.switches(0) | io.switches(1) // OR\n io.leds(3) := ~(io.switches(0) & io.switches(1)) // NAND\n io.leds(4) := ~(io.switches(0) | io.switches(1)) // NOR\n io.leds(5) := io.switches(0) ^ io.switches(1) // XOR\n", "right_context": "}\n\nobject LogicGatesVec extends App {\n chisel3.Driver.execute(args, () => new LogicGatesVec())\n}\n", "groundtruth": " io.leds(6) := ~(io.switches(0) ^ io.switches(1)) // NXOR\n", "crossfile_context": ""}
{"task_id": "homemade-riscv", "path": "homemade-riscv/chap04/04_Mux4/src/main/scala/Mux4.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\n\n/** 4入力マルチプレクサ。\n * selectorの値で、0から3を選択します。\n */\nclass Mux4 extends Module {\n val io = IO(new Bundle {\n val selector = Input(UInt(2.W))\n val in_0 = Input(UInt(1.W))\n val in_1 = Input(UInt(1.W))\n val in_2 = Input(UInt(1.W))\n val in_3 = Input(UInt(1.W))\n val out = Output(UInt(1.W))\n })\n\n io.out := Mux2(io.selector(1),\n Mux2(io.selector(0), io.in_0, io.in_1),\n Mux2(io.selector(0), io.in_2, io.in_3))\n}\n\n/**\n * Mux4のVerilogファイルを生成するための、オブジェクト\n */\n", "right_context": "", "groundtruth": "object Mux4 extends App {\n chisel3.Driver.execute(args, () => new Mux4())\n}\n", "crossfile_context": ""}
{"task_id": "homemade-riscv", "path": "homemade-riscv/chap04/09_FullAdder/src/main/scala/FullAdder.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\n\n/** 全加算器\n */\nclass FullAdder extends Module {\n /** 入出力の信号線を定義 */\n val io = IO(new Bundle {\n val a = Input(UInt(1.W))\n val b = Input(UInt(1.W))\n val carryIn = Input(UInt(1.W))\n val sum = Output(UInt(1.W))\n val carryOut = Output(UInt(1.W))\n })\n\n // まず同一桁の足し算\n val halfAddr = Module(new HalfAdder)\n halfAddr.io.a := io.a\n halfAddr.io.b := io.b\n\n // 同一桁の合計と桁上げ入力の足し算\n val halfAddrCarry = Module(new HalfAdder)\n halfAddrCarry.io.a := halfAddr.io.sum\n halfAddrCarry.io.b := io.carryIn\n\n io.sum := halfAddrCarry.io.sum\n\n // 2つの半加算器の結果のどちらかでも桁上げ出力が発生していたら、全体として桁上げ\n io.carryOut := halfAddr.io.carryOut | halfAddrCarry.io.carryOut\n}\n\n/**\n * Verilogファイルを生成するための、オブジェクト\n */\n", "right_context": "", "groundtruth": "object FullAdder extends App {\n chisel3.Driver.execute(args, () => new FullAdder)\n}\n", "crossfile_context": ""}
{"task_id": "homemade-riscv", "path": "homemade-riscv/chap04/12_LessThan/src/main/scala/Addr4Bit.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\nimport chisel3.util._\n\n/** 加算器(4bit)\n */\nclass Adder4Bit extends Module {\n val io = IO(new Bundle {\n val a = Input(UInt(4.W))\n val b = Input(UInt(4.W))\n\n /* この加算器同士を繋いで、更に多ビットの加算器を作れるようにする。 */\n val carryIn = Input(UInt(1.W))\n\n val sum = Output(UInt(4.W))\n val carryOut = Output(UInt(1.W))\n })\n\n /*\n * 4ビット分のAdderを生成する。\n */\n val adder0 = Module(new FullAdder)\n adder0.io.a := io.a(0)\n adder0.io.b := io.b(0)\n adder0.io.carryIn := io.carryIn\n\n val adder1 = Module(new FullAdder)\n adder1.io.a := io.a(1)\n adder1.io.b := io.b(1)\n adder1.io.carryIn := adder0.io.carryOut // 下位の桁の桁上げ出力が伝搬してくる\n\n val adder2 = Module(new FullAdder)\n adder2.io.a := io.a(2)\n adder2.io.b := io.b(2)\n adder2.io.carryIn := adder1.io.carryOut\n\n val adder3 = Module(new FullAdder)\n adder3.io.a := io.a(3)\n adder3.io.b := io.b(3)\n adder3.io.carryIn := adder2.io.carryOut\n\n // 各桁の合計を連結する\n io.sum := Cat(adder3.io.sum, adder2.io.sum, adder1.io.sum, adder0.io.sum)\n\n io.carryOut := adder3.io.carryOut\n}\n\n/** 加算器(4bit)。forループ版\n */\nclass Adder4BitFor extends Module {\n val io = IO(new Bundle {\n val a = Input(UInt(4.W))\n val b = Input(UInt(4.W))\n val carryIn = Input(UInt(1.W))\n val sum = Output(UInt(4.W))\n val carryOut = Output(UInt(1.W))\n })\n\n", "right_context": " val carries = Wire(Vec(5, UInt(1.W)))\n val sum = Wire(Vec(4, UInt(1.W)))\n\n carries(0) := io.carryIn\n\n for (i <- 0 until 4) {\n fullAdders(i).a := io.a(i)\n fullAdders(i).b := io.b(i)\n fullAdders(i).carryIn := carries(i)\n sum(i) := fullAdders(i).sum\n carries(i + 1) := fullAdders(i).carryOut\n }\n\n io.sum := sum.asUInt\n io.carryOut := carries(4)\n}\n\nclass AdderLED extends Module {\n val io = IO(new Bundle {\n val a = Input(UInt(4.W))\n val b = Input(UInt(4.W))\n val seg7LEDBundle = Output(new Seg7LEDBundle)\n val overflowLED = Output(UInt(1.W)) // 桁溢れが発生したらLEDを点灯させる\n })\n\n val seg7LED = Module(new Seg7LED1Digit)\n val adder = Module(new Adder4Bit)\n adder.io.a := io.a\n adder.io.b := io.b\n adder.io.carryIn := 0.U // 最下位桁の桁上げ入力は存在しないので0を割り当て\n\n seg7LED.io.num := adder.io.sum\n\n io.seg7LEDBundle := seg7LED.io.seg7led\n io.overflowLED := adder.io.carryOut\n}\n\nclass AdderLEDFor extends Module {\n val io = IO(new Bundle {\n val a = Input(UInt(4.W))\n val b = Input(UInt(4.W))\n val seg7LEDBundle = Output(new Seg7LEDBundle)\n val overflowLED = Output(UInt(1.W)) // 桁溢れが発生したらLEDを点灯させる\n })\n\n val seg7LED = Module(new Seg7LED1Digit)\n val adder = Module(new Adder4BitFor)\n adder.io.a := io.a\n adder.io.b := io.b\n adder.io.carryIn := 0.U // 最下位桁の桁上げ入力は存在しないので0を割り当て\n\n seg7LED.io.num := adder.io.sum\n\n io.seg7LEDBundle := seg7LED.io.seg7led\n io.overflowLED := adder.io.carryOut\n}\n\n/**\n * Verilogファイルを生成するための、オブジェクト\n */\nobject AdderLED extends App {\n chisel3.Driver.execute(args, () => new AdderLED)\n}\n\nobject AdderLEDFor extends App {\n chisel3.Driver.execute(args, () => new AdderLEDFor)\n}\n", "groundtruth": " val fullAdders = VecInit(Seq.fill(4){ Module(new FullAdder).io }) // [注意]ioを渡している\n", "crossfile_context": ""}
{"task_id": "homemade-riscv", "path": "homemade-riscv/chap04/13_Shifter/src/main/scala/LeftShift.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\nimport chisel3.util._\n\n/** 左シフタ。\n */\nclass LeftShifter extends Module {\n val io = IO(new Bundle {\n val in = Input(UInt(4.W))\n val shiftAmount = Input(UInt(2.W)) // 入力が4ビットなので、2ビットで十分\n val out = Output(UInt(4.W))\n })\n\n // 最下位ビットはシフト量が0の時に入力最下位ビットを出力。それ以外は0になる。\n val mux0 = Module(new Mux4)\n mux0.io.selector := io.shiftAmount\n mux0.io.in_0 := io.in(0)\n mux0.io.in_1 := 0.U\n mux0.io.in_2 := 0.U\n mux0.io.in_3 := 0.U\n\n val mux1 = Module(new Mux4)\n mux1.io.selector := io.shiftAmount\n", "right_context": " mux1.io.in_3 := 0.U\n\n val mux2 = Module(new Mux4)\n mux2.io.selector := io.shiftAmount\n mux2.io.in_0 := io.in(2)\n mux2.io.in_1 := io.in(1)\n mux2.io.in_2 := io.in(0)\n mux2.io.in_3 := 0.U\n\n val mux3 = Module(new Mux4)\n mux3.io.selector := io.shiftAmount\n mux3.io.in_0 := io.in(3)\n mux3.io.in_1 := io.in(2)\n mux3.io.in_2 := io.in(1)\n mux3.io.in_3 := io.in(0)\n\n io.out := Cat(mux3.io.out, mux2.io.out, mux1.io.out, mux0.io.out)\n}\n\n/**\n * Verilogファイルを生成するための、オブジェクト\n */\nobject LeftShifter extends App {\n chisel3.Driver.execute(args, () => new LeftShifter)\n}\n", "groundtruth": " mux1.io.in_0 := io.in(1)\n mux1.io.in_1 := io.in(0)\n", "crossfile_context": ""}
{"task_id": "homemade-riscv", "path": "homemade-riscv/chap04/14_Multiplier/src/main/scala/Multiplier.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\nimport chisel3.util._\n\n/** 乗算器(4bit)\n */\nclass Multiplier4Bit extends Module {\n val io = IO(new Bundle {\n val a = Input(UInt(4.W))\n val b = Input(UInt(4.W))\n val result = Output(UInt(8.W))\n })\n\n // 各桁の計算をする\n val digit0 = Wire(UInt(4.W))\n val digit1 = Wire(UInt(4.W))\n val digit2 = Wire(UInt(4.W))\n val digit3 = Wire(UInt(4.W))\n digit0 := io.a & Fill(4, io.b(0)) // b(0)を4つコピーしてからANDをとる\n digit1 := io.a & Fill(4, io.b(1))\n digit2 := io.a & Fill(4, io.b(2))\n digit3 := io.a & Fill(4, io.b(3))\n\n // 0桁目と1桁目の足し算\n val adder1 = Module(new Adder4Bit)\n adder1.io.a := digit1\n adder1.io.b := Cat(0.U, digit0(3, 1)) // digit0の3〜1ビット目を使っている\n adder1.io.carryIn := 0.U // 桁上げ入力は不要\n\n // 1桁目の足し算の結果と2桁目の足し算\n val adder2 = Module(new Adder4Bit)\n adder2.io.a := digit2\n adder2.io.b := Cat(adder1.io.carryOut, adder1.io.sum(3, 1))\n adder2.io.carryIn := 0.U\n\n val adder3 = Module(new Adder4Bit)\n adder3.io.a := digit3\n adder3.io.b := Cat(adder2.io.carryOut, adder2.io.sum(3, 1))\n adder3.io.carryIn := 0.U\n\n io.result := Cat(adder3.io.carryOut, adder3.io.sum,\n adder2.io.sum(0), adder1.io.sum(0), digit0(0))\n}\n\n/** 乗算器(4bit)\n */\nclass Multiplier4Bit2 extends Module {\n val io = IO(new Bundle {\n val a = Input(UInt(4.W))\n val b = Input(UInt(4.W))\n val result = Output(UInt(8.W))\n })\n\n val digits = VecInit(\n for (i <- 0 until 4) yield { io.a & Fill(4, io.b(i)) }\n )\n\n val adders = VecInit(Seq.fill(3){ Module(new Adder4Bit).io })\n for (i <- 0 until 3) {\n adders(i).a := digits(i + 1)\n if (i == 0) {\n adders(i).b := Cat(0.U, digits(i)(3, 1)) // digits(0)(3, 1)はdigits(0).apply(3, 1)の略\n } else {\n adders(i).b := Cat(adders(i - 1).carryOut, adders(i - 1).sum(3, 1))\n }\n adders(i).carryIn := 0.U // 桁上げ入力は不要\n }\n\n io.result := Cat(adders(2).carryOut, adders(2).sum,\n adders(1).sum(0), adders(0).sum(0), digits(0)(0))\n}\n\n/** 乗算器\n * \n * @param n ビット幅\n */\nclass Multiplier(n: Int) extends Module {\n val io = IO(new Bundle {\n val a = Input(UInt(n.W))\n val b = Input(UInt(n.W))\n val result = Output(UInt((2 * n).W))\n })\n\n val digits = VecInit(\n for (i <- 0 until n) yield { io.a & Fill(n, io.b(i)) }\n )\n\n val adders = VecInit(Seq.fill(n - 1){ Module(new Adder4Bit).io })\n for (i <- 0 until (n - 1)) {\n adders(i).a := digits(i + 1)\n if (i == 0) {\n // digits(0)(n - 1, 1)はdigits(0).apply(n - 1, 1)の略\n adders(i).b := Cat(0.U, digits(i)(n - 1, 1)) \n } else {\n adders(i).b := Cat(adders(i - 1).carryOut, adders(i - 1).sum(n - 1, 1))\n }\n adders(i).carryIn := 0.U // 桁上げ入力は不要\n }\n\n", "right_context": " io.result := Cat(adders(n - 2).carryOut, adders(n - 2).sum(n - 1, 1), adderLsbs, digits(0)(0))\n}\n\nobject Multiplier4Bit extends App {\n chisel3.Driver.execute(args, () => new Multiplier4Bit)\n}\n\nobject Multiplier4Bit2 extends App {\n chisel3.Driver.execute(args, () => new Multiplier4Bit2)\n}\n\nobject Multiplier extends App {\n chisel3.Driver.execute(args, () => new Multiplier(4))\n}\n", "groundtruth": " val adderLsbs = Cat(for (i <- (n - 2) to 0 by -1) yield { adders(i).sum(0) })\n", "crossfile_context": ""}
{"task_id": "homemade-riscv", "path": "homemade-riscv/chap05/02_DFlipFlop/src/main/scala/SRLatch.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\n\n/** SRラッチ\n */\nclass SRLatch extends Module {\n val io = IO(new Bundle {\n val set = Input(Bool())\n val reset = Input(Bool())\n val q = Output(Bool())\n val notQ = Output(Bool())\n })\n\n io.q := ~(io.reset | io.notQ)\n io.notQ := ~(io.set | io.q)\n}\n\n", "right_context": "", "groundtruth": "object SRLatch extends App {\n chisel3.Driver.execute(args, () => new SRLatch)\n}\n", "crossfile_context": ""}
{"task_id": "homemade-riscv", "path": "homemade-riscv/chap05/03_SyncResetFF/src/main/scala/DLatch.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\n\n/** Dラッチ\n */\nclass DLatch extends Module {\n val io = IO(new Bundle {\n val data = Input(Bool())\n val enable = Input(Bool())\n val q = Output(Bool())\n })\n\n val srLatch = Module(new SRLatch)\n srLatch.io.reset := io.enable & ~io.data\n srLatch.io.set := io.enable & io.data\n\n io.q := srLatch.io.q\n}\n\n", "right_context": "", "groundtruth": "object DLatch extends App {\n chisel3.Driver.execute(args, () => new DLatch)\n}\n", "crossfile_context": ""}
{"task_id": "homemade-riscv", "path": "homemade-riscv/chap05/09_Stopwatch/src/main/scala/Stopwatch.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\nimport chisel3.util._\n\n/** ストップウォッチ\n */\nclass Stopwatch extends Module {\n val io = IO(new Bundle {\n val startStop = Input(Bool())\n val seg7led = Output(new Seg7LEDBundle)\n })\n\n val running = RegInit(false.B)\n when (Debounce(io.startStop)) {\n running := ~running\n }\n\n val (clockNum, centimalSec) = Counter(running, 1000000) // 1Mクロック(1/100秒)分カウント\n val (cSec, oneSec) = Counter(centimalSec, 100) // 1秒カウント\n val (sec, oneMin) = Counter(oneSec, 60) // 60秒カウント\n val (min, oneHour) = Counter(oneMin, 60) // 60分カウント\n val (hour, oneDay) = Counter(oneHour, 24) // 24時間カウント\n\n val seg7LED = Module(new Seg7LED)\n seg7LED.io.digits := VecInit(List(cSec % 10.U, (cSec / 10.U)(3, 0), sec % 10.U, (sec / 10.U)(3, 0),\n min % 10.U, (min / 10.U)(3, 0), hour % 10.U, (hour / 10.U)(3, 0)))\n\n io.seg7led := seg7LED.io.seg7led\n}\n\n", "right_context": "", "groundtruth": "object Stopwatch extends App {\n chisel3.Driver.execute(args, () => new Stopwatch)\n}\n", "crossfile_context": ""}
{"task_id": "homemade-riscv", "path": "homemade-riscv/chap05/15_SvgaUartDisp/src/main/scala/Uart.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\nimport chisel3.util._\n\n/** UART\n */\nclass Uart extends Module {\n val io = IO(new Bundle {\n", "right_context": "\n val uartRx = Module(new UartRx)\n uartRx.io.rxData := io.rxData\n io.receiveData <> uartRx.io.receiveData\n\n val uartTx = Module(new UartTx)\n io.txData := uartTx.io.txData\n uartTx.io.sendData <> io.sendData\n\n io.rts := false.B\n}\n\n/** UART送信\n */\nclass UartTx extends Module {\n val io = IO(new Bundle {\n val sendData = Flipped(Decoupled(UInt(8.W)))\n val txData = Output(Bool())\n })\n\n /* ステート・マシン定義 */\n val sIdle :: sStartBit :: sSend :: sStopBit :: Nil = Enum(4)\n val state = RegInit(sIdle)\n\n val (txCount, txEnable) = Counter(true.B, 100000000 / 115200) // 状態遷移用カウンタ\n val sendCount = Reg(UInt(3.W)) // 8ビット送信\n val shiftReg = Module(new ShiftRegisterPISO(8)) // 送信データ用シフトレジスタ\n shiftReg.io.d := Reverse(io.sendData.bits)\n shiftReg.io.load := io.sendData.valid\n shiftReg.io.enable := state === sSend && txEnable\n\n // 状態遷移\n when (state === sIdle && io.sendData.valid) {\n state := sStartBit\n txCount := 0.U\n } .elsewhen (txEnable) {\n switch (state) {\n is (sStartBit) {\n state := sSend\n sendCount := 0.U\n }\n is (sSend) {\n when (sendCount === 7.U) {\n state := sStopBit\n } .otherwise {\n sendCount := sendCount + 1.U\n }\n }\n is (sStopBit) {\n state := sIdle\n }\n }\n }\n\n io.sendData.ready := state === sIdle\n \n io.txData := MuxCase(true.B, Array(\n (state === sStartBit) -> false.B,\n (state === sSend) -> shiftReg.io.shiftOut,\n (state === sStopBit) -> true.B))\n}\n\n/** UART受信\n */\nclass UartRx extends Module {\n val io = IO(new Bundle {\n val rxData = Input(Bool())\n val receiveData = Decoupled(UInt(8.W))\n })\n\n /* ステート・マシン定義 */\n val sIdle :: sStartBit :: sReceive :: sStopBit :: Nil = Enum(4)\n val state = RegInit(sIdle)\n\n val (rxCount, rxEnable) = Counter(true.B, 100000000 / 115200) // 状態遷移用カウンタ\n val (rxHalfCount, rxHalfEnable) = Counter(true.B, 100000000 / 115200 / 2) // 1/2ビット周期カウンタ\n val receiveCount = Reg(UInt(3.W)) // 8ビット受信\n\n val shiftReg = Module(new ShiftRegisterSIPO(8))\n shiftReg.io.shiftIn := io.rxData\n shiftReg.io.enable := state === sReceive && rxEnable\n\n val rDataValid = RegInit(false.B)\n val start = NegEdge(Synchronizer(io.rxData))\n\n // 状態遷移\n when (state === sIdle && start) {\n state := sStartBit\n rxHalfCount := 0.U\n } .elsewhen (state === sStartBit && rxHalfEnable) {\n state := sReceive\n rxCount := 0.U\n receiveCount := 0.U\n } .elsewhen (rxEnable) {\n switch (state) {\n is (sReceive) {\n when (receiveCount === 7.U) {\n state := sStopBit\n } .otherwise {\n receiveCount := receiveCount + 1.U\n }\n }\n is (sStopBit) {\n when (rxEnable) {\n state := sIdle\n }\n }\n }\n }\n\n when (state === sStopBit && rxEnable) {\n rDataValid := true.B\n } .elsewhen (io.receiveData.ready) {\n rDataValid := false.B\n }\n\n io.receiveData.bits := Reverse(shiftReg.io.q)\n io.receiveData.valid := rDataValid\n}\n", "groundtruth": " val rxData = Input(Bool())\n val txData = Output(Bool())\n val rts = Output(Bool())\n val cts = Input(Bool())\n", "crossfile_context": ""}
{"task_id": "homemade-riscv", "path": "homemade-riscv/chap07/00_PencilRocketI/src/main/scala/NegEdge.scala", "left_context": "// See LICENSE for license details.\n\nimport chisel3._\nimport chisel3.util._\n\n/** 入力の立ち下がりを検出します。\n */\nclass NegEdge extends Module {\n val io = IO(new Bundle {\n", "right_context": "\n val reg = RegNext(io.d, false.B)\n\n io.pulse := reg && !io.d\n}\n\nobject NegEdge {\n def apply(d: Bool): Bool = {\n val negEdge = Module(new NegEdge)\n negEdge.io.d := d\n negEdge.io.pulse\n }\n}\n", "groundtruth": " val d = Input(Bool())\n val pulse = Output(Bool())\n", "crossfile_context": ""}
{"task_id": "CHISEL-Projects", "path": "CHISEL-Projects/src/main/scala/lab7/lab7ex1.scala", "left_context": "package lab7\nimport chisel3._\nimport chisel3.util._\nclass ex1 extends Module {\n val io = IO (new Bundle {\n", "right_context": " val in2 = Flipped(Decoupled(UInt(8.W))) //ready-> output , valid->input\n val out = Decoupled(UInt(8.W)) // ready-> input, valid->output\n })\n io.in1.ready:=0.B\n io.in2.ready:=0.B\n\n val q1= Queue(io.in1,4)\n val q2= Queue(io.in2,4)\n val arb_noPriority = Module (new RRArbiter ( UInt () , 2) )\n// connect the inputs to different producers\n arb_noPriority . io . in (0) <> q1\n arb_noPriority . io . in (1) <> q2\n io.out <> arb_noPriority.io.out\n}", "groundtruth": " val in1 = Flipped(Decoupled(UInt(8.W))) //ready-> output , valid->input\n", "crossfile_context": ""}
{"task_id": "CHISEL-Projects", "path": "CHISEL-Projects/src/main/scala/lab8/lab8ex1.scala", "left_context": "package lab8\nimport chisel3 . _\nimport chisel3.util._\n\nclass MaskedReadWriteSmem extends Module {\nval width : Int = 8\n val io = IO (new Bundle {\n val enable = Input ( Bool () )\n val write = Input ( Bool () )\n val addr = Input ( UInt (10. W ) )\n val mask = Input ( Vec (4 , Bool () ) )\n val dataIn = Input ( Vec (4 , UInt ( width . W ) ) )\n val dataOut = Output ( Vec (4 , UInt ( width . W ) ) )\n })\n// Create a 32 - bit wide memory that is byte - masked\n val mem = SyncReadMem (1024 , Vec (4 , UInt ( width . W ) ) )\n val sel= Cat(io.mask(3),io.mask(2),io.mask(1),io.mask(0)).asUInt\n // io.dataOut:=mem.read(io.addr,io.enable)\n \n val data= Reg(Vec(4,UInt(width.W)))\n when (io.write){\n", "right_context": " when(io.mask(2)){\n data(2):=io.dataIn(3)\n }.otherwise{\n data(2):=0.U(width.W)\n }\n when(io.mask(1)){\n data(1):=io.dataIn(3)\n }.otherwise{\n data(1):=0.U(width.W)\n }\n when(io.mask(0)){\n data(0):=io.dataIn(3)\n }.otherwise{\n data(0):=0.U(width.W)\n }\n mem.write(io.addr,data)\n } \n io.dataOut := mem.read(io.addr,io.enable)\n}\n", "groundtruth": " when(io.mask(3)){\n data(3):=io.dataIn(3)\n }.otherwise{\n", "crossfile_context": ""}
{"task_id": "CHISEL-Projects", "path": "CHISEL-Projects/src/main/scala/labs/lab1task1.scala", "left_context": "package labs\nimport chisel3._\n \nclass mux extends Module{\n val io=IO(new Bundle{\n val a=Input(UInt(4.W))\n val b=Input(UInt(4.W))\n val sel=Input(UInt(3.W))\n val x=Output(UInt(4.W))\n\n })\n", "right_context": " io.x:=io.a & io.b\n }.elsewhen(io.sel===3.U){\n io.x:=io.a | io.b\n }.elsewhen(io.sel===4.U){\n io.x:=io.a ^ io.b\n }.elsewhen(io.sel===5.U){\n io.x:= ~(io.a ^ io.b)\n }.otherwise{\n io.x:=0.U\n }\n}", "groundtruth": " when(io.sel===0.U){\n io.x:=io.a + io.b\n }.elsewhen(io.sel===1.U){\n", "crossfile_context": ""}
{"task_id": "CHISEL-Projects", "path": "CHISEL-Projects/src/main/scala/labs/lab3ex1.scala", "left_context": "package labs\nimport chisel3._\nimport chisel3.util._\n\nclass EncoderIO extends Bundle {\n val in = Input ( UInt (4. W ) )\n val out = Output ( UInt (2. W ) )\n}\nclass Encoder4to2 extends Module {\n val io = IO (new EncoderIO )\n io.out:=0.U\n switch(io.in){\n is(\"b0001\".U){io.out:=\"b00\".U}\n is(\"b0010\".U){io.out:=\"b01\".U}\n is(\"b0100\".U){io.out:= \"b10\".U}\n", "right_context": " }\n}\n", "groundtruth": " is(\"b1000\".U){io.out:=\"b11\".U}\n", "crossfile_context": ""}
{"task_id": "CHISEL-Projects", "path": "CHISEL-Projects/src/test/scala/lab1/lab1ex2test.scala", "left_context": "package labs\nimport chisel3._\nimport org.scalatest._\nimport chiseltest._\n\nclass resettest extends FreeSpec with ChiselScalatestTester {\n \"Reset Test\" in {\n", "right_context": "", "groundtruth": " test(new resetcounter(5)){c=>\n c.clock.step(20)\n c.io.result.expect(0.B)\n\n }\n", "crossfile_context": ""}
{"task_id": "CHISEL-Projects", "path": "CHISEL-Projects/src/test/scala/lab2/lab2ex1test.scala", "left_context": "package labs\nimport chisel3._\nimport org.scalatest._\nimport chiseltest._\n\n", "right_context": " \"mux2 Test\" in {\n test(new Mux_2to1()){c=>\n c.io.in_A.poke(10.U)\n c.io.in_B.poke(11.U)\n c.io.select.poke(0.B)\n c.clock.step(20)\n c.io.out.expect(10.B)\n\n }\n }\n}", "groundtruth": "class mux2test extends FreeSpec with ChiselScalatestTester {\n", "crossfile_context": ""}
{"task_id": "CHISEL-Projects", "path": "CHISEL-Projects/src/test/scala/labs/lab3ex2test.scala", "left_context": "package labs\nimport chisel3._\nimport org.scalatest._\nimport chiseltest._\nclass ALUtest extends FreeSpec with ChiselScalatestTester{\n", "right_context": " }\n }\n}", "groundtruth": " \"ALU Test\" in {\n test(new ALU()){c=>\n c.io.in_A.poke(4.U)\n c.io.in_B.poke(5.U)\n c.io.alu_Op.poke(4.U)\n", "crossfile_context": ""}
{"task_id": "CHISEL-Projects", "path": "CHISEL-Projects/src/test/scala/labs/lab5task1test.scala", "left_context": "package labs\nimport chisel3._\nimport org.scalatest._\nimport chiseltest._\nclass Adder5test extends FreeSpec with ChiselScalatestTester{\n \"Adder5 Test\" in {\n", "right_context": "\n }\n }\n}\n", "groundtruth": " test(new Adder5(32)){c=>\n c.io.in0.poke(2.U)\n c.io.in1.poke(2.U)\n", "crossfile_context": ""}
{"task_id": "CHISEL-Projects", "path": "CHISEL-Projects/src/test/scala/practice/NANDtest.scala", "left_context": "package labs\nimport chisel3._\nimport org.scalatest._\nimport chiseltest._\n\nclass NANDtest extends FreeSpec with ChiselScalatestTester {\n", "right_context": " }\n }\n}", "groundtruth": " \"NAND Gate Test\" in {\n test(new NAND()){c=>\n c.io.a.poke(8.S)\n c.io.b.poke(15.S)\n", "crossfile_context": ""}
{"task_id": "CHISEL-Projects", "path": "CHISEL-Projects/src/test/scala/practice/fulladdertest.scala", "left_context": "package labs\nimport chisel3._\nimport org.scalatest._\nimport chiseltest._\n\nclass fulladdertest extends FreeSpec with ChiselScalatestTester {\n \"fulladder Gate Test\" in {\n test(new fulladder()){c=>\n c.io.a.poke(8.S)\n", "right_context": "", "groundtruth": " c.io.b.poke(-15.S)\n c.io.c.poke(2.S)\n c.clock.step(1)\n c.io.sum.expect(-5.S)\n c.io.cout.expect(0.S)\n", "crossfile_context": ""}
{"task_id": "CHISEL-Projects", "path": "CHISEL-Projects/src/test/scala/practice/halfaddertest.scala", "left_context": "package labs\nimport chisel3._\nimport org.scalatest._\nimport chiseltest._\n\nclass halfaddertest extends FreeSpec with ChiselScalatestTester {\n \"halfadder Gate Test\" in {\n", "right_context": " c.clock.step(1)\n c.io.sum.expect(-7.S)\n c.io.cout.expect(0.S)\n\n }\n }\n}", "groundtruth": " test(new halfadder()){c=>\n c.io.a.poke(8.S)\n", "crossfile_context": ""}
{"task_id": "chipyard", "path": "chipyard/generators/chipyard/src/main/scala/clocking/CanHaveClockTap.scala", "left_context": "package chipyard.clocking\n\nimport chisel3._\n\nimport org.chipsalliance.cde.config.{Parameters, Field, Config}\nimport freechips.rocketchip.diplomacy._\nimport freechips.rocketchip.tilelink._\nimport freechips.rocketchip.subsystem._\nimport freechips.rocketchip.util._\nimport freechips.rocketchip.tile._\nimport freechips.rocketchip.prci._\n\n", "right_context": "\ntrait CanHaveClockTap { this: BaseSubsystem =>\n require(!p(SubsystemDriveClockGroupsFromIO), \"Subsystem must not drive clocks from IO\")\n val clockTapNode = Option.when(p(ClockTapKey)) {\n val clockTap = ClockSinkNode(Seq(ClockSinkParameters(name=Some(\"clock_tap\"))))\n clockTap := ClockGroup() := allClockGroupsNode\n clockTap\n }\n val clockTapIO = clockTapNode.map { node => InModuleBody {\n val clock_tap = IO(Output(Clock()))\n clock_tap := node.in.head._1.clock\n clock_tap\n }}\n}\n", "groundtruth": "case object ClockTapKey extends Field[Boolean](true)\n", "crossfile_context": ""}
{"task_id": "chipyard", "path": "chipyard/generators/chipyard/src/main/scala/config/BoomConfigs.scala", "left_context": "package chipyard\n\nimport org.chipsalliance.cde.config.{Config}\n\n// ---------------------\n// BOOM V3 Configs\n// Performant, stable baseline\n// ---------------------\n\nclass SmallBoomV3Config extends Config(\n new boom.v3.common.WithNSmallBooms(1) ++ // small boom config\n new chipyard.config.AbstractConfig)\n\nclass MediumBoomV3Config extends Config(\n new boom.v3.common.WithNMediumBooms(1) ++ // medium boom config\n new chipyard.config.AbstractConfig)\n\nclass LargeBoomV3Config extends Config(\n new boom.v3.common.WithNLargeBooms(1) ++ // large boom config\n new chipyard.config.WithSystemBusWidth(128) ++\n new chipyard.config.AbstractConfig)\n\nclass MegaBoomV3Config extends Config(\n new boom.v3.common.WithNMegaBooms(1) ++ // mega boom config\n new chipyard.config.WithSystemBusWidth(128) ++\n new chipyard.config.AbstractConfig)\n\nclass DualSmallBoomV3Config extends Config(\n new boom.v3.common.WithNSmallBooms(2) ++ // 2 boom cores\n new chipyard.config.AbstractConfig)\n\nclass Cloned64MegaBoomV3Config extends Config(\n new boom.v3.common.WithCloneBoomTiles(63, 0) ++\n new boom.v3.common.WithNMegaBooms(1) ++ // mega boom config\n new chipyard.config.WithSystemBusWidth(128) ++\n new chipyard.config.AbstractConfig)\n\nclass LoopbackNICLargeBoomV3Config extends Config(\n new chipyard.harness.WithLoopbackNIC ++ // drive NIC IOs with loopback\n new icenet.WithIceNIC ++ // build a NIC\n new boom.v3.common.WithNLargeBooms(1) ++\n new chipyard.config.WithSystemBusWidth(128) ++\n new chipyard.config.AbstractConfig)\n\nclass MediumBoomV3CosimConfig extends Config(\n new chipyard.harness.WithCospike ++ // attach spike-cosim\n new chipyard.config.WithTraceIO ++ // enable the traceio\n new boom.v3.common.WithNMediumBooms(1) ++\n new chipyard.config.AbstractConfig)\n\nclass dmiCheckpointingMediumBoomV3Config extends Config(\n new chipyard.config.WithNPMPs(0) ++ // remove PMPs (reduce non-core arch state)\n new chipyard.harness.WithSerialTLTiedOff ++ // don't attach anything to serial-tl\n new chipyard.config.WithDMIDTM ++ // have debug module expose a clocked DMI port\n new boom.v3.common.WithNMediumBooms(1) ++\n new chipyard.config.AbstractConfig)\n\nclass dmiMediumBoomV3CosimConfig extends Config(\n new chipyard.harness.WithCospike ++ // attach spike-cosim\n new chipyard.config.WithTraceIO ++ // enable the traceio\n new chipyard.harness.WithSerialTLTiedOff ++ // don't attach anythint to serial-tl\n new chipyard.config.WithDMIDTM ++ // have debug module expose a clocked DMI port\n new boom.v3.common.WithNMediumBooms(1) ++\n new chipyard.config.AbstractConfig)\n\nclass SimBlockDeviceMegaBoomV3Config extends Config(\n new chipyard.harness.WithSimBlockDevice ++ // drive block-device IOs with SimBlockDevice\n new testchipip.iceblk.WithBlockDevice ++ // add block-device module to peripherybus\n new boom.v3.common.WithNMegaBooms(1) ++ // mega boom config\n new chipyard.config.WithSystemBusWidth(128) ++\n new chipyard.config.AbstractConfig)\n\n// ---------------------\n// BOOM V4 Configs\n// Less stable and performant, but with more advanced micro-architecture\n// Use for PD exploration\n// ---------------------\n\nclass SmallBoomV4Config extends Config(\n new boom.v4.common.WithNSmallBooms(1) ++ // small boom config\n new chipyard.config.AbstractConfig)\n\nclass MediumBoomV4Config extends Config(\n new boom.v4.common.WithNMediumBooms(1) ++ // medium boom config\n new chipyard.config.AbstractConfig)\n\nclass LargeBoomV4Config extends Config(\n new boom.v4.common.WithNLargeBooms(1) ++ // large boom config\n new chipyard.config.WithSystemBusWidth(128) ++\n new chipyard.config.AbstractConfig)\n\n", "right_context": " new chipyard.config.AbstractConfig)\n\nclass Cloned64MegaBoomV4Config extends Config(\n new boom.v4.common.WithCloneBoomTiles(63, 0) ++\n new boom.v4.common.WithNMegaBooms(1) ++ // mega boom config\n new chipyard.config.WithSystemBusWidth(128) ++\n new chipyard.config.AbstractConfig)\n\nclass MediumBoomV4CosimConfig extends Config(\n new chipyard.harness.WithCospike ++ // attach spike-cosim\n new chipyard.config.WithTraceIO ++ // enable the traceio\n new boom.v4.common.WithNMediumBooms(1) ++\n new chipyard.config.AbstractConfig)\n\nclass dmiCheckpointingMediumBoomV4Config extends Config(\n new chipyard.config.WithNPMPs(0) ++ // remove PMPs (reduce non-core arch state)\n new chipyard.harness.WithSerialTLTiedOff ++ // don't attach anything to serial-tl\n new chipyard.config.WithDMIDTM ++ // have debug module expose a clocked DMI port\n new boom.v4.common.WithNMediumBooms(1) ++\n new chipyard.config.AbstractConfig)\n\nclass dmiMediumBoomV4CosimConfig extends Config(\n new chipyard.harness.WithCospike ++ // attach spike-cosim\n new chipyard.config.WithTraceIO ++ // enable the traceio\n new chipyard.harness.WithSerialTLTiedOff ++ // don't attach anythint to serial-tl\n new chipyard.config.WithDMIDTM ++ // have debug module expose a clocked DMI port\n new boom.v4.common.WithNMediumBooms(1) ++\n new chipyard.config.AbstractConfig)\n\nclass SimBlockDeviceMegaBoomV4Config extends Config(\n new chipyard.harness.WithSimBlockDevice ++ // drive block-device IOs with SimBlockDevice\n new testchipip.iceblk.WithBlockDevice ++ // add block-device module to peripherybus\n new boom.v4.common.WithNMegaBooms(1) ++ // mega boom config\n new chipyard.config.WithSystemBusWidth(128) ++\n new chipyard.config.AbstractConfig)\n", "groundtruth": "class MegaBoomV4Config extends Config(\n new boom.v4.common.WithNMegaBooms(1) ++ // mega boom config\n new chipyard.config.WithSystemBusWidth(128) ++\n new chipyard.config.AbstractConfig)\n", "crossfile_context": ""}
{"task_id": "chipyard", "path": "chipyard/generators/chipyard/src/main/scala/config/fragments/RoCCFragments.scala", "left_context": "package chipyard.config\n\nimport chisel3._\n\nimport org.chipsalliance.cde.config.{Field, Parameters, Config}\nimport freechips.rocketchip.tile._\nimport freechips.rocketchip.diplomacy._\n\n\nimport chipyard.{TestSuitesKey, TestSuiteHelper}\n\n/**\n * Map from a tileId to a particular RoCC accelerator\n */\n", "right_context": "\n/**\n * Config fragment to enable different RoCCs based on the tileId\n */\nclass WithMultiRoCC extends Config((site, here, up) => {\n case BuildRoCC => site(MultiRoCCKey).getOrElse(site(TileKey).tileId, Nil)\n})\n\n/**\n * Assigns what was previously in the BuildRoCC key to specific harts with MultiRoCCKey\n * Must be paired with WithMultiRoCC\n */\nclass WithMultiRoCCFromBuildRoCC(harts: Int*) extends Config((site, here, up) => {\n case BuildRoCC => Nil\n case MultiRoCCKey => up(MultiRoCCKey, site) ++ harts.distinct.map { i =>\n (i -> up(BuildRoCC, site))\n }\n})\n\nclass WithAccumulatorRoCC(op: OpcodeSet = OpcodeSet.custom1) extends Config((site, here, up) => {\n case BuildRoCC => up(BuildRoCC) ++ Seq((p: Parameters) => {\n val accumulator = LazyModule(new AccumulatorExample(op, n = 4)(p))\n accumulator\n })\n})\n\nclass WithCharacterCountRoCC(op: OpcodeSet = OpcodeSet.custom2) extends Config((site, here, up) => {\n case BuildRoCC => up(BuildRoCC) ++ Seq((p: Parameters) => {\n val counter = LazyModule(new CharacterCountExample(op)(p))\n counter\n })\n})\n", "groundtruth": "case object MultiRoCCKey extends Field[Map[Int, Seq[Parameters => LazyRoCC]]](Map.empty[Int, Seq[Parameters => LazyRoCC]])\n", "crossfile_context": ""}
{"task_id": "chipyard", "path": "chipyard/generators/chipyard/src/main/scala/example/EmptyChipTop.scala", "left_context": "package chipyard.example\n\nimport chisel3._\n\nimport org.chipsalliance.cde.config._\nimport freechips.rocketchip.diplomacy._\nimport freechips.rocketchip.util.{DontTouch}\n\nimport chipyard._\nimport chipyard.harness.{BuildTop}\n\nclass EmptyChipTop(implicit p: Parameters) extends LazyModule {\n override lazy val module = new Impl\n", "right_context": "class WithEmptyChipTop extends Config((site, here, up) => {\n case BuildTop => (p: Parameters) => new EmptyChipTop()(p)\n})\n", "groundtruth": " class Impl extends LazyRawModuleImp(this) with DontTouch {\n // Your custom non-rocketchip-soc stuff here\n }\n", "crossfile_context": ""}
{"task_id": "chipyard", "path": "chipyard/generators/chipyard/src/main/scala/example/TutorialTile.scala", "left_context": "package chipyard.example\n\nimport chisel3._\nimport chisel3.util._\n\nimport org.chipsalliance.cde.config._\nimport freechips.rocketchip.subsystem._\nimport freechips.rocketchip.devices.tilelink._\nimport freechips.rocketchip.diplomacy._\nimport freechips.rocketchip.rocket._\nimport freechips.rocketchip.subsystem.{RocketCrossingParams}\nimport freechips.rocketchip.tilelink._\nimport freechips.rocketchip.interrupts._\nimport freechips.rocketchip.util._\nimport freechips.rocketchip.tile._\nimport freechips.rocketchip.amba.axi4._\nimport freechips.rocketchip.prci._\n\n// Example parameter class copied from CVA6, not included in documentation but for compile check only\n// If you are here for documentation, DO NOT copy MyCoreParams and MyTileParams directly - always figure\n// out what parameters you need before you write the parameter class\ncase class MyCoreParams(\n bootFreqHz: BigInt = BigInt(1700000000),\n rasEntries: Int = 4,\n btbEntries: Int = 16,\n bhtEntries: Int = 16,\n enableToFromHostCaching: Boolean = false,\n) extends CoreParams {\n val xLen: Int = 32\n val pgLevels: Int = 2\n val useVM: Boolean = true\n val useHypervisor: Boolean = false\n val useUser: Boolean = true\n val useSupervisor: Boolean = false\n val useDebug: Boolean = true\n val useAtomics: Boolean = true\n val useAtomicsOnlyForIO: Boolean = false // copied from Rocket\n val useCompressed: Boolean = true\n override val useVector: Boolean = false\n val useSCIE: Boolean = false\n val useRVE: Boolean = false\n val mulDiv: Option[MulDivParams] = Some(MulDivParams()) // copied from Rocket\n val fpu: Option[FPUParams] = Some(FPUParams()) // copied fma latencies from Rocket\n val nLocalInterrupts: Int = 0\n val useNMI: Boolean = false\n val nPTECacheEntries: Int = 0 // TODO: Check\n val nPMPs: Int = 0 // TODO: Check\n val pmpGranularity: Int = 4 // copied from Rocket\n val nBreakpoints: Int = 0 // TODO: Check\n val useBPWatch: Boolean = false\n val mcontextWidth: Int = 0\n val scontextWidth: Int = 0\n val nPerfCounters: Int = 29\n val haveBasicCounters: Boolean = true\n val haveFSDirty: Boolean = false\n val misaWritable: Boolean = false\n val haveCFlush: Boolean = false\n val nL2TLBEntries: Int = 512 // copied from Rocket\n val nL2TLBWays: Int = 1\n val mtvecInit: Option[BigInt] = Some(BigInt(0)) // copied from Rocket\n val mtvecWritable: Boolean = true // copied from Rocket\n val instBits: Int = if (useCompressed) 16 else 32\n val lrscCycles: Int = 80 // copied from Rocket\n val decodeWidth: Int = 1 // TODO: Check\n val fetchWidth: Int = 1 // TODO: Check\n val retireWidth: Int = 2\n val traceHasWdata: Boolean = false\n val useConditionalZero = false\n val useZba: Boolean = false\n val useZbb: Boolean = false\n val useZbs: Boolean = false\n}\n\n// DOC include start: CanAttachTile\ncase class MyTileAttachParams(\n tileParams: MyTileParams,\n crossingParams: RocketCrossingParams\n) extends CanAttachTile {\n type TileType = MyTile\n val lookup = PriorityMuxHartIdFromSeq(Seq(tileParams))\n}\n// DOC include end: CanAttachTile\n\ncase class MyTileParams(\n name: Option[String] = Some(\"my_tile\"),\n tileId: Int = 0,\n trace: Boolean = false,\n val core: MyCoreParams = MyCoreParams()\n) extends InstantiableTileParams[MyTile]\n{\n val beuAddr: Option[BigInt] = None\n val blockerCtrlAddr: Option[BigInt] = None\n val btb: Option[BTBParams] = Some(BTBParams())\n val boundaryBuffers: Boolean = false\n val dcache: Option[DCacheParams] = Some(DCacheParams())\n val icache: Option[ICacheParams] = Some(ICacheParams())\n val clockSinkParams: ClockSinkParameters = ClockSinkParameters()\n def instantiate(crossing: HierarchicalElementCrossingParamsLike, lookup: LookupByHartIdImpl)(implicit p: Parameters): MyTile = {\n new MyTile(this, crossing, lookup)\n }\n val baseName = name.getOrElse(\"my_tile\")\n val uniqueName = s\"${baseName}_$tileId\"\n}\n\n// DOC include start: Tile class\nclass MyTile(\n val myParams: MyTileParams,\n crossing: ClockCrossingType,\n lookup: LookupByHartIdImpl,\n q: Parameters)\n extends BaseTile(myParams, crossing, lookup, q)\n with SinksExternalInterrupts\n with SourcesExternalNotifications\n{\n\n // Private constructor ensures altered LazyModule.p is used implicitly\n def this(params: MyTileParams, crossing: HierarchicalElementCrossingParamsLike, lookup: LookupByHartIdImpl)(implicit p: Parameters) =\n this(params, crossing.crossingType, lookup, p)\n\n // Require TileLink nodes\n val intOutwardNode = None\n val masterNode = visibilityNode\n val slaveNode = TLIdentityNode()\n\n // Implementation class (See below)\n override lazy val module = new MyTileModuleImp(this)\n\n // Required entry of CPU device in the device tree for interrupt purpose\n val cpuDevice: SimpleDevice = new SimpleDevice(\"cpu\", Seq(\"my-organization,my-cpu\", \"riscv\")) {\n", "right_context": " override def describe(resources: ResourceBindings): Description = {\n val Description(name, mapping) = super.describe(resources)\n Description(name, mapping ++\n cpuProperties ++\n nextLevelCacheProperty ++\n tileProperties)\n }\n }\n\n ResourceBinding {\n Resource(cpuDevice, \"reg\").bind(ResourceAddress(tileId))\n }\n\n // TODO: Create TileLink nodes and connections here.\n // DOC include end: Tile class\n\n // DOC include start: AXI4 node\n // # of bits used in TileLink ID for master node. 4 bits can support 16 master nodes, but you can have a longer ID if you need more.\n val idBits = 4\n val memAXI4Node = AXI4MasterNode(\n Seq(AXI4MasterPortParameters(\n masters = Seq(AXI4MasterParameters(\n name = \"myPortName\",\n id = IdRange(0, 1 << idBits))))))\n val memoryTap = TLIdentityNode() // Every bus connection should have their own tap node\n // DOC include end: AXI4 node\n\n // DOC include start: AXI4 convert\n (tlMasterXbar.node // tlMasterXbar is the bus crossbar to be used when this core / tile is acting as a master; otherwise, use tlSlaveXBar\n := memoryTap\n := TLBuffer()\n := TLFIFOFixer(TLFIFOFixer.all) // fix FIFO ordering\n := TLWidthWidget(masterPortBeatBytes) // reduce size of TL\n := AXI4ToTL() // convert to TL\n := AXI4UserYanker(Some(2)) // remove user field on AXI interface. need but in reality user intf. not needed\n := AXI4Fragmenter() // deal with multi-beat xacts\n := memAXI4Node) // The custom node, see below\n // DOC include end: AXI4 convert\n\n}\n\n// DOC include start: Implementation class\nclass MyTileModuleImp(outer: MyTile) extends BaseTileModuleImp(outer){\n // TODO: Create the top module of the core and connect it with the ports in \"outer\"\n\n // If your core is in Verilog (assume your blackbox is called \"MyCoreBlackbox\"), instantiate it here like\n // val core = Module(new MyCoreBlackbox(params...))\n // (as described in the blackbox tutorial) and connect appropriate signals. See the blackbox tutorial\n // (link on the top of the page) for more info.\n // You can look at https://github.com/ucb-bar/cva6-wrapper/blob/master/src/main/scala/CVA6Tile.scala\n // for a Verilog example.\n\n // If your core is in Chisel, you can simply instantiate the top module here like other Chisel module\n // and connect appropriate signal. You can even implement this class as your top module.\n // See https://github.com/riscv-boom/riscv-boom/blob/master/src/main/scala/common/tile.scala and\n // https://github.com/chipsalliance/rocket-chip/blob/master/src/main/scala/tile/RocketTile.scala for\n // Chisel example.\n\n // DOC include end: Implementation class\n\n // DOC include start: connect interrupt\n // For example, our core support debug interrupt and machine-level interrupt, and suppose the following two signals\n // are the interrupt inputs to the core. (DO NOT COPY this code - if your core treat each type of interrupt differently,\n // you need to connect them to different interrupt ports of your core)\n val debug_i = Wire(Bool())\n val mtip_i = Wire(Bool())\n // We create a bundle here and decode the interrupt.\n val int_bundle = new TileInterrupts()\n outer.decodeCoreInterrupts(int_bundle)\n debug_i := int_bundle.debug\n mtip_i := int_bundle.meip & int_bundle.msip & int_bundle.mtip\n // DOC include end: connect interrupt\n\n // DOC include start: raise interrupt\n // This is a demo. You should call these function according to your core\n // Suppose that the following signal is from the decoder indicating a WFI instruction is received.\n val wfi_o = Wire(Bool())\n outer.reportWFI(Some(wfi_o))\n // Suppose that the following signal indicate an unreconverable hardware error.\n val halt_o = Wire(Bool())\n outer.reportHalt(Some(halt_o))\n // Suppose that our core never stall for a long time / stop retiring. Use None to indicate that this interrupt never fires.\n outer.reportCease(None)\n // DOC include end: raise interrupt\n\n // DOC include start: AXI4 connect\n outer.memAXI4Node.out foreach { case (out, edgeOut) =>\n // Connect your module IO port to \"out\"\n // The type of \"out\" here is AXI4Bundle, which is defined in generators/rocket-chip/src/main/scala/amba/axi4/Bundles.scala\n // Please refer to this file for the definition of the ports.\n // If you are using APB, check APBBundle in generators/rocket-chip/src/main/scala/amba/apb/Bundles.scala\n // If you are using AHB, check AHBSlaveBundle or AHBMasterBundle in generators/rocket-chip/src/main/scala/amba/ahb/Bundles.scala\n // (choose one depends on the type of AHB node you create)\n // If you are using AXIS, check AXISBundle and AXISBundleBits in generators/rocket-chip/src/main/scala/amba/axis/Bundles.scala\n }\n // DOC include end: AXI4 connect\n\n}\n\n// DOC include start: Config fragment\nclass WithNMyCores(n: Int = 1) extends Config((site, here, up) => {\n case TilesLocated(InSubsystem) => {\n // Calculate the next available hart ID (since hart ID cannot be duplicated)\n val prev = up(TilesLocated(InSubsystem), site)\n val idOffset = up(NumTiles)\n // Create TileAttachParams for every core to be instantiated\n (0 until n).map { i =>\n MyTileAttachParams(\n tileParams = MyTileParams(tileId = i + idOffset),\n crossingParams = RocketCrossingParams()\n )\n } ++ prev\n }\n // Configurate # of bytes in one memory / IO transaction. For RV64, one load/store instruction can transfer 8 bytes at most.\n case SystemBusKey => up(SystemBusKey, site).copy(beatBytes = 8)\n case NumTiles => up(NumTiles) + n\n})\n// DOC include end: Config fragment\n", "groundtruth": " override def parent = Some(ResourceAnchors.cpus)\n", "crossfile_context": ""}
{"task_id": "chipyard", "path": "chipyard/generators/chipyard/src/main/scala/example/dsptools/DspBlocks.scala", "left_context": "package chipyard.example\n\nimport chisel3._\nimport chisel3.util._\nimport dspblocks._\nimport dsptools.numbers._\nimport freechips.rocketchip.amba.axi4stream._\nimport org.chipsalliance.cde.config.Parameters\nimport freechips.rocketchip.diplomacy._\nimport freechips.rocketchip.regmapper._\nimport freechips.rocketchip.tilelink._\nimport freechips.rocketchip.subsystem._\n\n/**\n * The memory interface writes entries into the queue.\n * They stream out the streaming interface\n * @param depth number of entries in the queue\n * @param streamParameters parameters for the stream node\n * @param p\n */\nabstract class WriteQueue[D, U, E, O, B <: Data]\n(\n val depth: Int,\n val streamParameters: AXI4StreamMasterParameters = AXI4StreamMasterParameters()\n)(implicit p: Parameters) extends DspBlock[D, U, E, O, B] with HasCSR {\n // stream node, output only\n val streamNode = AXI4StreamMasterNode(streamParameters)\n\n lazy val module = new LazyModuleImp(this) {\n require(streamNode.out.length == 1)\n\n // get the output bundle associated with the AXI4Stream node\n val out = streamNode.out.head._1\n // width (in bits) of the output interface\n val width = out.params.n * 8\n // instantiate a queue\n val queue = Module(new Queue(UInt(out.params.dataBits.W), depth))\n // connect queue output to streaming output\n out.valid := queue.io.deq.valid\n out.bits.data := queue.io.deq.bits\n // don't use last\n out.bits.last := false.B\n queue.io.deq.ready := out.ready\n\n regmap(\n // each write adds an entry to the queue\n 0x0 -> Seq(RegField.w(width, queue.io.enq)),\n // read the number of entries in the queue\n (width+7)/8 -> Seq(RegField.r(width, queue.io.count)),\n )\n }\n}\n\n/**\n * TLDspBlock specialization of WriteQueue\n * @param depth number of entries in the queue\n * @param csrAddress address range for peripheral\n * @param beatBytes beatBytes of TL interface\n * @param p\n */\nclass TLWriteQueue (depth: Int, csrAddress: AddressSet, beatBytes: Int)\n(implicit p: Parameters) extends WriteQueue[\n TLClientPortParameters, TLManagerPortParameters, TLEdgeOut, TLEdgeIn, TLBundle\n](depth) with TLHasCSR {\n val devname = \"tlQueueIn\"\n val devcompat = Seq(\"ucb-art\", \"dsptools\")\n val device = new SimpleDevice(devname, devcompat) {\n override def describe(resources: ResourceBindings): Description = {\n val Description(name, mapping) = super.describe(resources)\n Description(name, mapping)\n }\n }\n // make diplomatic TL node for regmap\n override val mem = Some(TLRegisterNode(address = Seq(csrAddress), device = device, beatBytes = beatBytes))\n}\n\nobject TLWriteQueue {\n def apply(\n depth: Int = 8,\n csrAddress: AddressSet = AddressSet(0x2000, 0xff),\n beatBytes: Int = 8,\n )(implicit p: Parameters) = {\n val writeQueue = LazyModule(new TLWriteQueue(depth = depth, csrAddress = csrAddress, beatBytes = beatBytes))\n writeQueue\n }\n}\n\n/**\n * The streaming interface adds elements into the queue.\n * The memory interface can read elements out of the queue.\n * @param depth number of entries in the queue\n * @param streamParameters parameters for the stream node\n * @param p\n */\nabstract class ReadQueue[D, U, E, O, B <: Data]\n(\n val depth: Int,\n val streamParameters: AXI4StreamSlaveParameters = AXI4StreamSlaveParameters()\n)(implicit p: Parameters) extends DspBlock[D, U, E, O, B] with HasCSR {\n val streamNode = AXI4StreamSlaveNode(streamParameters)\n\n lazy val module = new LazyModuleImp(this) {\n require(streamNode.in.length == 1)\n\n // get the input associated with the stream node\n val in = streamNode.in.head._1\n // make a Decoupled[UInt] that RegReadFn can do something with\n val out = Wire(Decoupled(UInt()))\n // get width of streaming input interface\n val width = in.params.n * 8\n // instantiate a queue\n val queue = Module(new Queue(UInt(in.params.dataBits.W), depth))\n // connect input to the streaming interface\n queue.io.enq.valid := in.valid\n queue.io.enq.bits := in.bits.data\n in.ready := queue.io.enq.ready\n // connect output to wire\n out.valid := queue.io.deq.valid\n out.bits := queue.io.deq.bits\n queue.io.deq.ready := out.ready\n\n regmap(\n // map the output of the queue\n 0x0 -> Seq(RegField.r(width, RegReadFn(out))),\n // read the number of elements in the queue\n (width+7)/8 -> Seq(RegField.r(width, queue.io.count)),\n )\n }\n}\n\n/**\n * TLDspBlock specialization of ReadQueue\n * @param depth number of entries in the queue\n * @param csrAddress address range\n * @param beatBytes beatBytes of TL interface\n * @param p\n */\nclass TLReadQueue( depth: Int, csrAddress: AddressSet, beatBytes: Int)\n(implicit p: Parameters) extends ReadQueue[\n TLClientPortParameters, TLManagerPortParameters, TLEdgeOut, TLEdgeIn, TLBundle\n](depth) with TLHasCSR {\n val devname = \"tlQueueOut\"\n val devcompat = Seq(\"ucb-art\", \"dsptools\")\n val device = new SimpleDevice(devname, devcompat) {\n", "right_context": "}\n\nobject TLReadQueue {\n def apply(\n depth: Int = 8,\n csrAddress: AddressSet = AddressSet(0x2100, 0xff),\n beatBytes: Int = 8)(implicit p: Parameters) = {\n val readQueue = LazyModule(new TLReadQueue(depth = depth, csrAddress = csrAddress, beatBytes = beatBytes))\n readQueue\n }\n}\n", "groundtruth": " override def describe(resources: ResourceBindings): Description = {\n val Description(name, mapping) = super.describe(resources)\n Description(name, mapping)\n }\n", "crossfile_context": ""}
{"task_id": "chipyard", "path": "chipyard/generators/chipyard/src/main/scala/harness/HasHarnessInstantiators.scala", "left_context": "package chipyard.harness\n\nimport chisel3._\n\nimport scala.collection.mutable.{ArrayBuffer, LinkedHashMap}\nimport freechips.rocketchip.diplomacy.{LazyModule}\nimport org.chipsalliance.cde.config.{Field, Parameters, Config}\nimport freechips.rocketchip.util.{ResetCatchAndSync, DontTouch}\nimport freechips.rocketchip.prci.{ClockBundle, ClockBundleParameters, ClockSinkParameters, ClockParameters}\nimport chipyard.stage.phases.TargetDirKey\n\nimport chipyard.harness.{ApplyHarnessBinders, HarnessBinders}\nimport chipyard.iobinders.HasChipyardPorts\nimport chipyard.clocking.{SimplePllConfiguration, ClockDividerN}\nimport chipyard.{ChipTop}\n\n// -------------------------------\n// Chipyard Test Harness\n// -------------------------------\n\ncase object MultiChipNChips extends Field[Option[Int]](None) // None means ignore MultiChipParams\ncase class MultiChipParameters(chipId: Int) extends Field[Parameters]\ncase object BuildTop extends Field[Parameters => LazyModule]((p: Parameters) => new ChipTop()(p))\ncase object HarnessClockInstantiatorKey extends Field[() => HarnessClockInstantiator]()\n", "right_context": "case object MultiChipIdx extends Field[Int](0)\ncase object DontTouchChipTopPorts extends Field[Boolean](true)\n\nclass WithMultiChip(id: Int, p: Parameters) extends Config((site, here, up) => {\n case MultiChipParameters(`id`) => p\n case MultiChipNChips => Some(up(MultiChipNChips).getOrElse(0) max (id + 1))\n})\n\nclass WithHomogeneousMultiChip(n: Int, p: Parameters, idStart: Int = 0) extends Config((site, here, up) => {\n case MultiChipParameters(id) => if (id >= idStart && id < idStart + n) p else up(MultiChipParameters(id))\n case MultiChipNChips => Some(up(MultiChipNChips).getOrElse(0) max (idStart + n))\n})\n\nclass WithHarnessBinderClockFreqMHz(freqMHz: Double) extends Config((site, here, up) => {\n case HarnessBinderClockFrequencyKey => freqMHz\n})\n\nclass WithDontTouchChipTopPorts(b: Boolean = true) extends Config((site, here, up) => {\n case DontTouchChipTopPorts => b\n})\n\n// A TestHarness mixing this in will\n// - use the HarnessClockInstantiator clock provide\ntrait HasHarnessInstantiators {\n implicit val p: Parameters\n // clock/reset of the chiptop reference clock (can be different than the implicit harness clock/reset)\n private val harnessBinderClockFreq: Double = p(HarnessBinderClockFrequencyKey)\n def getHarnessBinderClockFreqHz: Double = harnessBinderClockFreq * 1000000\n def getHarnessBinderClockFreqMHz: Double = harnessBinderClockFreq\n\n // buildtopClock takes the refClockFreq, and drives the harnessbinders\n val harnessBinderClock = Wire(Clock())\n val harnessBinderReset = Wire(Reset())\n\n // classes which inherit this trait should provide the below definitions\n def referenceClockFreqMHz: Double\n def referenceClock: Clock\n def referenceReset: Reset\n def success: Bool\n\n // This can be accessed to get new clocks from the harness\n val harnessClockInstantiator = p(HarnessClockInstantiatorKey)()\n\n val supportsMultiChip: Boolean = false\n\n val chipParameters = p(MultiChipNChips) match {\n case Some(n) => (0 until n).map { i => p(MultiChipParameters(i)).alterPartial {\n case TargetDirKey => p(TargetDirKey) // hacky fix\n case MultiChipIdx => i\n }}\n case None => Seq(p)\n }\n\n // This shold be called last to build the ChipTops\n def instantiateChipTops(): Seq[LazyModule] = {\n require(p(MultiChipNChips).isEmpty || supportsMultiChip,\n s\"Selected Harness does not support multi-chip\")\n\n val lazyDuts = chipParameters.zipWithIndex.map { case (q,i) =>\n LazyModule(q(BuildTop)(q)).suggestName(s\"chiptop$i\")\n }\n val duts = lazyDuts.map(l => Module(l.module))\n\n withClockAndReset (harnessBinderClock, harnessBinderReset) {\n lazyDuts.zipWithIndex.foreach {\n case (d: HasChipyardPorts, i: Int) => {\n ApplyHarnessBinders(this, d.ports, i)(chipParameters(i))\n }\n case _ =>\n }\n ApplyMultiHarnessBinders(this, lazyDuts)\n }\n\n if (p(DontTouchChipTopPorts)) {\n duts.map(_ match {\n case d: DontTouch => d.dontTouchPorts()\n case _ =>\n })\n }\n\n val harnessBinderClk = harnessClockInstantiator.requestClockMHz(\"harnessbinder_clock\", getHarnessBinderClockFreqMHz)\n println(s\"Harness binder clock is $harnessBinderClockFreq\")\n harnessBinderClock := harnessBinderClk\n harnessBinderReset := ResetCatchAndSync(harnessBinderClk, referenceReset.asBool)\n\n harnessClockInstantiator.instantiateHarnessClocks(referenceClock, referenceClockFreqMHz)\n\n lazyDuts\n }\n}\n", "groundtruth": "case object HarnessBinderClockFrequencyKey extends Field[Double](100.0) // MHz\n", "crossfile_context": ""}
{"task_id": "chipyard", "path": "chipyard/generators/chipyard/src/main/scala/unittest/UnitTestSuite.scala", "left_context": "package chipyard.unittest\n\nimport org.chipsalliance.cde.config.Parameters\nimport freechips.rocketchip.util.{ElaborationArtefacts, PlusArgArtefacts}\n\n", "right_context": "", "groundtruth": "class UnitTestSuite(implicit p: Parameters) extends freechips.rocketchip.unittest.UnitTestSuite {\n ElaborationArtefacts.add(\"plusArgs\", PlusArgArtefacts.serialize_cHeader)\n}\n", "crossfile_context": ""}
{"task_id": "chipyard", "path": "chipyard/generators/chipyard/src/test/scala/clocking/SimplePllConfigurationSpec.scala", "left_context": "//See LICENSE for license details.\npackage chipyard.clocking\n\nimport freechips.rocketchip.prci._\n\nclass SimplePllConfigurationSpec extends org.scalatest.flatspec.AnyFlatSpec {\n\n def genConf(freqMHz: Iterable[Double]): SimplePllConfiguration = new SimplePllConfiguration(\n \"testPLL\",\n freqMHz.map({ f => ClockSinkParameters(\n name = Some(s\"desiredFreq_$f\"),\n take = Some(ClockParameters(f))) }).toSeq,\n maximumAllowableFreqMHz = 16000.0)\n\n def trySuccessfulConf(requestedFreqs: Seq[Double], expected: Double): Unit = {\n val freqStr = requestedFreqs.mkString(\", \")\n", "right_context": " val conf = genConf(requestedFreqs)\n conf.emitSummaries\n assert(expected == conf.referenceFreqMHz)\n }\n }\n\n trySuccessfulConf(Seq(3200.0, 1600.0, 1000.0, 100.0), 16000.0)\n trySuccessfulConf(Seq(3200.0, 1600.0), 3200.0)\n trySuccessfulConf(Seq(3200.0, 1066.7), 3200.0)\n trySuccessfulConf(Seq(100, 50, 6.67), 100)\n trySuccessfulConf(Seq(1, 2, 3, 5, 7, 11, 13).map(_ * 10.0), 1560.0)\n}\n", "groundtruth": " it should s\"select a reference of ${expected} MHz for ${freqStr} MHz\" in {\n", "crossfile_context": ""}
{"task_id": "chipyard", "path": "chipyard/generators/firechip/bridgeinterfaces/src/main/scala/UART.scala", "left_context": "// See LICENSE for license details.\n\npackage firechip.bridgeinterfaces\n\nimport chisel3._\n\n// Note: This file is heavily commented as it serves as a bridge walkthrough\n// example in the FireSim docs\n\n// Note: All code in this file must be isolated from target-side generators/classes/etc\n// since this is also injected into the midas compiler.\n\n// DOC include start: UART Bridge Target-Side Interface\nclass UARTPortIO extends Bundle {\n val txd = Output(Bool())\n val rxd = Input(Bool())\n}\n\nclass UARTBridgeTargetIO extends Bundle {\n val clock = Input(Clock())\n val uart = Flipped(new UARTPortIO)\n // Note this reset is optional and used only to reset target-state modeled\n // in the bridge. This reset is just like any other Bool included in your target\n // interface, simply appears as another Bool in the input token.\n val reset = Input(Bool())\n}\n// DOC include end: UART Bridge Target-Side Interface\n\n// DOC include start: UART Bridge Constructor Arg\n// Out bridge module constructor argument. This captures all of the extra\n// metadata we'd like to pass to the host-side BridgeModule. Note, we need to\n// use a single case class to do so, even if it is simply to wrap a primitive\n// type, as is the case for the div Int.\n", "right_context": "// DOC include end: UART Bridge Constructor Arg\n", "groundtruth": "case class UARTKey(div: Int)\n", "crossfile_context": ""}
{"task_id": "chipyard", "path": "chipyard/generators/firechip/bridgestubs/src/main/scala/uart/UARTBridge.scala", "left_context": "// See LICENSE for license details\n\npackage firechip.bridgestubs\n\nimport chisel3._\nimport chisel3.util._\n\nimport org.chipsalliance.cde.config.Parameters\n\nimport firesim.lib.bridgeutils._\n\nimport firechip.bridgeinterfaces._\n\n// Note: This file is heavily commented as it serves as a bridge walkthrough\n// example in the FireSim docs\n\n// DOC include start: UART Bridge Target-Side Module\nclass UARTBridge(initBaudRate: BigInt, freqMHz: Int)(implicit p: Parameters) extends BlackBox\n with Bridge[HostPortIO[UARTBridgeTargetIO]] {\n // Module portion corresponding to this bridge\n val moduleName = \"firechip.goldengateimplementations.UARTBridgeModule\"\n // Since we're extending BlackBox this is the port will connect to in our target's RTL\n val io = IO(new UARTBridgeTargetIO)\n // Implement the bridgeIO member of Bridge using HostPort. This indicates that\n // we want to divide io, into a bidirectional token stream with the input\n // token corresponding to all of the inputs of this BlackBox, and the output token consisting of\n // all of the outputs from the BlackBox\n val bridgeIO = HostPort(io)\n\n // Do some intermediate work to compute our host-side BridgeModule's constructor argument\n val div = (BigInt(freqMHz) * 1000000 / initBaudRate).toInt\n\n // And then implement the constructorArg member\n val constructorArg = Some(UARTKey(div))\n\n // Finally, and this is critical, emit the Bridge Annotations -- without\n // this, this BlackBox would appear like any other BlackBox to Golden Gate\n generateAnnotations()\n}\n// DOC include end: UART Bridge Target-Side Module\n\n// DOC include start: UART Bridge Companion Object\nobject UARTBridge {\n def apply(clock: Clock, uart: sifive.blocks.devices.uart.UARTPortIO, reset: Bool, freqMHz: Int)(implicit p: Parameters): UARTBridge = {\n val ep = Module(new UARTBridge(uart.c.initBaudRate, freqMHz))\n ep.io.uart.txd := uart.txd\n uart.rxd := ep.io.uart.rxd\n ep.io.clock := clock\n ep.io.reset := reset\n", "right_context": "// DOC include end: UART Bridge Companion Object\n", "groundtruth": " ep\n }\n", "crossfile_context": ""}
{"task_id": "rocket-chip", "path": "rocket-chip/src/main/scala/amba/axi4/Xbar.scala", "left_context": "// See LICENSE.SiFive for license details.\n\npackage freechips.rocketchip.amba.axi4\n\nimport chisel3._\nimport chisel3.util.{Cat, Queue, UIntToOH, log2Ceil, OHToUInt, Mux1H, IrrevocableIO}\n\nimport org.chipsalliance.cde.config.Parameters\n\nimport org.chipsalliance.diplomacy.lazymodule.{LazyModule, LazyModuleImp}\n\nimport freechips.rocketchip.diplomacy.{AddressDecoder, AddressSet, BufferParams}\nimport freechips.rocketchip.tilelink.{TLArbiter, TLXbar, TLFilter, TLFuzzer, TLToAXI4, TLRAMModel}\nimport freechips.rocketchip.unittest.{UnitTest, UnitTestModule}\nimport freechips.rocketchip.util.BundleField\n\n/**\n * AXI4 Crossbar. It connects multiple AXI4 masters to slaves.\n *\n * @param arbitrationPolicy arbitration policy\n * @param maxFlightPerId maximum inflight transactions per id\n * @param awQueueDepth queue depth for AW channel\n */\nclass AXI4Xbar(\n arbitrationPolicy: TLArbiter.Policy = TLArbiter.roundRobin,\n maxFlightPerId: Int = 7,\n awQueueDepth: Int = 2)(implicit p: Parameters) extends LazyModule\n{\n require (maxFlightPerId >= 1)\n require (awQueueDepth >= 1)\n\n val node = new AXI4NexusNode(\n masterFn = { seq =>\n seq(0).copy(\n echoFields = BundleField.union(seq.flatMap(_.echoFields)),\n requestFields = BundleField.union(seq.flatMap(_.requestFields)),\n responseKeys = seq.flatMap(_.responseKeys).distinct,\n masters = (AXI4Xbar.mapInputIds(seq) zip seq) flatMap { case (range, port) =>\n port.masters map { master => master.copy(id = master.id.shift(range.start)) }\n }\n )\n },\n slaveFn = { seq =>\n seq(0).copy(\n responseFields = BundleField.union(seq.flatMap(_.responseFields)),\n requestKeys = seq.flatMap(_.requestKeys).distinct,\n minLatency = seq.map(_.minLatency).min,\n slaves = seq.flatMap { port =>\n require (port.beatBytes == seq(0).beatBytes,\n s\"Xbar data widths don't match: ${port.slaves.map(_.name)} has ${port.beatBytes}B vs ${seq(0).slaves.map(_.name)} has ${seq(0).beatBytes}B\")\n port.slaves\n }\n )\n }\n ){\n override def circuitIdentity = outputs.size == 1 && inputs.size == 1\n }\n\n lazy val module = new Impl\n class Impl extends LazyModuleImp(this) {\n val (io_in, edgesIn) = node.in.unzip\n val (io_out, edgesOut) = node.out.unzip\n\n // Grab the port ID mapping\n val inputIdRanges = AXI4Xbar.mapInputIds(edgesIn.map(_.master))\n\n // Find a good mask for address decoding\n val port_addrs = edgesOut.map(_.slave.slaves.map(_.address).flatten)\n val routingMask = AddressDecoder(port_addrs)\n val route_addrs = port_addrs.map(seq => AddressSet.unify(seq.map(_.widen(~routingMask)).distinct))\n val outputPorts = route_addrs.map(seq => (addr: UInt) => seq.map(_.contains(addr)).reduce(_ || _))\n\n // To route W we need to record where the AWs went\n val awIn = Seq.fill(io_in .size) { Module(new Queue(UInt(io_out.size.W), awQueueDepth, flow = true)) }\n val awOut = Seq.fill(io_out.size) { Module(new Queue(UInt(io_in .size.W), awQueueDepth, flow = true)) }\n\n val requestARIO = io_in.map { i => VecInit(outputPorts.map { o => o(i.ar.bits.addr) }) }\n val requestAWIO = io_in.map { i => VecInit(outputPorts.map { o => o(i.aw.bits.addr) }) }\n val requestROI = io_out.map { o => inputIdRanges.map { i => i.contains(o.r.bits.id) } }\n val requestBOI = io_out.map { o => inputIdRanges.map { i => i.contains(o.b.bits.id) } }\n\n // W follows the path dictated by the AW Q\n for (i <- 0 until io_in.size) { awIn(i).io.enq.bits := requestAWIO(i).asUInt }\n val requestWIO = awIn.map { q => if (io_out.size > 1) q.io.deq.bits.asBools else Seq(true.B) }\n\n // We need an intermediate size of bundle with the widest possible identifiers\n val wide_bundle = AXI4BundleParameters.union(io_in.map(_.params) ++ io_out.map(_.params))\n\n // Transform input bundles\n val in = Wire(Vec(io_in.size, new AXI4Bundle(wide_bundle)))\n for (i <- 0 until in.size) {\n in(i).aw.bits.user := DontCare\n in(i).aw.bits.echo := DontCare\n in(i).ar.bits.user := DontCare\n in(i).ar.bits.echo := DontCare\n in(i).w.bits.user := DontCare\n in(i).squeezeAll.waiveAll :<>= io_in(i).squeezeAll.waiveAll\n\n // Handle size = 1 gracefully (Chisel3 empty range is broken)\n def trim(id: UInt, size: Int) = if (size <= 1) 0.U else id(log2Ceil(size)-1, 0)\n // Manipulate the AXI IDs to differentiate masters\n val r = inputIdRanges(i)\n in(i).aw.bits.id := io_in(i).aw.bits.id | (r.start).U\n in(i).ar.bits.id := io_in(i).ar.bits.id | (r.start).U\n io_in(i).r.bits.id := trim(in(i).r.bits.id, r.size)\n io_in(i).b.bits.id := trim(in(i).b.bits.id, r.size)\n\n if (io_out.size > 1) {\n // Block A[RW] if we switch ports, to ensure responses stay ordered (also: beware the dining philosophers)\n val endId = edgesIn(i).master.endId\n val arFIFOMap = WireDefault(VecInit.fill(endId) { true.B })\n val awFIFOMap = WireDefault(VecInit.fill(endId) { true.B })\n val arSel = UIntToOH(io_in(i).ar.bits.id, endId)\n val awSel = UIntToOH(io_in(i).aw.bits.id, endId)\n val rSel = UIntToOH(io_in(i).r .bits.id, endId)\n val bSel = UIntToOH(io_in(i).b .bits.id, endId)\n val arTag = OHToUInt(requestARIO(i).asUInt, io_out.size)\n val awTag = OHToUInt(requestAWIO(i).asUInt, io_out.size)\n\n for (master <- edgesIn(i).master.masters) {\n def idTracker(port: UInt, req_fire: Bool, resp_fire: Bool) = {\n if (master.maxFlight == Some(0)) {\n true.B\n } else {\n val legalFlight = master.maxFlight.getOrElse(maxFlightPerId+1)\n val flight = legalFlight min maxFlightPerId\n val canOverflow = legalFlight > flight\n val count = RegInit(0.U(log2Ceil(flight+1).W))\n val last = Reg(UInt(log2Ceil(io_out.size).W))\n count := count + req_fire.asUInt - resp_fire.asUInt\n assert (!resp_fire || count =/= 0.U)\n assert (!req_fire || count =/= flight.U)\n when (req_fire) { last := port }\n // No need to track where it went if we cap it at 1 request\n val portMatch = if (flight == 1) { true.B } else { last === port }\n (count === 0.U || portMatch) && ((!canOverflow).B || count =/= flight.U)\n }\n }\n\n for (id <- master.id.start until master.id.end) {\n arFIFOMap(id) := idTracker(\n arTag,\n arSel(id) && io_in(i).ar.fire,\n rSel(id) && io_in(i).r.fire && io_in(i).r.bits.last)\n awFIFOMap(id) := idTracker(\n awTag,\n awSel(id) && io_in(i).aw.fire,\n bSel(id) && io_in(i).b.fire)\n }\n }\n\n val allowAR = arFIFOMap(io_in(i).ar.bits.id)\n in(i).ar.valid := io_in(i).ar.valid && allowAR\n io_in(i).ar.ready := in(i).ar.ready && allowAR\n\n // Keep in mind that slaves may do this: awready := wvalid, wready := awvalid\n // To not cause a loop, we cannot have: wvalid := awready\n\n // Block AW if we cannot record the W destination\n val allowAW = awFIFOMap(io_in(i).aw.bits.id)\n val latched = RegInit(false.B) // cut awIn(i).enq.valid from awready\n in(i).aw.valid := io_in(i).aw.valid && (latched || awIn(i).io.enq.ready) && allowAW\n io_in(i).aw.ready := in(i).aw.ready && (latched || awIn(i).io.enq.ready) && allowAW\n awIn(i).io.enq.valid := io_in(i).aw.valid && !latched\n when (awIn(i).io.enq.fire) { latched := true.B }\n when (in(i).aw.fire) { latched := false.B }\n\n // Block W if we do not have an AW destination\n in(i).w.valid := io_in(i).w.valid && awIn(i).io.deq.valid // depends on awvalid (but not awready)\n io_in(i).w.ready := in(i).w.ready && awIn(i).io.deq.valid\n awIn(i).io.deq.ready := io_in(i).w.valid && io_in(i).w.bits.last && in(i).w.ready\n } else {\n awIn(i).io := DontCare // aw in queue is not used when outsize == 1\n }\n }\n\n // Transform output bundles\n val out = Wire(Vec(io_out.size, new AXI4Bundle(wide_bundle)))\n for (i <- 0 until out.size) {\n out(i).b.bits.user := DontCare\n out(i).r.bits.user := DontCare\n io_out(i).squeezeAll.waiveAll :<>= out(i).squeezeAll.waiveAll\n\n if (io_in.size > 1) {\n // Block AW if we cannot record the W source\n val latched = RegInit(false.B) // cut awOut(i).enq.valid from awready\n io_out(i).aw.valid := out(i).aw.valid && (latched || awOut(i).io.enq.ready)\n out(i).aw.ready := io_out(i).aw.ready && (latched || awOut(i).io.enq.ready)\n awOut(i).io.enq.valid := out(i).aw.valid && !latched\n when (awOut(i).io.enq.fire) { latched := true.B }\n when (out(i).aw.fire) { latched := false.B }\n\n // Block W if we do not have an AW source\n io_out(i).w.valid := out(i).w.valid && awOut(i).io.deq.valid // depends on awvalid (but not awready)\n out(i).w.ready := io_out(i).w.ready && awOut(i).io.deq.valid\n awOut(i).io.deq.ready := out(i).w.valid && out(i).w.bits.last && io_out(i).w.ready\n } else {\n awOut(i).io := DontCare // aw out queue is not used when io_in.size == 1\n }\n }\n\n // Fanout the input sources to the output sinks\n def transpose[T](x: Seq[Seq[T]]) = Seq.tabulate(x(0).size) { i => Seq.tabulate(x.size) { j => x(j)(i) } }\n val portsAROI = transpose((in zip requestARIO) map { case (i, r) => AXI4Xbar.fanout(i.ar, r) })\n val portsAWOI = transpose((in zip requestAWIO) map { case (i, r) => AXI4Xbar.fanout(i.aw, r) })\n val portsWOI = transpose((in zip requestWIO) map { case (i, r) => AXI4Xbar.fanout(i.w, r) })\n val portsRIO = transpose((out zip requestROI) map { case (o, r) => AXI4Xbar.fanout(o.r, r) })\n val portsBIO = transpose((out zip requestBOI) map { case (o, r) => AXI4Xbar.fanout(o.b, r) })\n\n // Arbitrate amongst the sources\n for (o <- 0 until out.size) {\n awOut(o).io.enq.bits := // Record who won AW arbitration to select W\n AXI4Arbiter.returnWinner(arbitrationPolicy)(out(o).aw, portsAWOI(o):_*).asUInt\n AXI4Arbiter(arbitrationPolicy)(out(o).ar, portsAROI(o):_*)\n // W arbitration is informed by the Q, not policy\n out(o).w.valid := Mux1H(awOut(o).io.deq.bits, portsWOI(o).map(_.valid))\n out(o).w.bits :<= Mux1H(awOut(o).io.deq.bits, portsWOI(o).map(_.bits))\n portsWOI(o).zipWithIndex.map { case (p, i) =>\n if (in.size > 1) {\n p.ready := out(o).w.ready && awOut(o).io.deq.bits(i)\n } else {\n p.ready := out(o).w.ready\n }\n }\n }\n\n for (i <- 0 until in.size) {\n AXI4Arbiter(arbitrationPolicy)(in(i).r, portsRIO(i):_*)\n AXI4Arbiter(arbitrationPolicy)(in(i).b, portsBIO(i):_*)\n }\n }\n}\n\nobject AXI4Xbar\n{\n def apply(\n arbitrationPolicy: TLArbiter.Policy = TLArbiter.roundRobin,\n maxFlightPerId: Int = 7,\n awQueueDepth: Int = 2)(implicit p: Parameters) =\n {\n val axi4xbar = LazyModule(new AXI4Xbar(arbitrationPolicy, maxFlightPerId, awQueueDepth))\n axi4xbar.node\n }\n\n def mapInputIds(ports: Seq[AXI4MasterPortParameters]) = TLXbar.assignRanges(ports.map(_.endId))\n\n // Replicate an input port to each output port\n def fanout[T <: AXI4BundleBase](input: IrrevocableIO[T], select: Seq[Bool]) = {\n val filtered = Wire(Vec(select.size, chiselTypeOf(input)))\n for (i <- 0 until select.size) {\n filtered(i).bits :<= input.bits\n filtered(i).valid := input.valid && select(i)\n }\n input.ready := Mux1H(select, filtered.map(_.ready))\n filtered\n }\n}\n\nobject AXI4Arbiter\n{\n def apply[T <: Data](policy: TLArbiter.Policy)(sink: IrrevocableIO[T], sources: IrrevocableIO[T]*): Unit = {\n if (sources.isEmpty) {\n sink.valid := false.B\n } else {\n returnWinner(policy)(sink, sources:_*)\n }\n }\n def returnWinner[T <: Data](policy: TLArbiter.Policy)(sink: IrrevocableIO[T], sources: IrrevocableIO[T]*) = {\n require (!sources.isEmpty)\n\n // The arbiter is irrevocable; when !idle, repeat last request\n val idle = RegInit(true.B)\n\n // Who wants access to the sink?\n val valids = sources.map(_.valid)\n val anyValid = valids.reduce(_ || _)\n // Arbitrate amongst the requests\n val readys = VecInit(policy(valids.size, Cat(valids.reverse), idle).asBools)\n // Which request wins arbitration?\n val winner = VecInit((readys zip valids) map { case (r,v) => r&&v })\n\n // Confirm the policy works properly\n require (readys.size == valids.size)\n // Never two winners\n val prefixOR = winner.scanLeft(false.B)(_||_).init\n", "right_context": " // If there was any request, there is a winner\n assert (!anyValid || winner.reduce(_||_))\n\n // The one-hot source granted access in the previous cycle\n val state = RegInit(VecInit.fill(sources.size)(false.B))\n val muxState = Mux(idle, winner, state)\n state := muxState\n\n // Determine when we go idle\n when (anyValid) { idle := false.B }\n when (sink.fire) { idle := true.B }\n\n if (sources.size > 1) {\n val allowed = Mux(idle, readys, state)\n (sources zip allowed) foreach { case (s, r) =>\n s.ready := sink.ready && r\n }\n } else {\n sources(0).ready := sink.ready\n }\n\n sink.valid := Mux(idle, anyValid, Mux1H(state, valids))\n sink.bits :<= Mux1H(muxState, sources.map(_.bits))\n muxState\n }\n}\n\nclass AXI4XbarFuzzTest(name: String, txns: Int, nMasters: Int, nSlaves: Int)(implicit p: Parameters) extends LazyModule\n{\n val xbar = AXI4Xbar()\n val slaveSize = 0x1000\n val masterBandSize = slaveSize >> log2Ceil(nMasters)\n def filter(i: Int) = TLFilter.mSelectIntersect(AddressSet(i * masterBandSize, ~BigInt(slaveSize - masterBandSize)))\n\n val slaves = Seq.tabulate(nSlaves) { i => LazyModule(new AXI4RAM(AddressSet(slaveSize * i, slaveSize-1))) }\n slaves.foreach { s => (s.node\n := AXI4Fragmenter()\n := AXI4Buffer(BufferParams.flow)\n := AXI4Buffer(BufferParams.flow)\n := AXI4Delayer(0.25)\n := xbar) }\n\n val masters = Seq.fill(nMasters) { LazyModule(new TLFuzzer(txns, 4, nOrdered = Some(1))) }\n masters.zipWithIndex.foreach { case (m, i) => (xbar\n := AXI4Delayer(0.25)\n := AXI4Deinterleaver(4096)\n := TLToAXI4()\n := TLFilter(filter(i))\n := TLRAMModel(s\"${name} Master $i\")\n := m.node) }\n\n lazy val module = new Impl\n class Impl extends LazyModuleImp(this) with UnitTestModule {\n io.finished := masters.map(_.module.io.finished).reduce(_ || _)\n }\n}\n\nclass AXI4XbarTest(txns: Int = 5000, timeout: Int = 500000)(implicit p: Parameters) extends UnitTest(timeout) {\n val dut21 = Module(LazyModule(new AXI4XbarFuzzTest(\"Xbar DUT21\", txns, 2, 1)).module)\n val dut12 = Module(LazyModule(new AXI4XbarFuzzTest(\"Xbar DUT12\", txns, 1, 2)).module)\n val dut22 = Module(LazyModule(new AXI4XbarFuzzTest(\"Xbar DUT22\", txns, 2, 2)).module)\n io.finished := Seq(dut21, dut12, dut22).map(_.io.finished).reduce(_ || _)\n Seq(dut21, dut12, dut22).foreach(_.io.start := io.start)\n}\n", "groundtruth": " assert((prefixOR zip winner) map { case (p,w) => !p || !w } reduce {_ && _})\n", "crossfile_context": ""}
{"task_id": "rocket-chip", "path": "rocket-chip/src/main/scala/devices/tilelink/MasterMux.scala", "left_context": "// See LICENSE.SiFive for license details.\n\npackage freechips.rocketchip.devices.tilelink\n\nimport chisel3._\n\nimport org.chipsalliance.cde.config._\nimport org.chipsalliance.diplomacy._\nimport org.chipsalliance.diplomacy.lazymodule._\n\nimport freechips.rocketchip.diplomacy.{AddressSet, TransferSizes}\nimport freechips.rocketchip.tilelink.{\n LFSR64, TLBundleA, TLBundleC, TLBundleE, TLClientNode, TLCustomNode, TLFilter, TLFragmenter,\n TLFuzzer, TLMasterParameters, TLMasterPortParameters, TLPermissions, TLRAM, TLRAMModel,\n TLSlaveParameters, TLSlavePortParameters\n}\n\nclass MasterMuxNode(uFn: Seq[TLMasterPortParameters] => TLMasterPortParameters)(implicit valName: ValName) extends TLCustomNode\n{\n def resolveStar(iKnown: Int, oKnown: Int, iStars: Int, oStars: Int): (Int, Int) = {\n require (iStars == 0 && oStars == 0, \"MasterMux node does not support :=* or :*=\")\n require (iKnown == 2, \"MasterMux node expects exactly two inputs\")\n require (oKnown == 1, \"MasterMux node expects exactly one output\")\n (0, 0)\n }\n def mapParamsD(n: Int, p: Seq[TLMasterPortParameters]): Seq[TLMasterPortParameters] = { Seq(uFn(p)) }\n def mapParamsU(n: Int, p: Seq[TLSlavePortParameters]): Seq[TLSlavePortParameters] = { p ++ p }\n}\n\nclass MuteMaster(name: String = \"MuteMaster\", maxProbe: Int = 0)(implicit p: Parameters) extends LazyModule\n{\n val node = TLClientNode(Seq(TLMasterPortParameters.v1(clients = Seq(TLMasterParameters.v1(\n name = name,\n supportsProbe = if (maxProbe > 0) TransferSizes(1, maxProbe) else TransferSizes.none)))))\n\n lazy val module = new Impl\n class Impl extends LazyModuleImp(this) {\n val Seq((out, edgeOut)) = node.out\n out.a.valid := false.B\n out.b.ready := out.c.ready\n out.c.valid := out.b.valid\n out.d.ready := true.B\n out.e.valid := false.B\n\n out.c.bits := edgeOut.ProbeAck(out.b.bits, TLPermissions.NtoN)\n }\n}\n\nclass MasterMux(uFn: Seq[TLMasterPortParameters] => TLMasterPortParameters)(implicit p: Parameters) extends LazyModule\n{\n val node = new MasterMuxNode(uFn)\n\n lazy val module = new Impl\n class Impl extends LazyModuleImp(this) {\n val io = IO(new Bundle {\n val bypass = Input(Bool())\n val pending = Output(Bool())\n })\n\n val Seq((in0, edgeIn0), (in1, edgeIn1)) = node.in\n val Seq((out, edgeOut)) = node.out\n\n // We need to be locked to the given bypass direction until all transactions stop\n val bypass = RegInit(io.bypass) // synchronous reset required\n val (flight, next_flight) = edgeOut.inFlight(out)\n\n io.pending := (flight > 0.U)\n when (next_flight === 0.U) { bypass := io.bypass }\n val stall = (bypass =/= io.bypass) && edgeOut.first(out.a)\n\n in0.a.ready := !stall && out.a.ready && bypass\n in1.a.ready := !stall && out.a.ready && !bypass\n out.a.valid := !stall && Mux(bypass, in0.a.valid, in1.a.valid)\n def castA(x: TLBundleA) = { val ret = Wire(x.cloneType); ret <> x; ret }\n out.a.bits := Mux(bypass, castA(in0.a.bits), castA(in1.a.bits))\n\n out.d.ready := Mux(bypass, in0.d.ready, in1.d.ready)\n in0.d.valid := out.d.valid && bypass\n in1.d.valid := out.d.valid && !bypass\n in0.d.bits := out.d.bits\n in1.d.bits := out.d.bits\n\n if (edgeOut.manager.anySupportAcquireB && edgeOut.client.anySupportProbe) {\n out.b.ready := Mux(bypass, in0.b.ready, in1.b.ready)\n in0.b.valid := out.b.valid && bypass\n in1.b.valid := out.b.valid && !bypass\n in0.b.bits := out.b.bits\n in1.b.bits := out.b.bits\n\n in0.c.ready := out.c.ready && bypass\n in1.c.ready := out.c.ready && !bypass\n out.c.valid := Mux(bypass, in0.c.valid, in1.c.valid)\n", "right_context": " out.c.bits := Mux(bypass, castC(in0.c.bits), castC(in1.c.bits))\n\n in0.e.ready := out.e.ready && bypass\n in1.e.ready := out.e.ready && !bypass\n out.e.valid := Mux(bypass, in0.e.valid, in1.e.valid)\n def castE(x: TLBundleE) = { val ret = Wire(out.e.bits); ret <> x; ret }\n out.e.bits := Mux(bypass, castE(in0.e.bits), castE(in1.e.bits))\n } else {\n in0.b.valid := false.B\n in0.c.ready := true.B\n in0.e.ready := true.B\n\n in1.b.valid := false.B\n in1.c.ready := true.B\n in1.e.ready := true.B\n\n out.b.ready := true.B\n out.c.valid := false.B\n out.e.valid := false.B\n }\n }\n}\n\n// Synthesizable unit tests\nimport freechips.rocketchip.unittest._\n\nclass TLMasterMuxTester(txns: Int)(implicit p: Parameters) extends LazyModule {\n val fuzz1 = LazyModule(new TLFuzzer(txns))\n val fuzz2 = LazyModule(new TLFuzzer(txns))\n val model1 = LazyModule(new TLRAMModel(\"MasterMux1\"))\n val model2 = LazyModule(new TLRAMModel(\"MasterMux2\"))\n val mux = LazyModule(new MasterMux(uFn = _.head))\n val ram = LazyModule(new TLRAM(AddressSet(0, 0x3ff), beatBytes = 4))\n mux.node := TLFilter(TLFilter.mSelectIntersect(AddressSet( 0, ~16))) := model1.node := fuzz1.node\n mux.node := TLFilter(TLFilter.mSelectIntersect(AddressSet(16, ~16))) := model2.node := fuzz2.node\n ram.node := TLFragmenter(4, 16) := mux.node\n // how to test probe + release?\n\n lazy val module = new Impl\n class Impl extends LazyModuleImp(this) with UnitTestModule {\n io.finished := fuzz1.module.io.finished && fuzz2.module.io.finished\n mux.module.io.bypass := LFSR64(true.B)(0)\n }\n}\n\nclass TLMasterMuxTest(txns: Int = 5000, timeout: Int = 500000)(implicit p: Parameters) extends UnitTest(timeout) {\n val dut = Module(LazyModule(new TLMasterMuxTester(txns)).module)\n io <> dut.io\n}\n", "groundtruth": " def castC(x: TLBundleC) = { val ret = Wire(out.c.bits); ret <> x; ret }\n", "crossfile_context": ""}
{"task_id": "rocket-chip", "path": "rocket-chip/src/main/scala/interrupts/BlockDuringReset.scala", "left_context": "// See LICENSE.SiFive for license details.\n\npackage freechips.rocketchip.interrupts\n\nimport org.chipsalliance.cde.config._\nimport org.chipsalliance.diplomacy.lazymodule._\n\nimport freechips.rocketchip.util.BlockDuringReset\n\n/** BlockDuringReset ensures that no interrupt is raised while reset is raised. */\n", "right_context": "{\n val intnode = IntAdapterNode()\n override def shouldBeInlined = true\n lazy val module = new Impl\n class Impl extends LazyModuleImp(this) {\n intnode.in.zip(intnode.out).foreach { case ((in, _), (out, _)) =>\n in.zip(out).foreach { case (i, o) => o := BlockDuringReset(i, stretchResetCycles) }\n }\n }\n}\n\nobject IntBlockDuringReset {\n def apply(stretchResetCycles: Int = 0)(implicit p: Parameters): IntNode = {\n val block_during_reset = LazyModule(new IntBlockDuringReset(stretchResetCycles))\n block_during_reset.intnode\n }\n}\n", "groundtruth": "class IntBlockDuringReset(stretchResetCycles: Int = 0)(implicit p: Parameters) extends LazyModule\n", "crossfile_context": ""}
{"task_id": "rocket-chip", "path": "rocket-chip/src/main/scala/interrupts/Xbar.scala", "left_context": "// See LICENSE.SiFive for license details.\n\npackage freechips.rocketchip.interrupts\n\nimport org.chipsalliance.cde.config._\nimport org.chipsalliance.diplomacy.lazymodule._\n\nclass IntXbar()(implicit p: Parameters) extends LazyModule\n{\n val intnode = new IntNexusNode(\n sinkFn = { _ => IntSinkPortParameters(Seq(IntSinkParameters())) },\n sourceFn = { seq =>\n IntSourcePortParameters((seq zip seq.map(_.num).scanLeft(0)(_+_).init).map {\n case (s, o) => s.sources.map(z => z.copy(range = z.range.offset(o)))\n }.flatten)\n })\n {\n override def circuitIdentity = outputs.size == 1 && inputs.size == 1\n }\n\n lazy val module = new Impl\n class Impl extends LazyRawModuleImp(this) {\n", "right_context": " val cat = intnode.in.map { case (i, e) => i.take(e.source.num) }.flatten\n intnode.out.foreach { case (o, _) => o := cat }\n }\n}\n\nclass IntSyncXbar()(implicit p: Parameters) extends LazyModule\n{\n val intnode = new IntSyncNexusNode(\n sinkFn = { _ => IntSinkPortParameters(Seq(IntSinkParameters())) },\n sourceFn = { seq =>\n IntSourcePortParameters((seq zip seq.map(_.num).scanLeft(0)(_+_).init).map {\n case (s, o) => s.sources.map(z => z.copy(range = z.range.offset(o)))\n }.flatten)\n })\n {\n override def circuitIdentity = outputs.size == 1 && inputs.size == 1\n }\n\n lazy val module = new Impl\n class Impl extends LazyModuleImp(this) {\n override def desiredName = s\"IntSyncXbar_i${intnode.in.size}_o${intnode.out.size}\"\n val cat = intnode.in.map { case (i, e) => i.sync.take(e.source.num) }.flatten\n intnode.out.foreach { case (o, _) => o.sync := cat }\n }\n}\n\nobject IntXbar {\n def apply()(implicit p: Parameters): IntNode = {\n val xbar = LazyModule(new IntXbar)\n xbar.intnode\n }\n}\n\nobject IntSyncXbar {\n def apply()(implicit p: Parameters): IntSyncNode = {\n val xbar = LazyModule(new IntSyncXbar)\n xbar.intnode\n }\n}\n", "groundtruth": " override def desiredName = s\"IntXbar_i${intnode.in.size}_o${intnode.out.size}\"\n", "crossfile_context": ""}
{"task_id": "rocket-chip", "path": "rocket-chip/src/main/scala/prci/ResetWrangler.scala", "left_context": "// See LICENSE for license details.\npackage freechips.rocketchip.prci\n\nimport chisel3._\nimport chisel3.util._\nimport org.chipsalliance.cde.config._\nimport org.chipsalliance.diplomacy.lazymodule._\n\nimport freechips.rocketchip.util.{AsyncResetReg, ResetCatchAndSync}\n\nclass ResetWrangler(debounceNs: Double = 100000)(implicit p: Parameters) extends LazyModule\n{\n val node = ClockAdapterNode()\n\n lazy val module = new Impl\n class Impl extends LazyRawModuleImp(this) {\n val (in, _) = node.in.unzip\n val (out, _) = node.out.unzip\n\n val status = IO(Output(UInt(in.size.W)))\n status := Cat(in.map(_.reset.asBool).reverse)\n val causes = in.map(_.reset).foldLeft(false.B)(_.asBool || _.asBool)\n\n require(node.in.forall(_._2.clock.isDefined), \"Cannot wrangle reset for an unspecified clock frequency\")\n val (slowIn, slowEdge) = node.in.minBy(_._2.clock.get.freqMHz)\n val slowPeriodNs = 1000 / slowEdge.clock.get.freqMHz\n val slowTicks = math.ceil(debounceNs/slowPeriodNs).toInt max 7\n val slowBits = log2Ceil(slowTicks+1)\n\n // debounce\n val increment = Wire(Bool())\n val incremented = Wire(UInt(slowBits.W))\n", "right_context": " val deglitched = AsyncResetReg(increment, slowIn.clock, causes, true, Some(\"deglitch\"))\n\n // catch and sync increment to each domain\n (in zip out) foreach { case (i, o) =>\n o.clock := i.clock\n o.reset := ResetCatchAndSync(o.clock, deglitched)\n }\n }\n}\n", "groundtruth": " val debounced = withClockAndReset(slowIn.clock, causes) {\n AsyncResetReg(incremented, 0, increment, Some(\"debounce\"))\n }\n", "crossfile_context": ""}
{"task_id": "rocket-chip", "path": "rocket-chip/src/main/scala/subsystem/MemoryBus.scala", "left_context": "// See LICENSE.SiFive for license details.\n\npackage freechips.rocketchip.subsystem\n\nimport org.chipsalliance.cde.config._\nimport org.chipsalliance.diplomacy.lazymodule._\n\nimport freechips.rocketchip.devices.tilelink.{BuiltInDevices, HasBuiltInDeviceParams, BuiltInErrorDeviceParams, BuiltInZeroDeviceParams}\nimport freechips.rocketchip.tilelink.{\n ReplicatedRegion, HasTLBusParams, HasRegionReplicatorParams, TLBusWrapper,\n TLBusWrapperInstantiationLike, RegionReplicator, TLXbar, TLInwardNode,\n TLOutwardNode, ProbePicker, TLEdge, TLFIFOFixer\n}\nimport freechips.rocketchip.util.Location\n\n/** Parameterization of the memory-side bus created for each memory channel */\ncase class MemoryBusParams(\n beatBytes: Int,\n blockBytes: Int,\n dtsFrequency: Option[BigInt] = None,\n zeroDevice: Option[BuiltInZeroDeviceParams] = None,\n errorDevice: Option[BuiltInErrorDeviceParams] = None,\n replication: Option[ReplicatedRegion] = None)\n extends HasTLBusParams\n with HasBuiltInDeviceParams\n with HasRegionReplicatorParams\n with TLBusWrapperInstantiationLike\n{\n def instantiate(context: HasTileLinkLocations, loc: Location[TLBusWrapper])(implicit p: Parameters): MemoryBus = {\n val mbus = LazyModule(new MemoryBus(this, loc.name))\n mbus.suggestName(loc.name)\n context.tlBusWrapperLocationMap += (loc -> mbus)\n mbus\n }\n}\n\n/** Wrapper for creating TL nodes from a bus connected to the back of each mem channel */\nclass MemoryBus(params: MemoryBusParams, name: String = \"memory_bus\")(implicit p: Parameters)\n extends TLBusWrapper(params, name)(p)\n{\n private val replicator = params.replication.map(r => LazyModule(new RegionReplicator(r)))\n val prefixNode = replicator.map { r =>\n r.prefix := addressPrefixNexusNode\n addressPrefixNexusNode\n }\n\n private val xbar = LazyModule(new TLXbar(nameSuffix = Some(name))).suggestName(busName + \"_xbar\")\n val inwardNode: TLInwardNode =\n replicator.map(xbar.node :*=* TLFIFOFixer(TLFIFOFixer.all) :*=* _.node)\n .getOrElse(xbar.node :*=* TLFIFOFixer(TLFIFOFixer.all))\n\n val outwardNode: TLOutwardNode = ProbePicker() :*= xbar.node\n", "right_context": "\n val builtInDevices: BuiltInDevices = BuiltInDevices.attach(params, outwardNode)\n}\n", "groundtruth": " def busView: TLEdge = xbar.node.edges.in.head\n", "crossfile_context": ""}
{"task_id": "rocket-chip", "path": "rocket-chip/src/main/scala/system/SimAXIMem.scala", "left_context": "// See LICENSE.SiFive for license details.\n\npackage freechips.rocketchip.system // TODO this should really be in a testharness package\n\nimport chisel3._\n\nimport org.chipsalliance.cde.config._\nimport org.chipsalliance.diplomacy.lazymodule._\n\nimport freechips.rocketchip.amba.AMBACorrupt\nimport freechips.rocketchip.amba.axi4.{AXI4RAM, AXI4MasterNode, AXI4EdgeParameters, AXI4Xbar, AXI4Buffer, AXI4Fragmenter}\nimport freechips.rocketchip.diplomacy.AddressSet\nimport freechips.rocketchip.subsystem.{CanHaveMasterAXI4MMIOPort, CanHaveMasterAXI4MemPort, ExtBus, ExtMem}\n\n/** Memory with AXI port for use in elaboratable test harnesses.\n * \n * Topology: AXIRAM <-< AXI4Buffer <-< AXI4Fragmenter <-< AXI4Xbar <-< AXI4MasterNode\n*/\nclass SimAXIMem(edge: AXI4EdgeParameters, size: BigInt, base: BigInt = 0)(implicit p: Parameters) extends SimpleLazyModule {\n val node = AXI4MasterNode(List(edge.master))\n val srams = AddressSet.misaligned(base, size).map { aSet =>\n LazyModule(new AXI4RAM(\n address = aSet,\n beatBytes = edge.bundle.dataBits/8,\n wcorrupt=edge.slave.requestKeys.contains(AMBACorrupt)))\n }\n val xbar = AXI4Xbar()\n srams.foreach{ s => s.node := AXI4Buffer() := AXI4Fragmenter() := xbar }\n xbar := node\n", "right_context": "}\n\n/**\n * Connect Master AXI4 Mem/MMIO Port to SimAXIMem.\n */\nobject SimAXIMem {\n def connectMMIO(dut: CanHaveMasterAXI4MMIOPort)(implicit p: Parameters): Seq[SimAXIMem] = {\n dut.mmio_axi4.zip(dut.mmioAXI4Node.in).map { case (io, (_, edge)) =>\n // test harness size capped to 4KB (ignoring p(ExtMem).get.master.size)\n val mmio_mem = LazyModule(new SimAXIMem(edge, base = p(ExtBus).get.base, size = 4096))\n Module(mmio_mem.module).suggestName(\"mmio_mem\")\n mmio_mem.io_axi4.head <> io\n mmio_mem\n }.toSeq\n }\n\n def connectMem(dut: CanHaveMasterAXI4MemPort)(implicit p: Parameters): Seq[SimAXIMem] = {\n dut.mem_axi4.zip(dut.memAXI4Node.in).map { case (io, (_, edge)) =>\n val mem = LazyModule(new SimAXIMem(edge, base = p(ExtMem).get.master.base, size = p(ExtMem).get.master.size))\n Module(mem.module).suggestName(\"mem\")\n mem.io_axi4.head <> io\n mem\n }.toSeq\n }\n}\n", "groundtruth": " val io_axi4 = InModuleBody { node.makeIOs() }\n", "crossfile_context": ""}
{"task_id": "rocket-chip", "path": "rocket-chip/src/main/scala/tilelink/Nodes.scala", "left_context": "// See LICENSE.SiFive for license details.\n\npackage freechips.rocketchip.tilelink\n\nimport chisel3._\nimport chisel3.experimental.SourceInfo\n\nimport org.chipsalliance.cde.config._\nimport org.chipsalliance.diplomacy._\nimport org.chipsalliance.diplomacy.nodes._\n\nimport freechips.rocketchip.util.{AsyncQueueParams,RationalDirection}\n\ncase object TLMonitorBuilder extends Field[TLMonitorArgs => TLMonitorBase](args => new TLMonitor(args))\n\nobject TLImp extends NodeImp[TLMasterPortParameters, TLSlavePortParameters, TLEdgeOut, TLEdgeIn, TLBundle]\n{\n def edgeO(pd: TLMasterPortParameters, pu: TLSlavePortParameters, p: Parameters, sourceInfo: SourceInfo) = new TLEdgeOut(pd, pu, p, sourceInfo)\n def edgeI(pd: TLMasterPortParameters, pu: TLSlavePortParameters, p: Parameters, sourceInfo: SourceInfo) = new TLEdgeIn (pd, pu, p, sourceInfo)\n\n def bundleO(eo: TLEdgeOut) = TLBundle(eo.bundle)\n def bundleI(ei: TLEdgeIn) = TLBundle(ei.bundle)\n\n def render(ei: TLEdgeIn) = RenderedEdge(colour = \"#000000\" /* black */, label = (ei.manager.beatBytes * 8).toString)\n\n override def monitor(bundle: TLBundle, edge: TLEdgeIn): Unit = {\n val monitor = Module(edge.params(TLMonitorBuilder)(TLMonitorArgs(edge)))\n monitor.io.in :#= bundle\n }\n\n override def mixO(pd: TLMasterPortParameters, node: OutwardNode[TLMasterPortParameters, TLSlavePortParameters, TLBundle]): TLMasterPortParameters =\n pd.v1copy(clients = pd.clients.map { c => c.v1copy (nodePath = node +: c.nodePath) })\n override def mixI(pu: TLSlavePortParameters, node: InwardNode[TLMasterPortParameters, TLSlavePortParameters, TLBundle]): TLSlavePortParameters =\n pu.v1copy(managers = pu.managers.map { m => m.v1copy (nodePath = node +: m.nodePath) })\n}\n\n\ntrait TLFormatNode extends FormatNode[TLEdgeIn, TLEdgeOut]\n\ncase class TLClientNode(portParams: Seq[TLMasterPortParameters])(implicit valName: ValName) extends SourceNode(TLImp)(portParams) with TLFormatNode\ncase class TLManagerNode(portParams: Seq[TLSlavePortParameters])(implicit valName: ValName) extends SinkNode(TLImp)(portParams) with TLFormatNode\n\ncase class TLAdapterNode(\n clientFn: TLMasterPortParameters => TLMasterPortParameters = { s => s },\n managerFn: TLSlavePortParameters => TLSlavePortParameters = { s => s })(\n implicit valName: ValName)\n extends AdapterNode(TLImp)(clientFn, managerFn) with TLFormatNode\n\ncase class TLJunctionNode(\n clientFn: Seq[TLMasterPortParameters] => Seq[TLMasterPortParameters],\n managerFn: Seq[TLSlavePortParameters] => Seq[TLSlavePortParameters])(\n implicit valName: ValName)\n extends JunctionNode(TLImp)(clientFn, managerFn) with TLFormatNode\n\ncase class TLIdentityNode()(implicit valName: ValName) extends IdentityNode(TLImp)() with TLFormatNode\n\nobject TLNameNode {\n def apply(name: ValName) = TLIdentityNode()(name)\n def apply(name: Option[String]): TLIdentityNode = apply(ValName(name.getOrElse(\"with_no_name\")))\n def apply(name: String): TLIdentityNode = apply(Some(name))\n}\n\ncase class TLEphemeralNode()(implicit valName: ValName) extends EphemeralNode(TLImp)()\n\nobject TLTempNode {\n def apply(): TLEphemeralNode = TLEphemeralNode()(ValName(\"temp\"))\n}\n\ncase class TLNexusNode(\n clientFn: Seq[TLMasterPortParameters] => TLMasterPortParameters,\n managerFn: Seq[TLSlavePortParameters] => TLSlavePortParameters)(\n implicit valName: ValName)\n extends NexusNode(TLImp)(clientFn, managerFn) with TLFormatNode\n\nabstract class TLCustomNode(implicit valName: ValName)\n extends CustomNode(TLImp) with TLFormatNode\n\n// Asynchronous crossings\n\ntrait TLAsyncFormatNode extends FormatNode[TLAsyncEdgeParameters, TLAsyncEdgeParameters]\n\nobject TLAsyncImp extends SimpleNodeImp[TLAsyncClientPortParameters, TLAsyncManagerPortParameters, TLAsyncEdgeParameters, TLAsyncBundle]\n{\n def edge(pd: TLAsyncClientPortParameters, pu: TLAsyncManagerPortParameters, p: Parameters, sourceInfo: SourceInfo) = TLAsyncEdgeParameters(pd, pu, p, sourceInfo)\n def bundle(e: TLAsyncEdgeParameters) = new TLAsyncBundle(e.bundle)\n def render(e: TLAsyncEdgeParameters) = RenderedEdge(colour = \"#ff0000\" /* red */, label = e.manager.async.depth.toString)\n\n override def mixO(pd: TLAsyncClientPortParameters, node: OutwardNode[TLAsyncClientPortParameters, TLAsyncManagerPortParameters, TLAsyncBundle]): TLAsyncClientPortParameters =\n pd.copy(base = pd.base.v1copy(clients = pd.base.clients.map { c => c.v1copy (nodePath = node +: c.nodePath) }))\n override def mixI(pu: TLAsyncManagerPortParameters, node: InwardNode[TLAsyncClientPortParameters, TLAsyncManagerPortParameters, TLAsyncBundle]): TLAsyncManagerPortParameters =\n pu.copy(base = pu.base.v1copy(managers = pu.base.managers.map { m => m.v1copy (nodePath = node +: m.nodePath) }))\n}\n\ncase class TLAsyncAdapterNode(\n clientFn: TLAsyncClientPortParameters => TLAsyncClientPortParameters = { s => s },\n managerFn: TLAsyncManagerPortParameters => TLAsyncManagerPortParameters = { s => s })(\n implicit valName: ValName)\n extends AdapterNode(TLAsyncImp)(clientFn, managerFn) with TLAsyncFormatNode\n\ncase class TLAsyncIdentityNode()(implicit valName: ValName) extends IdentityNode(TLAsyncImp)() with TLAsyncFormatNode\n\nobject TLAsyncNameNode {\n def apply(name: ValName) = TLAsyncIdentityNode()(name)\n def apply(name: Option[String]): TLAsyncIdentityNode = apply(ValName(name.getOrElse(\"with_no_name\")))\n def apply(name: String): TLAsyncIdentityNode = apply(Some(name))\n}\n\ncase class TLAsyncSourceNode(sync: Option[Int])(implicit valName: ValName)\n extends MixedAdapterNode(TLImp, TLAsyncImp)(\n dFn = { p => TLAsyncClientPortParameters(p) },\n uFn = { p => p.base.v1copy(minLatency = p.base.minLatency + sync.getOrElse(p.async.sync)) }) with FormatNode[TLEdgeIn, TLAsyncEdgeParameters] // discard cycles in other clock domain\ncase class TLAsyncSinkNode(async: AsyncQueueParams)(implicit valName: ValName)\n extends MixedAdapterNode(TLAsyncImp, TLImp)(\n dFn = { p => p.base.v1copy(minLatency = p.base.minLatency + async.sync) },\n uFn = { p => TLAsyncManagerPortParameters(async, p) }) with FormatNode[TLAsyncEdgeParameters, TLEdgeOut]\n\n// Rationally related crossings\n\ntrait TLRationalFormatNode extends FormatNode[TLRationalEdgeParameters, TLRationalEdgeParameters]\n\nobject TLRationalImp extends SimpleNodeImp[TLRationalClientPortParameters, TLRationalManagerPortParameters, TLRationalEdgeParameters, TLRationalBundle]\n{\n def edge(pd: TLRationalClientPortParameters, pu: TLRationalManagerPortParameters, p: Parameters, sourceInfo: SourceInfo) = TLRationalEdgeParameters(pd, pu, p, sourceInfo)\n def bundle(e: TLRationalEdgeParameters) = new TLRationalBundle(e.bundle)\n def render(e: TLRationalEdgeParameters) = RenderedEdge(colour = \"#00ff00\" /* green */)\n\n override def mixO(pd: TLRationalClientPortParameters, node: OutwardNode[TLRationalClientPortParameters, TLRationalManagerPortParameters, TLRationalBundle]): TLRationalClientPortParameters =\n pd.copy(base = pd.base.v1copy(clients = pd.base.clients.map { c => c.v1copy (nodePath = node +: c.nodePath) }))\n override def mixI(pu: TLRationalManagerPortParameters, node: InwardNode[TLRationalClientPortParameters, TLRationalManagerPortParameters, TLRationalBundle]): TLRationalManagerPortParameters =\n pu.copy(base = pu.base.v1copy(managers = pu.base.managers.map { m => m.v1copy (nodePath = node +: m.nodePath) }))\n}\n\ncase class TLRationalAdapterNode(\n clientFn: TLRationalClientPortParameters => TLRationalClientPortParameters = { s => s },\n managerFn: TLRationalManagerPortParameters => TLRationalManagerPortParameters = { s => s })(\n implicit valName: ValName)\n extends AdapterNode(TLRationalImp)(clientFn, managerFn) with TLRationalFormatNode\n\ncase class TLRationalIdentityNode()(implicit valName: ValName) extends IdentityNode(TLRationalImp)() with TLRationalFormatNode\n\nobject TLRationalNameNode {\n def apply(name: ValName) = TLRationalIdentityNode()(name)\n def apply(name: Option[String]): TLRationalIdentityNode = apply(ValName(name.getOrElse(\"with_no_name\")))\n def apply(name: String): TLRationalIdentityNode = apply(Some(name))\n}\n\ncase class TLRationalSourceNode()(implicit valName: ValName)\n extends MixedAdapterNode(TLImp, TLRationalImp)(\n dFn = { p => TLRationalClientPortParameters(p) },\n uFn = { p => p.base.v1copy(minLatency = 1) }) with FormatNode[TLEdgeIn, TLRationalEdgeParameters] // discard cycles from other clock domain\ncase class TLRationalSinkNode(direction: RationalDirection)(implicit valName: ValName)\n extends MixedAdapterNode(TLRationalImp, TLImp)(\n", "right_context": " uFn = { p => TLRationalManagerPortParameters(direction, p) }) with FormatNode[TLRationalEdgeParameters, TLEdgeOut]\n\n// Credited version of TileLink channels\n\ntrait TLCreditedFormatNode extends FormatNode[TLCreditedEdgeParameters, TLCreditedEdgeParameters]\n\nobject TLCreditedImp extends SimpleNodeImp[TLCreditedClientPortParameters, TLCreditedManagerPortParameters, TLCreditedEdgeParameters, TLCreditedBundle]\n{\n def edge(pd: TLCreditedClientPortParameters, pu: TLCreditedManagerPortParameters, p: Parameters, sourceInfo: SourceInfo) = TLCreditedEdgeParameters(pd, pu, p, sourceInfo)\n def bundle(e: TLCreditedEdgeParameters) = new TLCreditedBundle(e.bundle)\n def render(e: TLCreditedEdgeParameters) = RenderedEdge(colour = \"#ffff00\" /* yellow */, e.delay.toString)\n\n override def mixO(pd: TLCreditedClientPortParameters, node: OutwardNode[TLCreditedClientPortParameters, TLCreditedManagerPortParameters, TLCreditedBundle]): TLCreditedClientPortParameters =\n pd.copy(base = pd.base.v1copy(clients = pd.base.clients.map { c => c.v1copy (nodePath = node +: c.nodePath) }))\n override def mixI(pu: TLCreditedManagerPortParameters, node: InwardNode[TLCreditedClientPortParameters, TLCreditedManagerPortParameters, TLCreditedBundle]): TLCreditedManagerPortParameters =\n pu.copy(base = pu.base.v1copy(managers = pu.base.managers.map { m => m.v1copy (nodePath = node +: m.nodePath) }))\n}\n\ncase class TLCreditedAdapterNode(\n clientFn: TLCreditedClientPortParameters => TLCreditedClientPortParameters = { s => s },\n managerFn: TLCreditedManagerPortParameters => TLCreditedManagerPortParameters = { s => s })(\n implicit valName: ValName)\n extends AdapterNode(TLCreditedImp)(clientFn, managerFn) with TLCreditedFormatNode\n\ncase class TLCreditedIdentityNode()(implicit valName: ValName) extends IdentityNode(TLCreditedImp)() with TLCreditedFormatNode\n\nobject TLCreditedNameNode {\n def apply(name: ValName) = TLCreditedIdentityNode()(name)\n def apply(name: Option[String]): TLCreditedIdentityNode = apply(ValName(name.getOrElse(\"with_no_name\")))\n def apply(name: String): TLCreditedIdentityNode = apply(Some(name))\n}\n\ncase class TLCreditedSourceNode(delay: TLCreditedDelay)(implicit valName: ValName)\n extends MixedAdapterNode(TLImp, TLCreditedImp)(\n dFn = { p => TLCreditedClientPortParameters(delay, p) },\n uFn = { p => p.base.v1copy(minLatency = 1) }) with FormatNode[TLEdgeIn, TLCreditedEdgeParameters] // discard cycles from other clock domain\n\ncase class TLCreditedSinkNode(delay: TLCreditedDelay)(implicit valName: ValName)\n extends MixedAdapterNode(TLCreditedImp, TLImp)(\n dFn = { p => p.base.v1copy(minLatency = 1) },\n uFn = { p => TLCreditedManagerPortParameters(delay, p) }) with FormatNode[TLCreditedEdgeParameters, TLEdgeOut]\n", "groundtruth": " dFn = { p => p.base.v1copy(minLatency = 1) },\n", "crossfile_context": ""}
{"task_id": "rocket-chip", "path": "rocket-chip/src/main/scala/util/ClockGate.scala", "left_context": "// See LICENSE.SiFive for license details.\n\npackage freechips.rocketchip.util\n\nimport chisel3._\nimport chisel3.util.{HasBlackBoxResource, HasBlackBoxPath}\nimport org.chipsalliance.cde.config.{Field, Parameters}\n\nimport java.nio.file.{Files, Paths}\n\ncase object ClockGateImpl extends Field[() => ClockGate](() => new EICG_wrapper)\ncase object ClockGateModelFile extends Field[Option[String]](None)\n\nabstract class ClockGate extends BlackBox\n with HasBlackBoxResource with HasBlackBoxPath {\n val io = IO(new Bundle{\n val in = Input(Clock())\n val test_en = Input(Bool())\n val en = Input(Bool())\n val out = Output(Clock())\n })\n\n def addVerilogResource(vsrc: String): Unit = {\n if (Files.exists(Paths.get(vsrc)))\n addPath(vsrc)\n else\n addResource(vsrc)\n }\n}\n\nobject ClockGate {\n def apply[T <: ClockGate](\n in: Clock,\n en: Bool,\n name: Option[String] = None)(implicit p: Parameters): Clock = {\n val cg = Module(p(ClockGateImpl)())\n name.foreach(cg.suggestName(_))\n p(ClockGateModelFile).map(cg.addVerilogResource(_))\n\n cg.io.in := in\n cg.io.test_en := false.B\n cg.io.en := en\n cg.io.out\n }\n\n def apply[T <: ClockGate](\n in: Clock,\n en: Bool,\n name: String)(implicit p: Parameters): Clock =\n apply(in, en, Some(name))\n}\n\n// behavioral model of Integrated Clock Gating cell\n", "right_context": "", "groundtruth": "class EICG_wrapper extends ClockGate\n", "crossfile_context": ""}
{"task_id": "rocket-chip", "path": "rocket-chip/src/main/scala/util/CoreMonitor.scala", "left_context": "// See LICENSE.Berkeley for license details.\n// See LICENSE.SiFive for license details.\n\npackage freechips.rocketchip.util\n\nimport chisel3._\n\n// this bundle is used to expose some internal core signals\n// to verification monitors which sample instruction commits\n", "right_context": " val wrenx = Bool()\n val wrenf = Bool()\n @deprecated(\"replace wren with wrenx or wrenf to specify integer or floating point\",\"Rocket Chip 2020.05\")\n def wren: Bool = wrenx || wrenf\n val rd0src = UInt(width = 5.W)\n val rd0val = UInt(width = xLen.W)\n val rd1src = UInt(width = 5.W)\n val rd1val = UInt(width = xLen.W)\n val inst = UInt(width = 32.W)\n}\n\n// mark a module that has cores with CoreMonitorBundles\ntrait HasCoreMonitorBundles {\n def coreMonitorBundles: List[CoreMonitorBundle]\n}\n", "groundtruth": "class CoreMonitorBundle(val xLen: Int, val fLen: Int) extends Bundle with Clocked {\n val excpt = Bool()\n val priv_mode = UInt(width = 3.W)\n val hartid = UInt(width = xLen.W)\n val timer = UInt(width = 32.W)\n", "crossfile_context": ""}
{"task_id": "rocket-chip", "path": "rocket-chip/src/main/scala/util/DescribedSRAM.scala", "left_context": "// See LICENSE.Berkeley for license details.\n// See LICENSE.SiFive for license details.\n\npackage freechips.rocketchip.util\n\nimport chisel3.{Data, SyncReadMem, Vec}\nimport chisel3.util.log2Ceil\n\nobject DescribedSRAM {\n def apply[T <: Data](\n name: String,\n desc: String,\n size: BigInt, // depth\n data: T\n ): SyncReadMem[T] = {\n\n val mem = SyncReadMem(size, data)\n\n", "right_context": " }\n\n val uid = 0\n\n mem\n }\n}\n", "groundtruth": " mem.suggestName(name)\n\n val granWidth = data match {\n", "crossfile_context": ""}
{"task_id": "chiseltest", "path": "chiseltest/src/main/scala/chiseltest/coverage/FsmCoveragePass.scala", "left_context": "// Copyright 2021-2023 The Regents of the University of California\n// released under BSD 3-Clause License\n// author: Kevin Laeufer \n\npackage chiseltest.coverage\n\nimport firrtl2._\nimport firrtl2.annotations._\nimport firrtl2.options.Dependency\nimport firrtl2.stage.Forms\nimport firrtl2.stage.TransformManager.TransformDependency\n\nimport scala.collection.mutable\n\ncase class FsmCoverageAnnotation(\n stateReg: ReferenceTarget,\n states: Seq[(String, ReferenceTarget)],\n transitions: Seq[((String, String), ReferenceTarget)])\n extends MultiTargetAnnotation\n with CoverageInfo {\n override def targets = Seq(Seq(stateReg)) ++ states.map(s => Seq(s._2)) ++ transitions.map(t => Seq(t._2))\n\n override def duplicate(n: Seq[Seq[Target]]) = {\n assert(n.length == 1 + states.length + transitions.length)\n n.foreach(e => assert(e.length == 1, \"Cover points and state registers should not be split up!\"))\n val targets = n.map(_.head.asInstanceOf[ReferenceTarget])\n val r = copy(\n stateReg = targets.head,\n states = states.map(_._1).zip(targets.slice(1, states.length + 1)),\n transitions = transitions.map(_._1).zip(targets.drop(1 + states.length))\n )\n r\n }\n}\n\ncase object SkipFsmCoverageAnnotation extends NoTargetAnnotation\n\nobject FsmCoveragePass extends Transform {\n val Prefix = \"f\"\n\n override def prerequisites: Seq[TransformDependency] =\n Forms.LowForm ++ Seq(Dependency(FsmInfoPass), Dependency(RegisterResetAnnotationPass))\n override def invalidates(a: Transform): Boolean = false\n\n override def execute(state: CircuitState): CircuitState = {\n if (state.annotations.contains(SkipFsmCoverageAnnotation)) {\n logger.info(\"[FsmCoverage] skipping due to SkipFsmCoverage annotation\")\n return state\n }\n\n // collect FSMs in modules that are not ignored\n val ignoreMods = Coverage.collectModulesToIgnore(state)\n val infos = state.annotations.collect { case a: FsmInfoAnnotation if !ignoreMods(a.target.module) => a }\n\n // if there are no FSMs there is nothing to do\n if (infos.isEmpty) return state\n\n // instrument FSMs\n val registerResets = state.annotations.collect { case a: RegisterResetAnnotation => a }\n val newAnnos = mutable.ListBuffer[Annotation]()\n val c = CircuitTarget(state.circuit.main)\n val circuit = state.circuit.mapModule(onModule(_, c, newAnnos, infos, registerResets))\n state.copy(circuit = circuit, annotations = newAnnos.toList ++ state.annotations)\n }\n\n private def onModule(\n m: ir.DefModule,\n c: CircuitTarget,\n annos: mutable.ListBuffer[Annotation],\n infos: Seq[FsmInfoAnnotation],\n resets: Seq[RegisterResetAnnotation]\n ): ir.DefModule = m match {\n case mod: ir.Module =>\n val fsms = infos.filter(_.target.module == mod.name)\n if (fsms.isEmpty) { mod }\n else {\n val isFsm = fsms.map(_.target.ref).toSet\n val fsmRegs = findFsmRegs(mod.body, isFsm)\n val stmts = new mutable.ListBuffer[ir.Statement]()\n val ctx = ModuleCtx(c.module(mod.name), stmts, Namespace(mod))\n val toReset = RegisterResetAnnotationPass.findResetsInModule(ctx.m, resets)\n val fsmAnnos = fsms.map { f => onFsm(f, fsmRegs.find(_.name == f.target.ref).get, ctx, toReset.get) }\n annos ++= fsmAnnos\n val newBody = ir.Block(mod.body +: stmts.toList)\n\n mod.copy(body = newBody)\n }\n case other => other\n }\n\n private case class ModuleCtx(m: ModuleTarget, stmts: mutable.ListBuffer[ir.Statement], namespace: Namespace)\n\n private def onFsm(fsm: FsmInfoAnnotation, reg: ir.DefRegister, ctx: ModuleCtx, toReset: String => Option[String])\n : Annotation = {\n val info = reg.info\n val clock = reg.clock\n val reset = toReset(reg.name).map(ir.Reference(_, Utils.BoolType, NodeKind, SourceFlow)).getOrElse(Utils.False())\n val notReset = Utils.not(reset)\n val regRef = ir.Reference(reg)\n val regWidth = firrtl2.bitWidth(reg.tpe)\n def inState(s: BigInt): ir.Expression = Utils.eq(regRef, ir.UIntLiteral(s, ir.IntWidth(regWidth)))\n\n // cover state when FSM is _not_ in reset\n val states = fsm.states.map { case (id, stateName) =>\n val name = ctx.namespace.newName(reg.name + \"_\" + stateName)\n ctx.stmts.append(ir.Verification(ir.Formal.Cover, info, clock, inState(id), notReset, ir.StringLit(\"\"), name))\n stateName -> ctx.m.ref(name)\n }\n\n // create a register to hold the previous state\n val prevState =\n Builder.makeRegister(ctx.stmts, info, ctx.namespace.newName(reg.name + \"_prev\"), reg.tpe, clock, regRef)\n", "right_context": "\n // create a register to track if the previous state is valid\n val prevValid = Builder.makeRegister(\n ctx.stmts,\n info,\n ctx.namespace.newName(reg.name + \"_prev_valid\"),\n Utils.BoolType,\n clock,\n notReset\n )\n\n // create a transition valid signal\n val transitionValid = ir.Reference(ctx.namespace.newName(reg.name + \"_t_valid\"), Utils.BoolType, NodeKind)\n ctx.stmts.append(ir.DefNode(info, transitionValid.name, Utils.and(notReset, prevValid)))\n\n val idToName = fsm.states.toMap\n val transitions = fsm.transitions.map { case (from, to) =>\n val (fromName, toName) = (idToName(from), idToName(to))\n val name = ctx.namespace.newName(reg.name + \"_\" + fromName + \"_to_\" + toName)\n ctx.stmts.append(\n ir.Verification(\n ir.Formal.Cover,\n info,\n clock,\n Utils.and(inPrevState(from), inState(to)),\n transitionValid,\n ir.StringLit(\"\"),\n name\n )\n )\n (fromName, toName) -> ctx.m.ref(name)\n }\n\n FsmCoverageAnnotation(ctx.m.ref(reg.name), states, transitions)\n }\n\n private def printFsmInfo(fsm: FsmInfoAnnotation): Unit = {\n val toName = fsm.states.toMap\n println(s\"[${fsm.target.module}.${fsm.target.name}] Found FSM\")\n if (fsm.start.nonEmpty) {\n println(s\"Start: ${toName(fsm.start.get)}\")\n }\n println(\"Transitions:\")\n fsm.transitions.foreach(t => println(s\"${toName(t._1)} -> ${toName(t._2)}\"))\n }\n\n private def findFsmRegs(s: ir.Statement, isFsm: String => Boolean): Seq[ir.DefRegister] = s match {\n case r: ir.DefRegister if isFsm(r.name) => List(r)\n case ir.Block(stmts) => stmts.flatMap(findFsmRegs(_, isFsm))\n case _: ir.Conditionally => throw new RuntimeException(\"Unexpected when statement! Expected LoFirrtl.\")\n case _ => List()\n }\n}\n", "groundtruth": " def inPrevState(s: BigInt): ir.Expression = Utils.eq(prevState, ir.UIntLiteral(s, ir.IntWidth(regWidth)))\n", "crossfile_context": ""}
{"task_id": "chiseltest", "path": "chiseltest/src/main/scala/chiseltest/simulator/BlackBox.scala", "left_context": "package chiseltest.simulator\n\nimport chiseltest.simulator.jna.JNAUtils\n\nimport java.io.{File, FileInputStream, FileOutputStream, PrintWriter}\nimport scala.io.Source\n\nprivate object BlackBox {\n\n /** add the `.f` file containing the names of all blackbox verilog files, if it exists */\n def fFileFlags(targetDir: os.Path): Seq[String] = {\n val fFile = targetDir / firrtl2.transforms.BlackBoxSourceHelper.defaultFileListName\n if (os.exists(fFile)) {\n if (JNAUtils.isWindows) {\n // The canonical path on Windows contains backslashes that\n // verilator does not recognize\n // We need to transform backslashes to slashes\n", "right_context": " val writer = new PrintWriter(windowsfFile)\n val source = Source.fromFile(fFile.toString())\n source.getLines().foreach(line => writer.println(line.replace(\"\\\\\", \"/\")))\n source.close()\n writer.close()\n Seq(\"-f\", windowsfFile)\n } else {\n Seq(\"-f\", fFile.toString())\n }\n } else { Seq() }\n }\n}\n", "groundtruth": " val windowsfFile = s\"${fFile.toString()}.win\"\n", "crossfile_context": ""}
{"task_id": "chiseltest", "path": "chiseltest/src/main/scala/chiseltest/simulator/VerilatorSimulator.scala", "left_context": "// SPDX-License-Identifier: Apache-2.0\n\npackage chiseltest.simulator\n\nimport firrtl2._\nimport firrtl2.annotations._\nimport chiseltest.simulator.jna._\nimport chiseltest.simulator.Utils.quoteCmdArgs\n\ncase object VerilatorBackendAnnotation extends SimulatorAnnotation {\n override def getSimulator: Simulator = VerilatorSimulator\n}\n\n/** verilator specific options */\ntrait VerilatorOption extends NoTargetAnnotation\n\n/** adds flags to the invocation of verilator */\ncase class VerilatorFlags(flags: Seq[String]) extends VerilatorOption\n\n/** adds flags to the C++ compiler in the Makefile generated by verilator */\ncase class VerilatorCFlags(flags: Seq[String]) extends VerilatorOption\n\n/** adds flags to the linker in the Makefile generated by verilator */\ncase class VerilatorLinkFlags(flags: Seq[String]) extends VerilatorOption\n\nprivate object VerilatorSimulator extends Simulator {\n override def name: String = \"verilator\"\n\n /** is this simulator installed on the local machine? */\n override def isAvailable: Boolean = {\n val binaryFound = os.proc(\"which\", \"verilator\").call().exitCode == 0\n binaryFound && majorVersion >= 4\n }\n\n override def supportsCoverage = true\n override def supportsLiveCoverage = true\n override def waveformFormats = Seq(WriteVcdAnnotation, WriteFstAnnotation)\n\n /** search the local computer for an installation of this simulator and print versions */\n def findVersions(): Unit = {\n if (isAvailable) {\n val (maj, min) = version\n println(s\"Found Verilator $maj.$min\")\n }\n }\n\n // example version string1: Verilator 4.038 2020-07-11 rev v4.038\n // example version string2: Verilator 5.002.p 2022-11-15 rev v5.002-12-g58821e0eb\n private lazy val version: (Int, Int) = { // (major, minor)\n val versionSplitted = os\n .proc(\n", "right_context": " else { \"verilator\" },\n \"--version\"\n )\n .call()\n .out\n .trim()\n .split(' ')\n assert(\n versionSplitted.length > 1 && versionSplitted.head == \"Verilator\",\n s\"Unknown verilator version string: ${versionSplitted.mkString(\" \")}\"\n )\n\n val (maj, min) = versionSplitted(1).split('.').map(_.trim) match {\n case Array(majStr, minStr) =>\n assert(majStr.length == 1 && minStr.length == 3, s\"${majStr}.${minStr} is not of the expected format: D.DDD\")\n (majStr.toInt, minStr.toInt)\n case Array(majStr, minStr, s) =>\n assert(majStr.length == 1 && minStr.length == 3, s\"${majStr}.${minStr} is not of the expected format: D.DDD.s+\")\n (majStr.toInt, minStr.toInt)\n case s =>\n assert(false, s\"${s} is not of the expected format: D.DDD or D.DDD.s+\")\n (0, 0)\n }\n (maj, min)\n }\n\n private def majorVersion: Int = version._1\n private def minorVersion: Int = version._2\n\n /** start a new simulation\n *\n * @param state\n * LoFirrtl circuit + annotations\n */\n override def createContext(state: CircuitState): SimulatorContext = {\n val simName = s\"${VerilatorSimulator.name} ${VerilatorSimulator.majorVersion}.${VerilatorSimulator.minorVersion}\"\n Caching.cacheSimulationBin(simName, state, createContextFromScratch, recreateCachedContext)\n }\n\n private def getSimulatorArgs(state: CircuitState): Array[String] = {\n state.annotations.view.collect { case PlusArgsAnnotation(args) => args }.flatten.toArray\n }\n\n private def recreateCachedContext(state: CircuitState): SimulatorContext = {\n // we will create the simulation in the target directory\n val targetDir = Compiler.requireTargetDir(state.annotations)\n val toplevel = TopmoduleInfo(state.circuit)\n\n val libFilename = if (JNAUtils.isWindows) { \"V\" + toplevel.name + \".exe\" }\n else { \"V\" + toplevel.name }\n val libPath = targetDir / \"verilated\" / libFilename\n // the binary we created communicates using our standard IPC interface\n val coverageAnnos = loadCoverageAnnos(targetDir)\n val coverageFile = targetDir / \"coverage.dat\"\n def readCoverage(): List[(String, Long)] = {\n assert(os.exists(coverageFile), s\"Could not find `$coverageFile` file!\")\n VerilatorCoverage.loadCoverage(coverageAnnos, coverageFile, (majorVersion, minorVersion))\n }\n\n val args = getSimulatorArgs(state)\n val lib = JNAUtils.compileAndLoadJNAClass(libPath)\n new JNASimulatorContext(lib, targetDir, toplevel, VerilatorSimulator, args, Some(readCoverage))\n }\n\n private def createContextFromScratch(state: CircuitState): SimulatorContext = {\n // we will create the simulation in the target directory\n val targetDir = Compiler.requireTargetDir(state.annotations)\n val toplevel = TopmoduleInfo(state.circuit)\n\n // verbose output to stdout if we are in debug mode\n val verbose = state.annotations.contains(SimulatorDebugAnnotation)\n\n // Create the header files that verilator needs + a custom harness\n val waveformExt = Simulator.getWavformFormat(state.annotations)\n val cppHarness = generateHarness(targetDir, toplevel, waveformExt, verbose)\n\n // compile low firrtl to System Verilog for verilator to use\n val verilogState = Compiler.lowFirrtlToSystemVerilog(state, VerilatorCoverage.CoveragePasses)\n\n // turn SystemVerilog into C++ simulation\n val verilatedDir = runVerilator(toplevel.name, targetDir, cppHarness, state.annotations, verbose)\n\n // patch the coverage cpp provided with verilator only if Verilator is older than 4.202\n // Starting with Verilator 4.202, the whole patch coverage hack is no longer necessary\n require(\n majorVersion >= 4,\n s\"Unsupported Verilator version: $majorVersion.$minorVersion. Only major version 4 and up is supported.\"\n )\n\n if (majorVersion == 4 && minorVersion < 202) {\n VerilatorPatchCoverageCpp(verilatedDir, majorVersion, minorVersion)\n }\n\n val libPath = compileSimulation(topName = toplevel.name, verilatedDir, verbose)\n\n // the binary we created communicates using our standard IPC interface\n val coverageAnnos = VerilatorCoverage.collectCoverageAnnotations(verilogState.annotations)\n if (Caching.shouldCache(state)) {\n saveCoverageAnnos(targetDir, coverageAnnos)\n }\n val coverageFile = targetDir / \"coverage.dat\"\n def readCoverage(): List[(String, Long)] = {\n assert(os.exists(coverageFile), s\"Could not find `$coverageFile` file!\")\n VerilatorCoverage.loadCoverage(coverageAnnos, coverageFile, (majorVersion, minorVersion))\n }\n\n val args = getSimulatorArgs(state)\n val lib = JNAUtils.compileAndLoadJNAClass(libPath)\n new JNASimulatorContext(lib, targetDir, toplevel, VerilatorSimulator, args, Some(readCoverage))\n }\n\n private def saveCoverageAnnos(targetDir: os.Path, annos: AnnotationSeq): Unit = {\n os.write.over(targetDir / \"coverageAnnotations.json\", JsonProtocol.serialize(annos))\n }\n\n private def loadCoverageAnnos(targetDir: os.Path): AnnotationSeq = {\n JsonProtocol.deserialize((targetDir / \"coverageAnnotations.json\").toIO)\n }\n\n private def compileSimulation(topName: String, verilatedDir: os.Path, verbose: Boolean): os.Path = {\n val target = s\"V$topName\"\n val processorCount = Runtime.getRuntime.availableProcessors.toString\n val cmd = Seq(\"make\", \"-C\", verilatedDir.toString(), \"-j\", processorCount, \"-f\", s\"V$topName.mk\", target)\n val ret = run(cmd, null, verbose)\n assert(\n ret.exitCode == 0,\n s\"Compilation of verilator generated code failed for circuit $topName in work dir $verilatedDir\"\n )\n val simBinary = if (JNAUtils.isWindows) { verilatedDir / s\"${target}.exe\" }\n else { verilatedDir / target }\n assert(os.exists(simBinary), s\"Failed to generate simulation binary: $simBinary\")\n simBinary\n }\n\n /** executes verilator in order to generate a C++ simulation */\n private def runVerilator(\n topName: String,\n targetDir: os.Path,\n cppHarness: String,\n annos: AnnotationSeq,\n verbose: Boolean\n ): os.Path = {\n val verilatedDir = targetDir / \"verilated\"\n\n removeOldCode(verilatedDir, verbose)\n val flagAnnos = VerilatorLinkFlags(JNAUtils.ldFlags) +: VerilatorCFlags(JNAUtils.ccFlags) +: annos\n val flags = generateFlags(topName, verilatedDir, flagAnnos)\n val cmd = List(\n if (JNAUtils.isWindows) { \"verilator_bin\" }\n else { \"verilator\" },\n \"--cc\",\n \"--exe\",\n cppHarness\n ) ++ flags ++ List(s\"$topName.sv\")\n val ret = run(cmd, targetDir, verbose)\n\n assert(ret.exitCode == 0, s\"verilator command failed on circuit ${topName} in work dir $targetDir\")\n verilatedDir\n }\n\n private def removeOldCode(verilatedDir: os.Path, verbose: Boolean): Unit = {\n if (os.exists(verilatedDir)) {\n if (verbose) println(s\"Deleting stale Verilator object directory: $verilatedDir\")\n os.remove.all(verilatedDir)\n }\n }\n\n private def run(cmd: Seq[String], cwd: os.Path, verbose: Boolean): os.CommandResult = {\n if (verbose) {\n // print the command and pipe the output to stdout\n println(quoteCmdArgs(cmd))\n os.proc(cmd)\n .call(cwd = cwd, stdout = os.ProcessOutput.Readlines(println), stderr = os.ProcessOutput.Readlines(println))\n } else {\n os.proc(cmd).call(cwd = cwd)\n }\n }\n\n private def DefaultCFlags(topName: String) = List(\n \"-Os\",\n \"-DVL_USER_STOP\",\n \"-DVL_USER_FATAL\",\n \"-DVL_USER_FINISH\", // this is required because we ant to overwrite the vl_finish function!\n s\"-DTOP_TYPE=V$topName\"\n )\n\n private def DefaultFlags(topName: String, verilatedDir: os.Path, cFlags: Seq[String], ldFlags: Seq[String]) = List(\n \"--assert\", // we always enable assertions\n \"--coverage-user\", // we always enable use coverage\n \"-Wno-fatal\",\n \"-Wno-WIDTH\",\n \"-Wno-STMTDLY\",\n \"--top-module\",\n topName,\n \"+define+TOP_TYPE=V\" + topName,\n // flags passed to the C++ compiler\n \"-CFLAGS\",\n cFlags.mkString(\" \"),\n // name of the directory that verilator generates the C++ model + Makefile in\n \"-Mdir\",\n verilatedDir.toString()\n ) ++ (if (ldFlags.nonEmpty) Seq(\"-LDFLAGS\", ldFlags.mkString(\" \")) else Seq())\n\n // documentation of Verilator flags: https://verilator.org/guide/latest/exe_verilator.html#\n private def generateFlags(topName: String, verilatedDir: os.Path, annos: AnnotationSeq): Seq[String] = {\n val waveformExt = Simulator.getWavformFormat(annos)\n val targetDir = Compiler.requireTargetDir(annos)\n\n // generate C flags\n val userCFlags = annos.collect { case VerilatorCFlags(f) => f }.flatten\n // some older versions of Verilator seem to not set VM_TRACE_FST correctly, thus:\n val fstCFlag = if (waveformExt == \"fst\") Seq(\"-DVM_TRACE_FST=1\") else Seq()\n val cFlags = DefaultCFlags(topName) ++ fstCFlag ++ userCFlags\n val ldFlags = annos.collect { case VerilatorLinkFlags(f) => f }.flatten\n\n // combine all flags\n val userFlags = annos.collectFirst { case VerilatorFlags(f) => f }.getOrElse(Seq.empty)\n val waveformFlags = waveformExt match {\n case \"vcd\" => List(\"--trace\")\n case \"fst\" => List(\"--trace-fst\")\n case \"\" => List()\n case other => throw new RuntimeException(s\"Unsupported waveform format: $other\")\n }\n val flags =\n DefaultFlags(topName, verilatedDir, cFlags, ldFlags) ++ waveformFlags ++ BlackBox.fFileFlags(\n targetDir\n ) ++ userFlags\n flags\n }\n\n private def generateHarness(\n targetDir: os.Path,\n toplevel: TopmoduleInfo,\n waveformExt: String,\n verbose: Boolean\n ): String = {\n val topName = toplevel.name\n\n // create a custom c++ harness\n val cppHarnessFileName = s\"${topName}-harness.cpp\"\n val vcdFile = targetDir / (s\"$topName.\" + waveformExt)\n val code = VerilatorCppJNAHarnessGenerator.codeGen(\n toplevel,\n vcdFile,\n targetDir,\n majorVersion = majorVersion,\n minorVersion = minorVersion,\n verbose = verbose\n )\n os.write.over(targetDir / cppHarnessFileName, code)\n\n cppHarnessFileName\n }\n}\n\n/** Changes the file generated by verilator to generate per instance and not per module coverage. This is required in\n * order to satisfy our generic TestCoverage interface for which the simulator needs to return per instance coverage\n * counts. See: https://github.com/verilator/verilator/issues/2793\n */\nprivate object VerilatorPatchCoverageCpp {\n private val CallNeedle = \"VL_COVER_INSERT(\"\n private val CallReplacement = \"CHISEL_VL_COVER_INSERT(\"\n private val CoverageStartNeedle = \"// Coverage\"\n\n def apply(dir: os.Path, major: Int, minor: Int): Unit = {\n assert(major == 4 && minor < 202, \"Starting with Verilator 4.202 this hack is no longer necessary!\")\n val files = loadFiles(dir)\n files.foreach { case (cppFile, lines) =>\n replaceCoverage(cppFile, lines, minor)\n doWrite(cppFile, lines)\n }\n }\n\n private def replaceCoverage(cppFile: os.Path, lines: Array[String], minor: Int): Unit = {\n // we add our code at the beginning of the coverage section\n val coverageStart = findLine(CoverageStartNeedle, cppFile, lines)\n lines(coverageStart) += \"\\n\" + CustomCoverInsertCode(withCtxPtr = minor >= 200) + \"\\n\"\n\n // then we replace the call\n val call = findLine(CallNeedle, cppFile, lines)\n val callLine = lines(call).replace(CallNeedle, CallReplacement)\n lines(call) = callLine\n }\n\n private def loadFiles(dir: os.Path): Seq[(os.Path, Array[String])] = {\n if (!os.exists(dir) || !os.isDir(dir)) {\n error(s\"Failed to find directory $dir\")\n }\n\n // find all cpp files generated by verilator\n val cppFiles = os.list(dir).filter(os.isFile).filter { f =>\n val name = f.last\n name.startsWith(\"V\") && name.endsWith(\".cpp\")\n }\n\n // filter out files that do not contain any coverage definitions\n cppFiles.map(f => (f, FileUtils.getLines(f).toArray)).filter { case (name, lines) =>\n findLineOption(CoverageStartNeedle, lines).isDefined\n }\n }\n\n private def findLineOption(needle: String, lines: Iterable[String]): Option[Int] =\n lines.map(_.trim).zipWithIndex.find(_._1.startsWith(needle)).map(_._2)\n\n private def findLine(needle: String, filename: os.Path, lines: Iterable[String]): Int =\n findLineOption(needle, lines).getOrElse(error(s\"Failed to find line `$needle` in $filename.\"))\n\n private def doWrite(file: os.Path, lines: Array[String]): Unit = os.write.over(file, lines.mkString(\"\\n\"))\n\n private def error(msg: String): Nothing = {\n throw new RuntimeException(msg + \"\\n\" + \"Please file an issue and include the output of `verilator --version`\")\n }\n\n private def CustomCoverInsertCode(withCtxPtr: Boolean): String = {\n val argPrefix = if (withCtxPtr) \"VerilatedCovContext* covcontextp, \" else \"\"\n val callArgPrefix = if (withCtxPtr) \"covcontextp, \" else \"\"\n val cov = if (withCtxPtr) \"covcontextp->\" else \"VerilatedCov::\"\n\n s\"\"\"#ifndef CHISEL_VL_COVER_INSERT\n |#define CHISEL_VL_COVER_INSERT(${callArgPrefix}countp, ...) \\\\\n | VL_IF_COVER(${cov}_inserti(countp); ${cov}_insertf(__FILE__, __LINE__); \\\\\n | chisel_insertp(${callArgPrefix}\"hier\", name(), __VA_ARGS__))\n |\n |#ifdef VM_COVERAGE\n |static void chisel_insertp(${argPrefix}\n | const char* key0, const char* valp0, const char* key1, const char* valp1,\n | const char* key2, int lineno, const char* key3, int column,\n | const char* key4, const std::string& hier_str,\n | const char* key5, const char* valp5, const char* key6, const char* valp6,\n | const char* key7 = nullptr, const char* valp7 = nullptr) {\n |\n | std::string val2str = vlCovCvtToStr(lineno);\n | std::string val3str = vlCovCvtToStr(column);\n | ${cov}_insertp(\n | key0, valp0, key1, valp1, key2, val2str.c_str(),\n | key3, val3str.c_str(), key4, hier_str.c_str(),\n | key5, valp5, key6, valp6, key7, valp7,\n | // turn on per instance cover points\n | \"per_instance\", \"1\");\n |}\n |#endif // VM_COVERAGE\n |#endif // CHISEL_VL_COVER_INSERT\n |\"\"\".stripMargin\n }\n}\n", "groundtruth": " if (JNAUtils.isWindows) { \"verilator_bin\" }\n", "crossfile_context": ""}
{"task_id": "chiseltest", "path": "chiseltest/src/main/scala/chiseltest/simulator/jna/JNASimulatorContext.scala", "left_context": "// SPDX-License-Identifier: Apache-2.0\n\npackage chiseltest.simulator.jna\n\nimport chiseltest.simulator._\nimport firrtl2.logger.LazyLogging\n\n/** This context works with a simulation binary that communicates through the Java Native Access library.\n * @param so\n * interface to the dynamic simulation library\n * @param targetDir\n * simulation target directory\n * @param toplevel\n * information about the interface exposed by the module at the top of the RTL hierarchy\n * @param sim\n * simulator that generated the binary\n * @param args\n * command line arguments to the simulator (eg. Verilog plusargs)\n * @param readCoverageFile\n * function that parses the coverage file and returns the list of counts\n */\nprivate[chiseltest] class JNASimulatorContext(\n so: TesterSharedLibInterface,\n targetDir: os.Path,\n toplevel: TopmoduleInfo,\n override val sim: Simulator,\n args: Array[String],\n readCoverageFile: Option[() => List[(String, Long)]] = None)\n extends SimulatorContext\n with LazyLogging {\n toplevel.requireNoMultiClock()\n private val allSignals = toplevel.inputs ++ toplevel.outputs\n private val isWide = allSignals.filter(_.width > 64).map(_.name).toSet\n private val mask64 = (BigInt(1) << 64) - 1\n private val signalWidth = allSignals.map(s => s.name -> s.width).toMap\n\n private var isStale = true\n private val signalToId = (toplevel.inputs ++ toplevel.outputs).map(_.name).zipWithIndex.toMap\n private val idToMask = (toplevel.inputs ++ toplevel.outputs).map(_.width).map(w => (BigInt(1) << w) - 1).toIndexedSeq\n private val idIsSigned = (toplevel.inputs ++ toplevel.outputs).map(_.signed).toIndexedSeq\n\n // Pass command line arguments to the simulator\n so.setArgs(args)\n\n private def update(): Unit = {\n assert(isRunning)\n so.update()\n isStale = false\n }\n\n private def takeSteps(cycles: Int): Long = {\n assert(isRunning)\n require(cycles > 0)\n so.step(cycles)\n }\n\n private def getId(signal: String): Int =\n signalToId.getOrElse(signal, throw new RuntimeException(s\"Unknown signal: $signal\"))\n\n override def poke(signal: String, value: BigInt): Unit = {\n assert(isRunning)\n val signalId = getId(signal)\n val mask = idToMask(signalId)\n val maskedValue = value & mask\n if (isWide(signal)) {\n val width = signalWidth(signal)\n val words = (width + 63) / 64\n var remaining = maskedValue\n (0 until words).foreach { ii =>\n val part = (remaining & mask64).toLong\n so.pokeWide(signalId, ii, part)\n remaining = remaining >> 64\n }\n } else {\n so.poke(signalId, maskedValue.toLong)\n }\n isStale = true\n }\n\n override def peek(signal: String): BigInt = {\n assert(isRunning)\n", "right_context": " val signalId = getId(signal)\n val width = signalWidth(signal)\n val unsigned = if (isWide(signal)) {\n val words = (width + 63) / 64\n var value = BigInt(0)\n (0 until words).foreach { ii =>\n val word = BigInt(so.peekWide(signalId, ii)) & mask64\n value = value | (word << (ii * 64))\n }\n value\n } else {\n so.peek(signalId) & mask64\n }\n if (idIsSigned(signalId)) { toSigned(unsigned, width) }\n else { unsigned }\n }\n\n private def toSigned(v: BigInt, width: Int): BigInt = {\n val isNegative = ((v >> (width - 1)) & 1) == 1\n if (isNegative) {\n val mask = (BigInt(1) << width) - 1\n val twosComp = ((~v) + 1) & mask\n -twosComp\n } else { v }\n }\n\n private def defaultClock = toplevel.clocks.headOption\n override def step(n: Int): StepResult = {\n assert(isRunning)\n defaultClock match {\n case Some(_) =>\n case None => throw NoClockException(toplevel.name)\n }\n update()\n val r = takeSteps(n)\n val status = (r >> 32) & 3\n if (status == 0) {\n StepOk\n } else if (status == 3) {\n val msg = \"The simulator has encountered an unrecoverable error.\\n\" +\n \"Please consult the standard output and error for more details.\"\n throw new RuntimeException(msg)\n } else {\n val isFailure = status != 1\n val after = r & 0xffffffffL\n StepInterrupted(after.toInt, isFailure, List())\n }\n }\n\n private var isRunning = true\n override def finish(): Unit = {\n assert(isRunning, \"Simulator is already stopped! Are you trying to call finish twice?\")\n so.finish()\n isRunning = false\n }\n\n private val coverageFile = targetDir / \"coverage.dat\"\n override def getCoverage(): List[(String, Long)] = {\n if (isRunning) {\n so.writeCoverage(coverageFile.toString())\n }\n assert(os.exists(coverageFile), s\"Could not find `$coverageFile` file!\")\n readCoverageFile.get()\n }\n\n override def resetCoverage(): Unit = {\n assert(isRunning)\n so.resetCoverage()\n }\n}\n", "groundtruth": " if (isStale) { update() }\n", "crossfile_context": ""}
{"task_id": "chiseltest", "path": "chiseltest/src/main/scala/treadle2/executable/ClockInfo.scala", "left_context": "// SPDX-License-Identifier: Apache-2.0\n\npackage treadle2.executable\n\n/** ClockInfo associates a clock with the given name and period and offset The period is in an arbitrary number of\n * ticks. The VCD logger currently sets these ticks to be nanosecond(ns). The first up transition takes place after\n * initialOffset ticks. One or more clocks can be specified through the TreadleOptions clockInfo as a Seq of\n * ClockInfo's or from string command line based --fint-clock-info or -fici which use the format\n * clock-name[:period[:initial-offset] ]\n *\n * @param name\n * the signal name of a clock\n * @param period\n * how many ticks between rising edges of this clock\n * @param initialOffset\n * the tick where the first up transition takes place.\n */\ncase class ClockInfo(\n name: String = ClockInfo.DefaultName,\n period: Long = ClockInfo.DefaultPeriod,\n initialOffset: Long = ClockInfo.DefaultOffset) {\n if (period % 2 != 0) {\n throw TreadleException(s\"Error: Clock period must be divisible by 2: Found $this\")\n }\n\n val upPeriod: Long = period / 2\n val downPeriod: Long = period - upPeriod\n if (initialOffset < 0) {\n throw TreadleException(s\"initialOffset in ClockInfo for $name must be positive. Found value $initialOffset\")\n }\n\n def prettyString: String = {\n", "right_context": " f\"$name%-40.40s period $period%5d, $detail%15s, first up at $initialOffset\"\n }\n}\n\n/** The default settings for a single clock are here. Units are in arbitrary ticks\n */\nobject ClockInfo {\n val DefaultName: String = \"clock\"\n val DefaultPeriod: Long = 10L\n val DefaultOffset: Long = 1L\n}\n", "groundtruth": " def detail = s\"(up: $upPeriod, down: $downPeriod)\"\n", "crossfile_context": ""}
{"task_id": "chiseltest", "path": "chiseltest/src/test/scala/chiseltest/backends/icarus/IcarusBlackBoxTest.scala", "left_context": "// SPDX-License-Identifier: Apache-2.0\n\npackage chiseltest.backends.icarus\n\nimport chisel3._\nimport chisel3.util._\nimport chiseltest._\nimport chiseltest.simulator.{PlusArgsAnnotation, RequiresIcarus}\nimport org.scalatest.flatspec.AnyFlatSpec\n\nimport scala.util.Random\n\nclass BlackBoxAdderIO extends Bundle {\n val a = Input(UInt(8.W))\n val b = Input(UInt(8.W))\n val q = Output(UInt(8.W))\n}\n\nclass BlackBoxAdder extends BlackBox with HasBlackBoxInline {\n val io = IO(new BlackBoxAdderIO).suggestName(\"io\")\n setInline(\n \"BlackBoxAdder.v\",\n \"\"\"module BlackBoxAdder(a, b, q);\n |input [7:0] a, b;\n |output [7:0] q;\n |assign q = a + b;\n |endmodule\n |\"\"\".stripMargin\n )\n}\n\nclass BlackBoxAdderWrapper extends Module {\n val io = IO(new BlackBoxAdderIO)\n val m = Module(new BlackBoxAdder)\n m.io <> io\n}\n\n// Inspired by plusarg_reader in rocket-chip\nclass PlusArgReader extends BlackBox with HasBlackBoxInline {\n val io = IO(new Bundle {\n val out = Output(UInt(32.W))\n })\n setInline(\n \"PlusArgReader.v\",\n \"\"\"module PlusArgReader(\n | output [31:0] out\n |);\n | reg [32:0] argument;\n | assign out = argument;\n | initial begin\n | if (!$value$plusargs(\"ARGUMENT=%d\", argument)) begin\n | argument = 32'hdeadbeef;\n | end\n | end\n |endmodule\n |\"\"\".stripMargin\n )\n}\n\n", "right_context": " val annos = Seq(IcarusBackendAnnotation)\n\n it should \"support IcarusVerilog black boxes\" taggedAs RequiresIcarus in {\n val rand = new Random()\n val mask = (BigInt(1) << 8) - 1\n test(new BlackBoxAdderWrapper).withAnnotations(annos) { dut =>\n (0 until 1000).foreach { ii =>\n val a = BigInt(8, rand)\n val b = BigInt(8, rand)\n val q = (a + b) & mask\n dut.io.a.poke(a.U)\n dut.io.b.poke(b.U)\n dut.io.q.expect(q.U)\n }\n }\n }\n\n it should \"support reading IcarusVerilog plusargs\" taggedAs RequiresIcarus in {\n for (plusarg <- List(0, 123, 456)) {\n val allAnnos = annos :+ PlusArgsAnnotation(s\"+ARGUMENT=$plusarg\" :: Nil)\n test(new PlusArgReaderWrapper(plusarg)).withAnnotations(allAnnos) { dut =>\n dut.reset.poke(true.B)\n dut.clock.step()\n dut.reset.poke(false.B)\n dut.clock.step()\n }\n }\n }\n}\n", "groundtruth": "class PlusArgReaderWrapper(expected: Int) extends Module {\n val reader = Module(new PlusArgReader)\n val msg = s\"Expected $expected, got %x.\\n\" // this works around the fact that s\"..\" is forbidden in the assert\n assert(reader.io.out === expected.U, msg, reader.io.out)\n}\n", "crossfile_context": ""}
{"task_id": "chiseltest", "path": "chiseltest/src/test/scala/chiseltest/formal/MagicPacketTrackerTests.scala", "left_context": "package chiseltest.formal\n\nimport chisel3._\nimport chisel3.util._\nimport chiseltest._\nimport firrtl2.AnnotationSeq\nimport org.scalatest.flatspec.AnyFlatSpec\n\nclass MagicPacketTrackerTests extends AnyFlatSpec with ChiselScalatestTester with Formal with FormalBackendOption {\n behavior.of(\"MagicPacketTracker\")\n\n private def defaultOptions: AnnotationSeq = Seq(BoundedCheck(7), DefaultBackend)\n private val DefaultDepth = 3\n private val DefaultDepthPow2 = 4 // some queues only work with power of two\n\n it should \"notice if the counter overflows\" taggedAs FormalTag in {\n assume(DefaultBackend != CVC4EngineAnnotation, \"CVC4 is too slow with some of these tests (5h+)\")\n // counter overflows can happen if the user specified a depth that is too small\n val e = intercept[FailedBoundedCheckException] {\n verify(new PacketTrackerCounterOverflowTest, Seq(BoundedCheck(16), DefaultBackend))\n }\n assert(e.failAt == 3) // without the overflow check, this fails at 4\n }\n\n it should \"verify the BubbleFifo\" taggedAs FormalTag in {\n assume(DefaultBackend != CVC4EngineAnnotation, \"CVC4 is too slow with some of these tests (5h+)\")\n verify(new FifoTestWrapper(new BubbleFifo(UInt(16.W), 4)), defaultOptions)\n }\n\n it should \"verify QueueV0\" taggedAs FormalTag in {\n assume(DefaultBackend != CVC4EngineAnnotation, \"CVC4 is too slow with some of these tests (5h+)\")\n verify(new QueueFormalTest(new MyQueueV0(32)), defaultOptions)\n }\n\n it should \"verify QueueV1\" taggedAs FormalTag in {\n assume(DefaultBackend != CVC4EngineAnnotation, \"CVC4 is too slow with some of these tests (5h+)\")\n verify(new QueueFormalTest(new MyQueueV1(DefaultDepth, 32)), defaultOptions)\n }\n\n it should \"find bug in QueueV2\" taggedAs FormalTag in {\n assume(DefaultBackend != CVC4EngineAnnotation, \"CVC4 is too slow with some of these tests (5h+)\")\n val e = intercept[FailedBoundedCheckException] {\n verify(new QueueFormalTest(new MyQueueV2(DefaultDepth, 32)), defaultOptions)\n }\n assert(e.failAt == 3)\n }\n\n it should \"verify QueueV3\" taggedAs FormalTag in {\n assume(DefaultBackend != CVC4EngineAnnotation, \"CVC4 is too slow with some of these tests (5h+)\")\n verify(new QueueFormalTest(new MyQueueV3(DefaultDepthPow2, 32)), defaultOptions)\n }\n\n it should \"verify QueueV4\" taggedAs FormalTag in {\n assume(DefaultBackend != CVC4EngineAnnotation, \"CVC4 is too slow with some of these tests (5h+)\")\n verify(new QueueFormalTest(new MyQueueV4(DefaultDepthPow2, 32)), defaultOptions)\n }\n\n it should \"verify QueueV5\" taggedAs FormalTag in {\n assume(DefaultBackend != CVC4EngineAnnotation, \"CVC4 is too slow with some of these tests (5h+)\")\n verify(new QueueFormalTest(new MyQueueV5(DefaultDepthPow2, 32)), defaultOptions)\n }\n\n it should \"find bug in QueueV6 w/ pipe = false\" taggedAs FormalTag in {\n assume(DefaultBackend != CVC4EngineAnnotation, \"CVC4 is too slow with some of these tests (5h+)\")\n val e = intercept[FailedBoundedCheckException] {\n verify(new QueueFormalTest(new MyQueueV6(DefaultDepth, 32, pipe = false, fixed = false)), defaultOptions)\n }\n assert(e.failAt == 3)\n }\n\n it should \"verify fix for QueueV6 w/ pipe = false\" taggedAs FormalTag in {\n assume(DefaultBackend != CVC4EngineAnnotation, \"CVC4 is too slow with some of these tests (5h+)\")\n verify(new QueueFormalTest(new MyQueueV6(DefaultDepth, 32, pipe = false, fixed = true)), defaultOptions)\n }\n\n it should \"find bug in QueueV6 w/ pipe = true\" taggedAs FormalTag in {\n assume(DefaultBackend != CVC4EngineAnnotation, \"CVC4 is too slow with some of these tests (5h+)\")\n val e = intercept[FailedBoundedCheckException] {\n verify(new QueueFormalTest(new MyQueueV6(DefaultDepth, 32, pipe = true, fixed = false)), defaultOptions)\n }\n assert(e.failAt == 2)\n }\n\n it should \"verify fix for QueueV6 w/ pipe = true\" taggedAs FormalTag in {\n assume(DefaultBackend != CVC4EngineAnnotation, \"CVC4 is too slow with some of these tests (5h+)\")\n verify(new QueueFormalTest(new MyQueueV6(DefaultDepth, 32, pipe = true, fixed = true)), defaultOptions)\n }\n\n it should \"verify some versions of the Queue from the Chisel standard library\" taggedAs FormalTag in {\n assume(DefaultBackend != CVC4EngineAnnotation, \"CVC4 is too slow with some of these tests (5h+)\")\n verify(new ChiselQueueTest(DefaultDepth, 32, false, false), defaultOptions)\n verify(new ChiselQueueTest(DefaultDepth, 32, false, true), defaultOptions)\n verify(new ChiselQueueTest(DefaultDepth, 32, true, false), defaultOptions)\n verify(new ChiselQueueTest(DefaultDepth, 32, true, true), defaultOptions)\n }\n}\n\nprivate class PacketTrackerCounterOverflowTest extends Module {\n // our queue can take up to 8 elements\n val dut = Module(new Queue(UInt(32.W), 8))\n val io = IO(chiselTypeOf(dut.io)); io <> dut.io\n // however for some reason we misconfigure the depth of the tracker\n MagicPacketTracker(enq = dut.io.enq, deq = dut.io.deq, depth = 3)\n}\n\n// very similar to the QueueSpec in the chisel3 tests, but a formal test\nprivate class ChiselQueueTest(queueDepth: Int, bitWidth: Int, useSyncReadMem: Boolean, hasFlush: Boolean)\n extends Module {\n val dut = Module(new Queue(UInt(bitWidth.W), queueDepth, useSyncReadMem = useSyncReadMem, hasFlush = hasFlush))\n val io = IO(chiselTypeOf(dut.io)); io <> dut.io\n // we need to tie the flush pin to false, because the MagicPacketTracker cannot (currently)\n // handle flushes, it will complain about a missing packet if a flush happens\n dut.io.flush.foreach(_ := false.B)\n MagicPacketTracker(enq = dut.io.enq, deq = dut.io.deq, depth = queueDepth)\n}\n\n// FIFOs from https://github.com/freechipsproject/ip-contributions\n\nprivate class FifoTestWrapper(fifo: => Fifo[UInt]) extends Module {\n val dut = Module(fifo)\n val io = IO(chiselTypeOf(dut.io)); io <> dut.io\n MagicPacketTracker(enq = dut.io.enq, deq = dut.io.deq, depth = dut.depth)\n}\n\n/** FIFO IO with enqueue and dequeue ports using the ready/valid interface.\n */\nprivate class FifoIO[T <: Data](private val gen: T) extends Bundle {\n val enq = Flipped(new DecoupledIO(gen))\n val deq = new DecoupledIO(gen)\n}\n\n/** Base class for all FIFOs.\n */\nprivate abstract class Fifo[T <: Data](gen: T, val depth: Int) extends Module {\n val io = IO(new FifoIO(gen))\n\n assert(depth > 0, \"Number of buffer elements needs to be larger than 0\")\n}\n\n/** A simple bubble FIFO. Maximum throughput is one word every two clock cycles.\n */\nprivate class BubbleFifo[T <: Data](gen: T, depth: Int) extends Fifo(gen: T, depth: Int) {\n\n private class Buffer() extends Module {\n val io = IO(new FifoIO(gen))\n\n val fullReg = RegInit(false.B)\n val dataReg = Reg(gen)\n\n when(fullReg) {\n when(io.deq.ready) {\n fullReg := false.B\n }\n }.otherwise {\n when(io.enq.valid) {\n fullReg := true.B\n dataReg := io.enq.bits\n }\n }\n\n io.enq.ready := !fullReg\n io.deq.valid := fullReg\n io.deq.bits := dataReg\n }\n\n private val buffers = Array.fill(depth) { Module(new Buffer()) }\n for (i <- 0 until depth - 1) {\n buffers(i + 1).io.enq <> buffers(i).io.deq\n }\n\n io.enq <> buffers(0).io.enq\n io.deq <> buffers(depth - 1).io.deq\n}\n\n///////////////////////////////////////////////////////\n// Queues from Scott Beamer's agile hardware lectures\n///////////////////////////////////////////////////////\n\nprivate class QueueFormalTest(makeQueue: => IsQueue) extends Module {\n val dut = Module(makeQueue)\n val io = IO(chiselTypeOf(dut.io)); io <> dut.io\n MagicPacketTracker(enq = dut.io.enq, deq = dut.io.deq, depth = dut.numEntries, debugPrint = false)\n}\n\nprivate trait IsQueue extends Module {\n def io: QueueIO\n def numEntries: Int\n}\n\nprivate class QueueIO(bitWidth: Int) extends Bundle {\n val enq = Flipped(Decoupled(UInt(bitWidth.W)))\n val deq = Decoupled(UInt(bitWidth.W))\n}\n\nprivate class MyQueueV0(bitWidth: Int) extends Module with IsQueue {\n override val numEntries = 1\n val io = IO(new QueueIO(bitWidth))\n val entry = Reg(UInt(bitWidth.W))\n val full = RegInit(false.B)\n io.enq.ready := !full || io.deq.fire\n io.deq.valid := full\n io.deq.bits := entry\n when(io.deq.fire) {\n full := false.B\n }\n when(io.enq.fire) {\n entry := io.enq.bits\n full := true.B\n }\n}\n\nprivate class MyQueueV1(val numEntries: Int, bitWidth: Int) extends Module with IsQueue {\n val io = IO(new QueueIO(bitWidth))\n require(numEntries > 0)\n // enqueue into index numEntries-1 (last) and dequeue from index 0 (head)\n val entries = Seq.fill(numEntries)(Reg(UInt(bitWidth.W)))\n val fullBits = Seq.fill(numEntries)(RegInit(false.B))\n val shiftDown = io.deq.fire || !fullBits.head\n io.enq.ready := !fullBits.last || shiftDown\n io.deq.valid := fullBits.head\n io.deq.bits := entries.head\n when(shiftDown) { // dequeue / shift\n for (i <- 0 until numEntries - 1) {\n entries(i) := entries(i + 1)\n fullBits(i) := fullBits(i + 1)\n }\n fullBits.last := false.B\n }\n when(io.enq.fire) { // enqueue\n entries.last := io.enq.bits\n fullBits.last := true.B\n }\n // when (shiftDown || io.enq.fire) {\n // entries.foldRight(io.enq.bits){(thisEntry, lastEntry) => thisEntry := lastEntry; thisEntry}\n // fullBits.foldRight(io.enq.fire){(thisEntry, lastEntry) => thisEntry := lastEntry; thisEntry}\n //\n}\n\nprivate class MyQueueV2(val numEntries: Int, bitWidth: Int) extends Module with IsQueue {\n val io = IO(new QueueIO(bitWidth))\n require(numEntries > 0)\n // enqueue into lowest empty and dequeue from index 0 (head)\n val entries = Reg(Vec(numEntries, UInt(bitWidth.W)))\n val fullBits = RegInit(VecInit(Seq.fill(numEntries)(false.B)))\n val emptyBits = fullBits.map { !_ }\n", "right_context": " io.deq.valid := fullBits.head\n io.deq.bits := entries.head\n when(io.deq.fire) { // dequeue & shift up\n for (i <- 0 until numEntries - 1) {\n entries(i) := entries(i + 1)\n fullBits(i) := fullBits(i + 1)\n }\n fullBits.last := false.B\n }\n when(io.enq.fire) { // priority enqueue\n val writeIndex = PriorityEncoder(emptyBits)\n entries(writeIndex) := io.enq.bits\n fullBits(writeIndex) := true.B\n }\n}\n\nprivate class MyQueueV3(val numEntries: Int, bitWidth: Int) extends Module with IsQueue {\n val io = IO(new QueueIO(bitWidth))\n require(numEntries > 1)\n require(isPow2(numEntries))\n val entries = Reg(Vec(numEntries, UInt(bitWidth.W))) // Mem?\n val enqIndex = RegInit(0.U(log2Ceil(numEntries).W))\n val deqIndex = RegInit(0.U(log2Ceil(numEntries).W))\n val empty = enqIndex === deqIndex\n val full = (enqIndex +% 1.U) === deqIndex\n io.enq.ready := !full\n io.deq.valid := !empty\n io.deq.bits := entries(deqIndex)\n when(io.deq.fire) {\n deqIndex := deqIndex +% 1.U\n }\n when(io.enq.fire) {\n entries(enqIndex) := io.enq.bits\n enqIndex := enqIndex +% 1.U\n }\n}\n\nprivate class MyQueueV4(val numEntries: Int, bitWidth: Int) extends Module with IsQueue {\n val io = IO(new QueueIO(bitWidth))\n require(numEntries > 1)\n require(isPow2(numEntries))\n val entries = Reg(Vec(numEntries, UInt(bitWidth.W)))\n val enqIndex = RegInit(0.U(log2Ceil(numEntries).W))\n val deqIndex = RegInit(0.U(log2Ceil(numEntries).W))\n val maybeFull = RegInit(false.B)\n val empty = enqIndex === deqIndex && !maybeFull\n val full = enqIndex === deqIndex && maybeFull\n io.enq.ready := !full\n io.deq.valid := !empty\n io.deq.bits := entries(deqIndex)\n when(io.deq.fire) {\n deqIndex := deqIndex +% 1.U\n when(enqIndex =/= deqIndex) {\n maybeFull := false.B\n }\n }\n when(io.enq.fire) {\n entries(enqIndex) := io.enq.bits\n enqIndex := enqIndex +% 1.U\n when((enqIndex +% 1.U) === deqIndex) {\n maybeFull := true.B\n }\n }\n}\n\nprivate class MyQueueV5(val numEntries: Int, bitWidth: Int) extends Module with IsQueue {\n val io = IO(new QueueIO(bitWidth))\n require(numEntries > 1)\n require(isPow2(numEntries))\n val entries = Reg(Vec(numEntries, UInt(bitWidth.W)))\n val enqIndex = RegInit(0.U(log2Ceil(numEntries).W))\n val deqIndex = RegInit(0.U(log2Ceil(numEntries).W))\n val maybeFull = RegInit(false.B)\n val empty = enqIndex === deqIndex && !maybeFull\n val full = enqIndex === deqIndex && maybeFull\n io.enq.ready := !full || io.deq.ready // NOTE: io.enq.ready now attached to io.deq.ready\n io.deq.valid := !empty\n io.deq.bits := entries(deqIndex)\n when(io.deq.fire) {\n deqIndex := deqIndex +% 1.U\n when(enqIndex =/= deqIndex) {\n maybeFull := false.B\n }\n }\n when(io.enq.fire) {\n entries(enqIndex) := io.enq.bits\n enqIndex := enqIndex +% 1.U\n when((enqIndex +% 1.U) === deqIndex) {\n maybeFull := true.B\n }\n }\n}\n\nprivate class MyQueueV6(val numEntries: Int, bitWidth: Int, pipe: Boolean, fixed: Boolean) extends Module with IsQueue {\n val io = IO(new QueueIO(bitWidth))\n require(numEntries > 1)\n // require(isPow2(numEntries)) // no longer needed\n val entries = Mem(numEntries, UInt(bitWidth.W))\n val enqIndex = Counter(numEntries)\n val deqIndex = Counter(numEntries)\n val maybeFull = RegInit(false.B)\n val indicesEqual = enqIndex.value === deqIndex.value\n val empty = indicesEqual && !maybeFull\n val full = indicesEqual && maybeFull\n if (pipe)\n io.enq.ready := !full || io.deq.ready\n else\n io.enq.ready := !full\n io.deq.valid := !empty\n io.deq.bits := entries(deqIndex.value)\n if (fixed) {\n when(io.deq.fire =/= io.enq.fire) {\n maybeFull := io.enq.fire\n }\n } else {\n when(indicesEqual && io.deq.fire =/= io.enq.fire) {\n maybeFull := !maybeFull\n }\n }\n when(io.deq.fire) {\n deqIndex.inc()\n }\n when(io.enq.fire) {\n entries(enqIndex.value) := io.enq.bits\n enqIndex.inc()\n }\n}\n", "groundtruth": " io.enq.ready := emptyBits.reduce { _ || _ } // any empties?\n", "crossfile_context": ""}
{"task_id": "chiseltest", "path": "chiseltest/src/test/scala/chiseltest/formal/examples/SvaDemos.scala", "left_context": "// SPDX-License-Identifier: Apache-2.0\n\npackage chiseltest.formal.examples\n\nimport chisel3._\nimport chisel3.util._\nimport chisel3.experimental.{annotate, ChiselAnnotation}\nimport chiseltest._\nimport chiseltest.formal._\nimport org.scalatest.flatspec.AnyFlatSpec\nimport chiseltest.formal.FormalTag\n\n/** These small examples demonstrate how the chisel Past operator can be used to emulate simple SVA constructs. All\n * demos are based on the awesome SVA tutorial from SymbioticEDA: https://github.com/SymbioticEDA/sva-demos\n */\nclass SvaDemos extends AnyFlatSpec with ChiselScalatestTester with Formal with FormalBackendOption {\n \"Demo1\" should \"fail a bounded check 17 cycles after reset\" taggedAs FormalTag in {\n val e = intercept[FailedBoundedCheckException] {\n verify(new SvaDemo1, Seq(BoundedCheck(20), DefaultBackend))\n }\n assert(e.failAt == 17)\n }\n\n Seq(\"A\" -> (() => new SvaDemo2), \"B\" -> (() => new SvaDemo2B), \"C\" -> (() => new SvaDemo2C)).foreach {\n case (n, gen) =>\n s\"Demo2$n\" should \"fail a bounded check 15 cycles after reset\" taggedAs FormalTag in {\n val e = intercept[FailedBoundedCheckException] {\n verify(gen(), Seq(BoundedCheck(20), DefaultBackend))\n }\n assert(e.failAt == 15)\n }\n }\n\n \"Demo3\" should \"fail a bounded check 16 cycles after reset\" taggedAs FormalTag in {\n val e = intercept[FailedBoundedCheckException] {\n verify(new SvaDemo3, Seq(BoundedCheck(20), DefaultBackend))\n }\n assert(e.failAt == 16)\n }\n}\n\nclass SvaDemo1 extends SvaDemoModule {\n seqs(\n // 01234567890123456789\n reset = \"-_____-____-________\",\n a = \"_--___-___-______-__\",\n b = \"__--__-__________-__\"\n )\n\n // we can replace the a |=> b with our past operator\n when(past(a)) { assert(b) }\n}\n\nclass SvaDemo2 extends SvaDemoModule {\n seqs(\n // 0123456789012345678901\n reset = \"-_____-_______________\",\n a = \"_-____-_______-_______\",\n b = \"___-__-__________-____\"\n )\n\n // we need to manually express the two different possibilities\n assert(IfThen(past(a, 2), b) || past(IfThen(past(a), b)))\n}\n\n/** This version changes the trace to test the (allowed) possibility of b going high the cycle after a */\nclass SvaDemo2B extends SvaDemoModule {\n seqs(\n // 0123456789012345678901\n reset = \"-_____-_______________\",\n a = \"_-____-___-___-_______\",\n b = \"___-__-____-_____-____\"\n )\n\n // we need to manually express the two different possibilities\n assert(IfThen(past(a, 2), b) || past(IfThen(past(a), b)))\n}\n\n/** This version shows that b can be high independent from a */\nclass SvaDemo2C extends SvaDemoModule {\n seqs(\n // 0123456789012345678901\n reset = \"-_____-_______________\",\n a = \"_-____-_______-_______\",\n b = \"---------------__-----\"\n )\n\n // we need to manually express the two different possibilities\n // assert property (a |-> ##[1:2] b);\n assert(IfThen(past(a, 2), b) || past(IfThen(past(a), b)))\n}\n\nclass SvaDemo3 extends SvaDemoModule {\n seqs(\n // 0123456789012345678901\n reset = \"-_______-___________\",\n a = \"_--___-_______-_____\",\n b = \"__--___-________--__\",\n c = \"____-_____________-_\"\n )\n\n // we need to manually express the property\n // note that our translation will fail 2 cycles later than the original\n // assert property ($rose(a) |=> b[*2] ##1 c);\n when(past(rose(a), 3)) {\n assert(past(b, 2) && past(b) && c)\n }\n}\n\nclass SvaDemoModule extends Module {\n private val preset = IO(Input(AsyncReset()))\n annotateAsPreset(preset.toTarget)\n private def seq(values: String): Bool = {\n withReset(preset) {\n require(values.forall(c => c == '_' || c == '-'), s\"$values contains invalid characters\")\n val (counter, wrap) = Counter(true.B, values.length + 1)\n val bools = VecInit(values.map(c => (c == '-').B))\n bools(counter)\n }\n }\n val (a, b, c) = (WireInit(false.B), WireInit(false.B), WireInit(false.B))\n def seqs(reset: String, a: String, b: String, c: String = \"\"): Unit = {\n seqs_p(reset, a, b, c)\n }\n private def seqs_p(rStr: String, aStr: String, bStr: String, cStr: String): Unit = {\n val r = seq(rStr)\n withReset(false.B) {\n assume(reset.asBool === r)\n }\n if (aStr.nonEmpty) a := seq(aStr)\n if (bStr.nonEmpty) b := seq(bStr)\n", "right_context": " }\n}\n\nobject IfThen {\n def apply(if_clause: Bool, then_clause: Bool): Bool = !if_clause || then_clause\n}\n", "groundtruth": " if (cStr.nonEmpty) c := seq(cStr)\n", "crossfile_context": ""}
{"task_id": "chiseltest", "path": "chiseltest/src/test/scala/chiseltest/iotesters/examples/GCDCalculator.scala", "left_context": "// SPDX-License-Identifier: Apache-2.0\n\npackage chiseltest.iotesters.examples\n\nimport scala.annotation.tailrec\n\nobject GCDCalculator {\n @tailrec\n def computeGcdResultsAndCycles(a: Int, b: Int, depth: Int = 1): (Int, Int) = {\n if (b == 0) {\n (a, depth)\n", "right_context": "", "groundtruth": " } else {\n computeGcdResultsAndCycles(b, a % b, depth + 1)\n }\n", "crossfile_context": ""}
{"task_id": "chiseltest", "path": "chiseltest/src/test/scala/chiseltest/iotesters/examples/SecondClockDrivesRegisterSpec.scala", "left_context": "// SPDX-License-Identifier: Apache-2.0\n\npackage chiseltest.iotesters.examples\n\nimport chisel3._\nimport chiseltest.iotesters._\nimport chisel3.util.Counter\nimport chiseltest.{ChiselScalatestTester, VerilatorBackendAnnotation}\nimport chiseltest.simulator.RequiresVerilator\nimport org.scalatest.freespec.AnyFreeSpec\n\nclass SecondClockDrivesRegisterSpec extends AnyFreeSpec with ChiselScalatestTester {\n class SecondClock extends Module {\n val inClock = IO(Input(Bool()))\n val out = IO(Output(UInt(8.W)))\n\n withClock(inClock.asClock) {\n out := Counter(true.B, 8)._1\n }\n }\n\n class SecondClockTester(c: SecondClock) extends PeekPokeTester(c) {\n poke(c.inClock, 0)\n expect(c.out, 0)\n\n // Main clock should do nothing\n step(1)\n expect(c.out, 0)\n step(1)\n expect(c.out, 0)\n\n // Output should advance on rising edge, even without main clock edge\n poke(c.inClock, 1)\n expect(c.out, 1)\n\n step(1)\n expect(c.out, 1)\n\n // Repeated, 1should do nothing\n poke(c.inClock, 1)\n expect(c.out, 1)\n\n // and again\n poke(c.inClock, 0)\n expect(c.out, 1)\n poke(c.inClock, 1)\n expect(c.out, 2)\n }\n\n \"poking a clock should flip register\" - {\n\n", "right_context": " test(new SecondClock).withAnnotations(Seq(VerilatorBackendAnnotation)).runPeekPoke(new SecondClockTester(_))\n }\n }\n}\n", "groundtruth": " \"should work with Treadle\" in {\n test(new SecondClock).runPeekPoke(new SecondClockTester(_))\n }\n", "crossfile_context": ""}
{"task_id": "chiseltest", "path": "chiseltest/src/test/scala/chiseltest/simulator/WaveformCompliance.scala", "left_context": "// SPDX-License-Identifier: Apache-2.0\n\npackage chiseltest.simulator\n\nimport firrtl2.AnnotationSeq\nimport org.scalatest.Tag\n\nimport java.nio.ByteBuffer\n\n/** tests the waveform dumping abilities of a simulator */\nabstract class WaveformCompliance(sim: Simulator, tag: Tag = DefaultTag) extends ComplianceTest(sim, tag) {\n\n private val testSrc =\n \"\"\"circuit Foo :\n | module Child :\n | input clock : Clock\n | input reset : UInt<1>\n | output io : { flip in : UInt<1>, out : UInt<1>}\n |\n | reg r : UInt<1>, clock with :\n | reset => (reset, UInt(0))\n | r <= io.in\n | io.out <= r\n |\n | module Foo :\n | input clock : Clock\n | input reset : UInt<1>\n | output io : { flip in : UInt<1>, out : UInt<1>}\n |\n | node _io_out_T = not(io.in) @[main.scala 12:13]\n | inst c of Child\n | c.clock <= clock\n | c.reset <= reset\n | c.io.in <= _io_out_T @[main.scala 12:10]\n | io.out <= c.io.out\n |\"\"\".stripMargin\n\n val waveformExtensions = Set(\"vcd\", \"txt\", \"fst\", \"vpd\", \"lxt\", \"lxt2\", \"fsdb\")\n it should \"not create a waveform file when no WriteWaveformAnnotation is provided\" taggedAs (tag) in {\n performDutTest(Seq())\n val dumps = testDirFiles().filter(f => waveformExtensions.contains(f.last.split('.').last))\n assert(dumps.isEmpty, s\"Found waveform dump files $dumps even though no WriteWaveformAnnotation was provided!\")\n }\n\n sim.waveformFormats.foreach { anno =>\n val format = anno.format\n it should s\"generate a $format waveform dump at the end of simulation\" taggedAs (tag) in {\n performDutTest(Seq(anno))\n val dumpFile = targetDir / (\"Foo.\" + format)\n checkWavedump(dumpFile, format)\n }\n }\n\n // performs some sanity checks on a given waveform\n private def checkWavedump(file: os.Path, format: String): Unit = {\n assert(os.exists(file) && os.isFile(file), s\"Waveform dump $file does not exist!\")\n\n format match {\n case \"vcd\" =>\n // the VCD format is a text file that will contain some keyword we can search for\n val txt = os.read(file)\n assert(txt.contains(\"$version\"))\n assert(txt.contains(\"$scope\"))\n assert(txt.contains(\"$enddefinitions\"))\n case \"lxt\" =>\n // the LXT format has a characteristic header ID followed by the version number\n // lt_emit_u16(lt, LT_HDRID); // #define LT_HDRID (0x0138)\n // lt_emit_u16(lt, LT_VERSION); // #define LT_VERSION (0x0004)\n val bb = ByteBuffer.wrap(os.read.bytes(file))\n assert(bb.getShort == 0x0138)\n val version = bb.getShort\n assert(version == 4) // TODO: potentially relax this version requirement\n case \"lxt2\" =>\n // the LXT2 format has a characteristic header ID followed by the version number\n // lxt2_wr_emit_u16(lt, LXT2_WR_HDRID); // #define LXT2_WR_HDRID (0x1380)\n // lxt2_wr_emit_u16(lt, LXT2_WR_VERSION); // #define LXT2_WR_VERSION (0x0001)\n // lxt2_wr_emit_u8 (lt, LXT2_WR_GRANULE_SIZE);\t/* currently 32 or 64 */\n val bb = ByteBuffer.wrap(os.read.bytes(file))\n assert(bb.getShort == 0x1380)\n val version = bb.getShort\n val granule_size = bb.get()\n assert(granule_size == 32 || granule_size == 64)\n assert(version == 1) // TODO: potentially relax this version requirement\n case \"fst\" =>\n // we look for characteristic header bytes defined in `fstWriterEmitHdrBytes`\n val bb = ByteBuffer.wrap(os.read.bytes(file))\n // fstBlockType: FST_BL_HDR = 0\n assert(bb.get() == 0)\n // section length is hard coded to 329\n assert(bb.getLong() == 329)\n case \"vpd\" =>\n val txt = os.read(file).toString.take(3)\n assert(txt.startsWith(\"xV4\"))\n case \"fsdb\" =>\n val txt = os.read(file)\n assert(txt.contains(\"FSDB Writer\"))\n assert(txt.contains(\"finish\"))\n case other => throw new NotImplementedError(s\"TODO: add code to check $other\")\n }\n }\n\n // perform some testing with the dut in order to generate interesting waveforms\n private def performDutTest(annos: AnnotationSeq): Unit = {\n val dut = load(testSrc, annos = annos)\n dut.poke(\"reset\", 1)\n dut.step()\n dut.poke(\"reset\", 0)\n assert(dut.peek(\"io_out\") == 0)\n val rand = new scala.util.Random(0)\n (0 until 50).foreach { _ =>\n val in = BigInt(1, rand)\n dut.poke(\"io_in\", in)\n dut.step()\n assert(dut.peek(\"io_out\") == ((~in) & 1))\n }\n dut.step()\n dut.finish()\n }\n\n", "right_context": "}\n", "groundtruth": " private def testDirFiles(): Seq[os.Path] = os.list(targetDir).filter(os.isFile)\n", "crossfile_context": ""}
{"task_id": "XiangShan", "path": "XiangShan/src/main/scala/top/Generator.scala", "left_context": "/***************************************************************************************\n* Copyright (c) 2024 Beijing Institute of Open Source Chip (BOSC)\n* Copyright (c) 2020-2024 Institute of Computing Technology, Chinese Academy of Sciences\n* Copyright (c) 2020-2021 Peng Cheng Laboratory\n*\n* XiangShan is licensed under Mulan PSL v2.\n* You can use this software according to the terms and conditions of the Mulan PSL v2.\n* You may obtain a copy of Mulan PSL v2 at:\n* http://license.coscl.org.cn/MulanPSL2\n*\n* THIS SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS, WITHOUT WARRANTIES OF ANY KIND,\n* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,\n* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.\n*\n* See the Mulan PSL v2 for more details.\n***************************************************************************************/\n\npackage top\n\nimport circt.stage._\nimport chisel3.stage.ChiselGeneratorAnnotation\nimport xiangshan.transforms._\n\nobject Generator {\n", "right_context": "", "groundtruth": " def execute(args: Array[String], mod: => chisel3.RawModule, firtoolOpts: Array[String]) = {\n val annotations = firtoolOpts.map(FirtoolOption.apply).toSeq\n\n (new XiangShanStage).execute(args, ChiselGeneratorAnnotation(() => mod) +: annotations)\n }\n", "crossfile_context": ""}
{"task_id": "XiangShan", "path": "XiangShan/src/main/scala/xiangshan/backend/decode/VecExceptionGen.scala", "left_context": "package xiangshan.backend.decode\n\nimport org.chipsalliance.cde.config.Parameters\nimport chisel3._\nimport chisel3.util._\nimport freechips.rocketchip.rocket.Instructions._\nimport freechips.rocketchip.util.uintToBitPat\nimport utility._\nimport utils._\nimport xiangshan._\nimport xiangshan.backend.Bundles.{DecodedInst, DynInst, StaticInst}\nimport xiangshan.backend.fu.FuType\nimport xiangshan.backend.fu.vector.Bundles._\nimport xiangshan.backend.decode.isa.bitfield.{InstVType, XSInstBitFields, OPCODE7Bit}\nimport xiangshan.backend.decode.Zvbb._\n\nobject RegNumNotAlign {\n", "right_context": "object NFtoLmul {\n def apply(nf: UInt): UInt = {\n LookupTree(nf, List(\n \"b000\".U -> 4.U,\n \"b001\".U -> 5.U,\n \"b011\".U -> 6.U,\n \"b111\".U -> 7.U\n ))\n }\n}\n\nobject LmultoRegNum {\n def apply(lmul: UInt): UInt = {\n val numPow = Mux(lmul(2).asBool, lmul(1, 0), 0.U(2.W))\n val regNum = 1.U << numPow\n regNum\n }\n}\n\nclass VecExceptionGen(implicit p: Parameters) extends XSModule{\n val io = IO(new Bundle(){\n val inst = Input(UInt(32.W))\n val decodedInst = Input(new DecodedInst)\n val vtype = Input(new VType)\n val vstart = Input(Vl())\n\n val illegalInst = Output(Bool())\n })\n\n private val inst: XSInstBitFields = io.inst.asTypeOf(new XSInstBitFields)\n private val isVArithMem = FuType.isVArithMem(io.decodedInst.fuType)\n private val isVArith = FuType.isVArith(io.decodedInst.fuType)\n private val isVset = FuType.isVset(io.decodedInst.fuType)\n\n private val SEW = io.vtype.vsew(1, 0)\n private val LMUL = Cat(~io.vtype.vlmul(2), io.vtype.vlmul(1, 0))\n\n private val lsStrideInst = Seq(\n VLE8_V, VLE16_V, VLE32_V, VLE64_V, VSE8_V, VSE16_V, VSE32_V, VSE64_V, \n VLSE8_V, VLSE16_V, VLSE32_V, VLSE64_V, VSSE8_V, VSSE16_V, VSSE32_V, VSSE64_V, \n VLE8FF_V, VLE16FF_V, VLE32FF_V, VLE64FF_V\n ).map(_ === inst.ALL).reduce(_ || _)\n\n private val lsMaskInst = Seq(\n VLM_V, VSM_V\n ).map(_ === inst.ALL).reduce(_ || _)\n\n private val lsIndexInst = Seq(\n VLUXEI8_V, VLUXEI16_V, VLUXEI32_V, VLUXEI64_V, VLOXEI8_V, VLOXEI16_V, VLOXEI32_V, VLOXEI64_V, \n VSUXEI8_V, VSUXEI16_V, VSUXEI32_V, VSUXEI64_V, VSOXEI8_V, VSOXEI16_V, VSOXEI32_V, VSOXEI64_V\n ).map(_ === inst.ALL).reduce(_ || _)\n\n private val lsWholeInst = Seq(\n VL1RE8_V, VL1RE16_V, VL1RE32_V, VL1RE64_V, \n VL2RE8_V, VL2RE16_V, VL2RE32_V, VL2RE64_V, \n VL4RE8_V, VL4RE16_V, VL4RE32_V, VL4RE64_V, \n VL8RE8_V, VL8RE16_V, VL8RE32_V, VL8RE64_V, \n VS1R_V, VS2R_V, VS4R_V, VS8R_V\n ).map(_ === inst.ALL).reduce(_ || _)\n\n private val vdWideningInst = Seq(\n //int\n VWADD_VV, VWADD_VX, VWADD_WV, VWADD_WX, VWADDU_VV, VWADDU_VX, VWADDU_WV, VWADDU_WX, \n VWMACC_VV, VWMACC_VX, VWMACCSU_VV, VWMACCSU_VX, VWMACCU_VV, VWMACCU_VX, VWMACCUS_VX, \n VWMUL_VV, VWMUL_VX, VWMULSU_VV, VWMULSU_VX, VWMULU_VV, VWMULU_VX, \n VWSUB_VV, VWSUB_VX, VWSUB_WV, VWSUB_WX, VWSUBU_VV, VWSUBU_VX, VWSUBU_WV, VWSUBU_WX, \n //fp\n VFWADD_VF, VFWADD_VV, VFWADD_WF, VFWADD_WV, VFWSUB_VF, VFWSUB_VV, VFWSUB_WF, VFWSUB_WV, \n VFWMUL_VF, VFWMUL_VV, \n VFWMACC_VF, VFWMACC_VV, VFWMSAC_VF, VFWMSAC_VV, VFWNMACC_VF, VFWNMACC_VV, VFWNMSAC_VF, VFWNMSAC_VV, \n VFWCVT_F_F_V, VFWCVT_F_X_V, VFWCVT_F_XU_V, VFWCVT_RTZ_X_F_V, VFWCVT_RTZ_XU_F_V, VFWCVT_X_F_V, VFWCVT_XU_F_V,\n // zvbb\n VWSLL_VV, VWSLL_VX, VWSLL_VI,\n ).map(_ === inst.ALL).reduce(_ || _)\n\n private val vs2WideningInst = Seq(\n //int\n VWADD_WV, VWADD_WX, VWADDU_WV, VWADDU_WX, \n VWSUB_WV, VWSUB_WX, VWSUBU_WV, VWSUBU_WX, \n //fp\n VFWADD_WF, VFWADD_WV, VFWSUB_WF, VFWSUB_WV\n ).map(_ === inst.ALL).reduce(_ || _)\n\n private val narrowingInst = Seq(\n //int\n VNCLIP_WI, VNCLIP_WV, VNCLIP_WX, VNCLIPU_WI, VNCLIPU_WV, VNCLIPU_WX, \n VNSRA_WI, VNSRA_WV, VNSRA_WX, VNSRL_WI, VNSRL_WV, VNSRL_WX, \n //fp\n VFNCVT_F_F_W, VFNCVT_F_X_W, VFNCVT_F_XU_W, VFNCVT_ROD_F_F_W, VFNCVT_RTZ_X_F_W, VFNCVT_RTZ_XU_F_W, VFNCVT_X_F_W, VFNCVT_XU_F_W\n ).map(_ === inst.ALL).reduce(_ || _)\n\n private val intExtInst = Seq(\n VSEXT_VF2, VSEXT_VF4, VSEXT_VF8, VZEXT_VF2, VZEXT_VF4, VZEXT_VF8\n ).map(_ === inst.ALL).reduce(_ || _)\n\n private val acsbInst = Seq(\n VMADC_VI, VMADC_VIM, VMADC_VV, VMADC_VVM, VMADC_VX, VMADC_VXM, \n VMSBC_VV, VMSBC_VVM, VMSBC_VX, VMSBC_VXM\n ).map(_ === inst.ALL).reduce(_ || _)\n\n private val cmpInst = Seq(\n //int\n VMSEQ_VI, VMSEQ_VV, VMSEQ_VX, \n VMSGT_VI, VMSGT_VX, VMSGTU_VI, VMSGTU_VX, \n VMSLE_VI, VMSLE_VV, VMSLE_VX, VMSLEU_VI, VMSLEU_VV, VMSLEU_VX, \n VMSLT_VV, VMSLT_VX, VMSLTU_VV, VMSLTU_VX, \n VMSNE_VI, VMSNE_VV, VMSNE_VX, \n //fp\n VMFEQ_VF, VMFEQ_VV, VMFNE_VF, VMFNE_VV, \n VMFGE_VF, VMFGT_VF, VMFLE_VF, VMFLE_VV, VMFLT_VF, VMFLT_VV\n ).map(_ === inst.ALL).reduce(_ || _)\n\n private val redInst = Seq(\n VREDAND_VS, VREDMAX_VS, VREDMAXU_VS, VREDMIN_VS, VREDMINU_VS, VREDOR_VS, VREDSUM_VS, VREDXOR_VS, \n VFREDMAX_VS, VFREDMIN_VS, VFREDOSUM_VS, VFREDUSUM_VS\n ).map(_ === inst.ALL).reduce(_ || _)\n\n private val redWideningInst = Seq(\n VWREDSUM_VS, VWREDSUMU_VS, \n VFWREDOSUM_VS, VFWREDUSUM_VS\n ).map(_ === inst.ALL).reduce(_ || _)\n\n private val maskLogicalInst = Seq(\n VMAND_MM, VMNAND_MM, VMANDN_MM, VMXOR_MM, VMOR_MM, VMNOR_MM, VMORN_MM, VMXNOR_MM\n ).map(_ === inst.ALL).reduce(_ || _)\n\n private val maskArithmeticInst = Seq(\n VCPOP_M, VFIRST_M, VMSBF_M, VMSIF_M, VMSOF_M\n ).map(_ === inst.ALL).reduce(_ || _) || maskLogicalInst\n\n private val maskIndexInst = Seq(\n VIOTA_M, VID_V\n ).map(_ === inst.ALL).reduce(_ || _)\n\n private val vmvSingleInst = Seq(\n VMV_X_S, VMV_S_X, VFMV_F_S, VFMV_S_F\n ).map(_ === inst.ALL).reduce(_ || _)\n\n private val vmvWholeInst = Seq(\n VMV1R_V, VMV2R_V, VMV4R_V, VMV8R_V\n ).map(_ === inst.ALL).reduce(_ || _)\n\n private val vrgather16 = VRGATHEREI16_VV === inst.ALL\n private val vcompress = VCOMPRESS_VM === inst.ALL\n private val intExt2 = Seq(VSEXT_VF2, VZEXT_VF2).map(_ === inst.ALL).reduce(_ || _)\n private val intExt4 = Seq(VSEXT_VF4, VZEXT_VF4).map(_ === inst.ALL).reduce(_ || _)\n private val intExt8 = Seq(VSEXT_VF8, VZEXT_VF8).map(_ === inst.ALL).reduce(_ || _)\n\n private val notDependVtypeInst = Seq(VSETVLI, VSETIVLI, VSETVL).map(_ === inst.ALL).reduce(_ || _) || lsWholeInst\n\n\n // 1. inst Illegal\n private val instIllegal = maskLogicalInst && inst.VM === 0.U\n\n // 2. vill Illegal\n private val villIllegal = io.vtype.illegal && isVArithMem && !notDependVtypeInst\n\n // 3. EEW Illegal\n private val doubleFpInst = Seq(\n VFWCVT_F_X_V, VFWCVT_F_XU_V, VFNCVT_RTZ_X_F_W, VFNCVT_RTZ_XU_F_W, VFNCVT_X_F_W, VFNCVT_XU_F_W\n ).map(_ === inst.ALL).reduce(_ || _)\n\n // funct3 of OPFVV is 001, funct3 of OPFVF is 101\n private val isFp = (inst.FUNCT3 === BitPat(\"b?01\")) && (inst.OPCODE7Bit === OPCODE7Bit.VECTOR_ARITH)\n private val fpEewIllegal = isFp && ((SEW === 0.U) && !doubleFpInst)\n\n private val intExtEewIllegal = intExt2 && SEW === 0.U ||\n intExt4 && SEW <= 1.U ||\n intExt8 && SEW <= 2.U\n\n private val wnEewIllegal = (vdWideningInst || narrowingInst || redWideningInst) && SEW === 3.U\n\n private val eewIllegal = fpEewIllegal || intExtEewIllegal || wnEewIllegal\n\n // 4. EMUL Illegal\n private val lsEmulIllegal = (lsStrideInst || lsIndexInst) && (LMUL +& inst.WIDTH(1, 0) < SEW +& 1.U || LMUL +& inst.WIDTH(1, 0) > SEW +& 7.U)\n\n private val intExtEmulIllegal = intExt2 && LMUL === 1.U ||\n intExt4 && LMUL <= 2.U ||\n intExt8 && LMUL <= 3.U\n\n private val wnEmulIllegal = (vdWideningInst || narrowingInst) && LMUL === 7.U\n\n private val gather16EmulIllegal = vrgather16 && (LMUL < SEW || LMUL > SEW +& 6.U)\n\n private val NFIELDS = inst.NF +& 1.U\n private val segEmul = Mux(lsIndexInst, LMUL, LMUL +& inst.WIDTH(1, 0) - SEW)\n private val emulNumPow = Mux(segEmul(2), segEmul(1, 0), 0.U(2.W))\n private val segRegNum = NFIELDS << emulNumPow\n private val segRegMax = inst.VD +& segRegNum\n\n private val lsSegIllegal = (lsStrideInst || lsIndexInst) && inst.NF =/= 0.U && (segRegNum > 8.U || segRegMax > 32.U)\n \n private val emulIllegal = lsEmulIllegal || intExtEmulIllegal || wnEmulIllegal || gather16EmulIllegal || lsSegIllegal\n\n // 5. Reg Number Align\n private val vs1IsMask = maskArithmeticInst || vcompress\n private val vs1IsSingleElem = redInst || redWideningInst\n private val vs1Eew = Mux(vrgather16, \"b01\".U, SEW)\n private val vs1Emul = Mux(vs1IsMask || vs1IsSingleElem, \"b100\".U, Mux(vrgather16, LMUL +& 1.U - SEW, LMUL))\n private val vs1NotAlign = SrcType.isVp(io.decodedInst.srcType(0)) && RegNumNotAlign(inst.VS1, vs1Emul)\n\n private val vs2IsMask = maskArithmeticInst || maskIndexInst\n private val vs2IsSingleElem = vmvSingleInst\n private val vs2EewSel = Cat(lsIndexInst, (vs2WideningInst || narrowingInst || redWideningInst), intExt2, intExt4, intExt8)\n private val vs2Eew = LookupTreeDefault(vs2EewSel, SEW, List(\n \"b10000\".U -> inst.WIDTH(1, 0),\n \"b01000\".U -> (SEW + 1.U),\n \"b00100\".U -> (SEW - 1.U),\n \"b00010\".U -> (SEW - 2.U),\n \"b00001\".U -> (SEW - 3.U)\n ))\n private val vs2EmulSel = Cat((vs2IsMask || vs2IsSingleElem), (vs2WideningInst || narrowingInst), vmvWholeInst, (intExtInst || lsIndexInst))\n private val vs2Emul = LookupTreeDefault(vs2EmulSel, LMUL, List(\n \"b1000\".U -> \"b100\".U,\n \"b0100\".U -> (LMUL + 1.U),\n \"b0010\".U -> NFtoLmul(inst.IMM5_OPIVI(2, 0)),\n \"b0001\".U -> (LMUL +& vs2Eew - SEW)\n ))\n private val vs2NotAlign = SrcType.isVp(io.decodedInst.srcType(1)) && RegNumNotAlign(inst.VS2, vs2Emul)\n\n private val vdIsMask = lsMaskInst || acsbInst || cmpInst || maskArithmeticInst\n private val vdIsSingleElem = redInst || redWideningInst || vmvSingleInst\n private val vdEew = Mux(lsStrideInst, inst.WIDTH(1, 0), Mux(vdWideningInst || redWideningInst, SEW + 1.U, SEW))\n private val vdEmulSel = Cat((vdIsMask || vdIsSingleElem), vdWideningInst, vmvWholeInst, lsWholeInst, lsStrideInst)\n private val vdEmul = LookupTreeDefault(vdEmulSel, LMUL, List(\n \"b10000\".U -> \"b100\".U,\n \"b01000\".U -> (LMUL + 1.U),\n \"b00100\".U -> NFtoLmul(inst.IMM5_OPIVI(2, 0)),\n \"b00010\".U -> NFtoLmul(inst.NF),\n \"b00001\".U -> (LMUL +& vdEew - SEW)\n ))\n private val vdNotAlign = (SrcType.isVp(io.decodedInst.srcType(2)) || io.decodedInst.vecWen) && RegNumNotAlign(inst.VD, vdEmul)\n\n private val regNumIllegal = isVArithMem && (vs1NotAlign || vs2NotAlign || vdNotAlign)\n\n // 6. v0 Overlap\n private val v0AllowOverlap = (vdIsMask || vdIsSingleElem) && !Seq(VMSBF_M, VMSIF_M, VMSOF_M).map(_ === inst.ALL).reduce(_ || _)\n private val v0Overlap = isVArithMem && io.decodedInst.vecWen && inst.VM === 0.U && inst.VD === 0.U && !v0AllowOverlap\n\n // 7. Src Reg Overlap\n private val vs1RegLo = inst.VS1\n private val vs1RegHi = inst.VS1 +& LmultoRegNum(vs1Emul) - 1.U\n private val vs2RegLo = inst.VS2\n private val vs2RegHi = inst.VS2 +& LmultoRegNum(vs2Emul) - 1.U\n private val vdRegLo = inst.VD\n private val vdRegHi = Mux(lsStrideInst || lsIndexInst, segRegMax - 1.U, inst.VD + LmultoRegNum(vdEmul) - 1.U)\n\n private val notAllowOverlapInst = lsIndexInst && inst.NF =/= 0.U || Seq(VMSBF_M, VMSIF_M, VMSOF_M, VIOTA_M, \n VSLIDEUP_VX, VSLIDEUP_VI, VSLIDE1UP_VX, VFSLIDE1UP_VF, VRGATHER_VV, VRGATHEREI16_VV, VRGATHER_VX, VRGATHER_VI, VCOMPRESS_VM).map(_ === inst.ALL).reduce(_ || _)\n\n // 8. vstart Illegal\n private val vstartIllegal = isVArith && (io.vstart =/= 0.U)\n\n //vs1\n private val vs1vdRegNotOverlap = vs1RegHi < vdRegLo || vdRegHi < vs1RegLo\n private val vs1Constraint1 = vs1IsMask && vdIsMask || !vs1IsMask && !vdIsMask && vs1Eew === vdEew\n private val vs1Constraint2 = (vdIsMask && !vs1IsMask || !vs1IsMask && !vdIsMask && vs1Eew > vdEew) && vdRegLo === vs1RegLo && vdRegHi <= vs1RegHi\n private val vs1Constraint3 = (!vdIsMask && vs1IsMask || !vs1IsMask && !vdIsMask && vs1Eew < vdEew) && vs1Emul >= \"b100\".U && vdRegHi === vs1RegHi && vdRegLo <= vs1RegLo\n private val vs1AllowOverlap = (vs1Constraint1 || vs1Constraint2 || vs1Constraint3 || vdIsSingleElem) && !notAllowOverlapInst\n private val vs1vdOverlap = (SrcType.isVp(io.decodedInst.srcType(0)) && io.decodedInst.vecWen) && !vs1vdRegNotOverlap && !vs1AllowOverlap\n //vs2\n private val vs2vdRegNotOverlap = vs2RegHi < vdRegLo || vdRegHi < vs2RegLo\n private val vs2Constraint1 = vs2IsMask && vdIsMask || !vs2IsMask && !vdIsMask && vs2Eew === vdEew\n private val vs2Constraint2 = (vdIsMask && !vs2IsMask || !vs2IsMask && !vdIsMask && vs2Eew > vdEew) && vdRegLo === vs2RegLo && vdRegHi <= vs2RegHi\n private val vs2Constraint3 = (!vdIsMask && vs2IsMask || !vs2IsMask && !vdIsMask && vs2Eew < vdEew) && vs2Emul >= \"b100\".U && vdRegHi === vs2RegHi && vdRegLo <= vs2RegLo\n private val vs2AllowOverlap = (vs2Constraint1 || vs2Constraint2 || vs2Constraint3 || vdIsSingleElem) && !notAllowOverlapInst\n private val vs2vdOverlap = (SrcType.isVp(io.decodedInst.srcType(1)) && io.decodedInst.vecWen) && !vs2vdRegNotOverlap && !vs2AllowOverlap\n\n private val regOverlapIllegal = v0Overlap || vs1vdOverlap || vs2vdOverlap\n\n io.illegalInst := instIllegal || villIllegal || eewIllegal || emulIllegal || regNumIllegal || regOverlapIllegal || vstartIllegal\n dontTouch(instIllegal)\n dontTouch(villIllegal)\n dontTouch(eewIllegal)\n dontTouch(emulIllegal)\n dontTouch(regNumIllegal)\n dontTouch(regOverlapIllegal)\n dontTouch(notDependVtypeInst)\n dontTouch(vstartIllegal)\n}", "groundtruth": " def apply(reg: UInt, emul: UInt): Bool = {\n emul === \"b101\".U && reg(0) =/= 0.U || emul === \"b110\".U && reg(1, 0) =/= 0.U || emul === \"b111\".U && reg(2, 0) =/= 0.U\n }\n", "crossfile_context": ""}
{"task_id": "XiangShan", "path": "XiangShan/src/main/scala/xiangshan/backend/fu/Alu.scala", "left_context": "/***************************************************************************************\n* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences\n* Copyright (c) 2020-2021 Peng Cheng Laboratory\n*\n* XiangShan is licensed under Mulan PSL v2.\n* You can use this software according to the terms and conditions of the Mulan PSL v2.\n* You may obtain a copy of Mulan PSL v2 at:\n* http://license.coscl.org.cn/MulanPSL2\n*\n* THIS SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS, WITHOUT WARRANTIES OF ANY KIND,\n* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,\n* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.\n*\n* See the Mulan PSL v2 for more details.\n***************************************************************************************/\n\npackage xiangshan.backend.fu\n\nimport org.chipsalliance.cde.config.Parameters\nimport chisel3._\nimport chisel3.util._\nimport utility.{LookupTree, LookupTreeDefault, ParallelMux, SignExt, XSDebug, ZeroExt}\nimport xiangshan._\n\nclass AddModule(implicit p: Parameters) extends XSModule {\n val io = IO(new Bundle() {\n val src = Vec(2, Input(UInt(XLEN.W)))\n val srcw = Input(UInt((XLEN/2).W))\n val add = Output(UInt(XLEN.W))\n val addw = Output(UInt((XLEN/2).W))\n })\n io.add := io.src(0) + io.src(1)\n // TODO: why this extra adder?\n io.addw := io.srcw + io.src(1)(31,0)\n}\n\nclass SubModule(implicit p: Parameters) extends XSModule {\n val io = IO(new Bundle() {\n val src = Vec(2, Input(UInt(XLEN.W)))\n val sub = Output(UInt((XLEN+1).W))\n })\n io.sub := (io.src(0) +& (~io.src(1)).asUInt) + 1.U\n}\n\nclass LeftShiftModule(implicit p: Parameters) extends XSModule {\n val io = IO(new Bundle() {\n val shamt = Input(UInt(6.W))\n val revShamt = Input(UInt(6.W))\n val sllSrc = Input(UInt(XLEN.W))\n val sll = Output(UInt(XLEN.W))\n val revSll = Output(UInt(XLEN.W))\n })\n io.sll := io.sllSrc << io.shamt\n io.revSll := io.sllSrc << io.revShamt\n}\n\nclass LeftShiftWordModule(implicit p: Parameters) extends XSModule {\n val io = IO(new Bundle() {\n val shamt = Input(UInt(5.W))\n val revShamt = Input(UInt(5.W))\n val sllSrc = Input(UInt((XLEN/2).W))\n val sllw = Output(UInt((XLEN/2).W))\n val revSllw = Output(UInt((XLEN/2).W))\n })\n io.sllw := io.sllSrc << io.shamt\n io.revSllw := io.sllSrc << io.revShamt\n}\n\nclass RightShiftModule(implicit p: Parameters) extends XSModule {\n val io = IO(new Bundle() {\n val shamt = Input(UInt(6.W))\n val revShamt = Input(UInt(6.W))\n val srlSrc, sraSrc = Input(UInt(XLEN.W))\n val srl, sra = Output(UInt(XLEN.W))\n val revSrl = Output(UInt(XLEN.W))\n })\n io.srl := io.srlSrc >> io.shamt\n io.sra := (io.sraSrc.asSInt >> io.shamt).asUInt\n io.revSrl := io.srlSrc >> io.revShamt\n}\n\nclass RightShiftWordModule(implicit p: Parameters) extends XSModule {\n val io = IO(new Bundle() {\n val shamt = Input(UInt(5.W))\n val revShamt = Input(UInt(5.W))\n val srlSrc, sraSrc = Input(UInt((XLEN/2).W))\n val srlw, sraw = Output(UInt((XLEN/2).W))\n val revSrlw = Output(UInt((XLEN/2).W))\n })\n\n io.srlw := io.srlSrc >> io.shamt\n io.sraw := (io.sraSrc.asSInt >> io.shamt).asUInt\n io.revSrlw := io.srlSrc >> io.revShamt\n}\n\n\nclass MiscResultSelect(implicit p: Parameters) extends XSModule {\n val io = IO(new Bundle() {\n val func = Input(UInt(6.W))\n val and, or, xor, orcb, orh48, sextb, packh, sexth, packw, revb, rev8, pack = Input(UInt(XLEN.W))\n val src = Input(UInt(XLEN.W))\n val miscRes = Output(UInt(XLEN.W))\n })\n\n val logicRes = VecInit(Seq(\n io.and,\n io.or,\n io.xor,\n io.orcb\n ))(io.func(2, 1))\n val miscRes = VecInit(Seq(io.sextb, io.packh, io.sexth, io.packw))(io.func(1, 0))\n val logicBase = Mux(io.func(3), miscRes, logicRes)\n\n val revRes = VecInit(Seq(io.revb, io.rev8, io.pack, io.orh48))(io.func(1, 0))\n val customRes = VecInit(Seq(\n Cat(0.U(31.W), io.src(31, 0), 0.U(1.W)),\n Cat(0.U(30.W), io.src(31, 0), 0.U(2.W)),\n Cat(0.U(29.W), io.src(31, 0), 0.U(3.W)),\n Cat(0.U(56.W), io.src(15, 8))))(io.func(1, 0))\n val logicAdv = Mux(io.func(3), customRes, revRes)\n\n val mask = Cat(Fill(15, io.func(0)), 1.U(1.W))\n val maskedLogicRes = mask & logicRes\n\n io.miscRes := Mux(io.func(5), maskedLogicRes, Mux(io.func(4), logicAdv, logicBase))\n}\n\nclass ConditionalZeroModule(implicit p: Parameters) extends XSModule {\n val io = IO(new Bundle() {\n val condition = Input(UInt(XLEN.W))\n val value = Input(UInt(XLEN.W))\n val isNez = Input(Bool())\n val condRes = Output(UInt(XLEN.W))\n })\n\n val condition_zero = io.condition === 0.U\n val use_zero = !io.isNez && condition_zero ||\n io.isNez && !condition_zero\n\n io.condRes := Mux(use_zero, 0.U, io.value)\n}\n\nclass ShiftResultSelect(implicit p: Parameters) extends XSModule {\n val io = IO(new Bundle() {\n val func = Input(UInt(4.W))\n val sll, srl, sra, rol, ror, bclr, bset, binv, bext = Input(UInt(XLEN.W))\n val shiftRes = Output(UInt(XLEN.W))\n })\n\n // val leftBit = Mux(io.func(1), io.binv, Mux(io.func(0), io.bset, io.bclr))\n // val leftRes = Mux(io.func(2), leftBit, io.sll)\n // val rightRes = Mux(io.func(1) && io.func(0), io.sra, Mux(io.func(1), io.bext, io.srl))\n val resultSource = VecInit(Seq(\n io.sll,\n io.sll,\n io.bclr,\n io.bset,\n io.binv,\n io.srl,\n io.bext,\n io.sra\n ))\n val simple = resultSource(io.func(2, 0))\n\n io.shiftRes := Mux(io.func(3), Mux(io.func(1), io.ror, io.rol), simple)\n}\n\nclass WordResultSelect(implicit p: Parameters) extends XSModule {\n val io = IO(new Bundle() {\n val func = Input(UInt())\n val sllw, srlw, sraw, rolw, rorw, addw, subw = Input(UInt((XLEN/2).W))\n val wordRes = Output(UInt(XLEN.W))\n })\n\n val addsubRes = Mux(!io.func(2) && io.func(1) && !io.func(0), io.subw, io.addw)\n val shiftRes = Mux(io.func(2), Mux(io.func(0), io.rorw, io.rolw),\n Mux(io.func(1), io.sraw, Mux(io.func(0), io.srlw, io.sllw)))\n val wordRes = Mux(io.func(3), shiftRes, addsubRes)\n io.wordRes := SignExt(wordRes, XLEN)\n}\n\n\nclass AluResSel(implicit p: Parameters) extends XSModule {\n val io = IO(new Bundle() {\n val func = Input(UInt(3.W))\n val addRes, shiftRes, miscRes, compareRes, wordRes, condRes = Input(UInt(XLEN.W))\n val aluRes = Output(UInt(XLEN.W))\n })\n\n val res = Mux(io.func(2, 1) === 0.U, Mux(io.func(0), io.wordRes, io.shiftRes),\n Mux(!io.func(2), Mux(io.func(0), io.compareRes, io.addRes),\n Mux(io.func(1, 0) === 3.U, io.condRes, io.miscRes)))\n io.aluRes := res\n}\n\nclass AluDataModule(implicit p: Parameters) extends XSModule {\n val io = IO(new Bundle() {\n val src = Vec(2, Input(UInt(XLEN.W)))\n val func = Input(FuOpType())\n val result = Output(UInt(XLEN.W))\n })\n val (src1, src2, func) = (io.src(0), io.src(1), io.func)\n\n val shamt = src2(5, 0)\n val revShamt = ~src2(5,0) + 1.U\n\n // slliuw, sll\n val leftShiftModule = Module(new LeftShiftModule)\n val sll = leftShiftModule.io.sll\n val revSll = leftShiftModule.io.revSll\n leftShiftModule.io.sllSrc := Cat(Fill(32, func(0)), Fill(32, 1.U)) & src1\n leftShiftModule.io.shamt := shamt\n leftShiftModule.io.revShamt := revShamt\n\n // bclr, bset, binv\n val bitShift = 1.U << src2(5, 0)\n val bclr = src1 & ~bitShift\n val bset = src1 | bitShift\n val binv = src1 ^ bitShift\n\n // srl, sra, bext\n val rightShiftModule = Module(new RightShiftModule)\n val srl = rightShiftModule.io.srl\n val revSrl = rightShiftModule.io.revSrl\n val sra = rightShiftModule.io.sra\n rightShiftModule.io.shamt := shamt\n rightShiftModule.io.revShamt := revShamt\n rightShiftModule.io.srlSrc := src1\n rightShiftModule.io.sraSrc := src1\n val bext = srl(0)\n\n val rol = revSrl | sll\n val ror = srl | revSll\n\n // addw\n val addModule = Module(new AddModule)\n addModule.io.srcw := Mux(!func(2) && func(0), Mux(func(1), SignExt(src2(11, 0), XLEN), ZeroExt(src1(0), XLEN)), src1(31, 0))\n val addwResultAll = VecInit(Seq(\n ZeroExt(addModule.io.addw(0), XLEN),\n ZeroExt(addModule.io.addw(7, 0), XLEN),\n ZeroExt(addModule.io.addw(15, 0), XLEN),\n SignExt(addModule.io.addw(15, 0), XLEN)\n ))\n val addw = Mux(func(2), addwResultAll(func(1, 0)), addModule.io.addw)\n\n // subw\n val subModule = Module(new SubModule)\n val subw = subModule.io.sub\n\n // sllw\n val leftShiftWordModule = Module(new LeftShiftWordModule)\n val sllw = leftShiftWordModule.io.sllw\n val revSllw = leftShiftWordModule.io.revSllw\n leftShiftWordModule.io.sllSrc := src1\n leftShiftWordModule.io.shamt := shamt\n leftShiftWordModule.io.revShamt := revShamt\n\n val rightShiftWordModule = Module(new RightShiftWordModule)\n val srlw = rightShiftWordModule.io.srlw\n val revSrlw = rightShiftWordModule.io.revSrlw\n val sraw = rightShiftWordModule.io.sraw\n rightShiftWordModule.io.shamt := shamt\n rightShiftWordModule.io.revShamt := revShamt\n rightShiftWordModule.io.srlSrc := src1\n rightShiftWordModule.io.sraSrc := src1\n\n val rolw = revSrlw | sllw\n val rorw = srlw | revSllw\n\n // add\n val wordMaskAddSource = Cat(Fill(32, func(0)), Fill(32, 1.U)) & src1\n val shaddSource = VecInit(Seq(\n Cat(wordMaskAddSource(62, 0), 0.U(1.W)),\n Cat(wordMaskAddSource(61, 0), 0.U(2.W)),\n Cat(wordMaskAddSource(60, 0), 0.U(3.W)),\n Cat(wordMaskAddSource(59, 0), 0.U(4.W))\n ))\n val sraddSource = VecInit(Seq(\n ZeroExt(src1(63, 29), XLEN),\n ZeroExt(src1(63, 30), XLEN),\n ZeroExt(src1(63, 31), XLEN),\n ZeroExt(src1(63, 32), XLEN)\n ))\n // TODO: use decoder or other libraries to optimize timing\n // Now we assume shadd has the worst timing.\n addModule.io.src(0) := Mux(func(3), shaddSource(func(2, 1)),\n Mux(func(2), sraddSource(func(1, 0)),\n Mux(func(1), Mux(func(0), SignExt(src2(11, 0), XLEN), ZeroExt(src1(0), XLEN)), wordMaskAddSource))\n )\n addModule.io.src(1) := Mux(func(3, 0) === \"b0011\".U, Cat(src2(63, 12), 0.U(12.W)), src2)\n val add = addModule.io.add\n\n // sub\n val sub = subModule.io.sub\n subModule.io.src(0) := src1\n subModule.io.src(1) := src2\n val sltu = !sub(XLEN)\n val slt = src1(XLEN - 1) ^ src2(XLEN - 1) ^ sltu\n val maxMin = Mux(slt ^ func(0), src2, src1)\n val maxMinU = Mux(sltu ^ func(0), src2, src1)\n val compareRes = Mux(func(2), Mux(func(1), maxMin, maxMinU), Mux(func(1), slt, Mux(func(0), sltu, sub)))\n\n // logic\n val logicSrc2 = Mux(!func(5) && func(0), ~src2, src2)\n val and = src1 & logicSrc2\n val or = src1 | logicSrc2\n val xor = src1 ^ logicSrc2\n val orcb = Cat((0 until 8).map(i => Fill(8, src1(i * 8 + 7, i * 8).orR)).reverse)\n val orh48 = Cat(src1(63, 8), 0.U(8.W)) | src2\n\n val sextb = SignExt(src1(7, 0), XLEN)\n val packh = Cat(src2(7,0), src1(7,0))\n val sexth = SignExt(src1(15, 0), XLEN)\n val packw = SignExt(Cat(src2(15, 0), src1(15, 0)), XLEN)\n\n val revb = Cat((0 until 8).map(i => Reverse(src1(8 * i + 7, 8 * i))).reverse)\n val pack = Cat(src2(31, 0), src1(31, 0))\n val rev8 = Cat((0 until 8).map(i => src1(8 * i + 7, 8 * i)))\n\n\n // Result Select\n val shiftResSel = Module(new ShiftResultSelect)\n shiftResSel.io.func := func(3, 0)\n shiftResSel.io.sll := sll\n shiftResSel.io.srl := srl\n shiftResSel.io.sra := sra\n shiftResSel.io.rol := rol\n shiftResSel.io.ror := ror\n shiftResSel.io.bclr := bclr\n shiftResSel.io.binv := binv\n shiftResSel.io.bset := bset\n shiftResSel.io.bext := bext\n val shiftRes = shiftResSel.io.shiftRes\n\n val miscResSel = Module(new MiscResultSelect)\n miscResSel.io.func := func(5, 0)\n miscResSel.io.and := and\n miscResSel.io.or := or\n miscResSel.io.xor := xor\n miscResSel.io.orcb := orcb\n miscResSel.io.orh48 := orh48\n miscResSel.io.sextb := sextb\n miscResSel.io.packh := packh\n miscResSel.io.sexth := sexth\n miscResSel.io.packw := packw\n miscResSel.io.revb := revb\n miscResSel.io.rev8 := rev8\n miscResSel.io.pack := pack\n miscResSel.io.src := src1\n val miscRes = miscResSel.io.miscRes\n\n val condModule = Module(new ConditionalZeroModule)\n condModule.io.value := src1\n condModule.io.condition := src2\n condModule.io.isNez := func(1)\n val condRes = condModule.io.condRes\n\n\n val wordResSel = Module(new WordResultSelect)\n wordResSel.io.func := func\n wordResSel.io.addw := addw\n wordResSel.io.subw := subw\n wordResSel.io.sllw := sllw\n wordResSel.io.srlw := srlw\n wordResSel.io.sraw := sraw\n wordResSel.io.rolw := rolw\n wordResSel.io.rorw := rorw\n val wordRes = wordResSel.io.wordRes\n\n val aluResSel = Module(new AluResSel)\n aluResSel.io.func := func(6, 4)\n aluResSel.io.addRes := add\n aluResSel.io.compareRes := compareRes\n aluResSel.io.shiftRes := shiftRes\n aluResSel.io.miscRes := miscRes\n aluResSel.io.wordRes := wordRes\n aluResSel.io.condRes := condRes\n val aluRes = aluResSel.io.aluRes\n\n io.result := aluRes\n\n XSDebug(func === ALUOpType.lui32add, p\"[alu] func lui32: src1=${Hexadecimal(src1)} src2=${Hexadecimal(src2)} alures=${Hexadecimal(aluRes)}\\n\")\n XSDebug(func === ALUOpType.lui32add, p\"[alu] func lui32: add_src1=${Hexadecimal(addModule.io.src(0))} add_src2=${Hexadecimal(addModule.io.src(1))} addres=${Hexadecimal(add)}\\n\")\n\n XSDebug(func === ALUOpType.lui32addw, p\"[alu] func lui32w: src1=${Hexadecimal(src1)} src2=${Hexadecimal(src2)} alures=${Hexadecimal(aluRes)}\\n\")\n", "right_context": "}\n", "groundtruth": " XSDebug(func === ALUOpType.lui32addw, p\"[alu] func lui32w: add_src1=${Hexadecimal(addModule.io.srcw)} add_src2=${Hexadecimal(addModule.io.src(1)(31,0))} addres=${Hexadecimal(addw)}\\n\")\n", "crossfile_context": ""}
{"task_id": "XiangShan", "path": "XiangShan/src/main/scala/xiangshan/backend/fu/NewCSR/CSRDefines.scala", "left_context": "package xiangshan.backend.fu.NewCSR\n\nimport chisel3._\nimport xiangshan.backend.fu.NewCSR.CSRFunc._\n\nimport scala.language.experimental.macros\nimport scala.reflect.runtime.{universe => ru}\n\nobject CSRDefines {\n object CSRField1Bits extends CSREnum with CSRMacroApply\n\n object CSRField2Bits extends CSREnum with CSRMacroApply\n\n object CSRField3Bits extends CSREnum with CSRMacroApply\n\n object CSRField4Bits extends CSREnum with CSRMacroApply\n\n object CSRField5Bits extends CSREnum with CSRMacroApply\n\n object CSRField6Bits extends CSREnum with CSRMacroApply\n\n object CSRField7Bits extends CSREnum with CSRMacroApply\n\n object CSRField8Bits extends CSREnum with CSRMacroApply\n\n object CSRField9Bits extends CSREnum with CSRMacroApply\n\n object CSRField10Bits extends CSREnum with CSRMacroApply\n\n object CSRField11Bits extends CSREnum with CSRMacroApply\n\n object CSRField12Bits extends CSREnum with CSRMacroApply\n\n object CSRField13Bits extends CSREnum with CSRMacroApply\n\n object CSRField14Bits extends CSREnum with CSRMacroApply\n\n object CSRField15Bits extends CSREnum with CSRMacroApply\n\n object CSRField16Bits extends CSREnum with CSRMacroApply\n\n object CSRField17Bits extends CSREnum with CSRMacroApply\n\n object CSRField18Bits extends CSREnum with CSRMacroApply\n\n object CSRField19Bits extends CSREnum with CSRMacroApply\n\n object CSRField20Bits extends CSREnum with CSRMacroApply\n\n object CSRField21Bits extends CSREnum with CSRMacroApply\n\n object CSRField22Bits extends CSREnum with CSRMacroApply\n\n object CSRField23Bits extends CSREnum with CSRMacroApply\n\n object CSRField24Bits extends CSREnum with CSRMacroApply\n\n object CSRField25Bits extends CSREnum with CSRMacroApply\n\n object CSRField26Bits extends CSREnum with CSRMacroApply\n\n object CSRField27Bits extends CSREnum with CSRMacroApply\n\n object CSRField28Bits extends CSREnum with CSRMacroApply\n\n object CSRField29Bits extends CSREnum with CSRMacroApply\n\n object CSRField30Bits extends CSREnum with CSRMacroApply\n\n object CSRField31Bits extends CSREnum with CSRMacroApply\n\n object CSRField32Bits extends CSREnum with CSRMacroApply\n\n object CSRField33Bits extends CSREnum with CSRMacroApply\n\n object CSRField34Bits extends CSREnum with CSRMacroApply\n\n object CSRField35Bits extends CSREnum with CSRMacroApply\n\n object CSRField36Bits extends CSREnum with CSRMacroApply\n\n object CSRField37Bits extends CSREnum with CSRMacroApply\n\n object CSRField38Bits extends CSREnum with CSRMacroApply\n\n object CSRField39Bits extends CSREnum with CSRMacroApply\n\n object CSRField40Bits extends CSREnum with CSRMacroApply\n\n object CSRField41Bits extends CSREnum with CSRMacroApply\n\n object CSRField42Bits extends CSREnum with CSRMacroApply\n\n object CSRField43Bits extends CSREnum with CSRMacroApply\n\n object CSRField44Bits extends CSREnum with CSRMacroApply\n\n object CSRField45Bits extends CSREnum with CSRMacroApply\n\n object CSRField46Bits extends CSREnum with CSRMacroApply\n\n object CSRField47Bits extends CSREnum with CSRMacroApply\n\n object CSRField48Bits extends CSREnum with CSRMacroApply\n\n object CSRField49Bits extends CSREnum with CSRMacroApply\n\n object CSRField50Bits extends CSREnum with CSRMacroApply\n\n object CSRField51Bits extends CSREnum with CSRMacroApply\n\n object CSRField52Bits extends CSREnum with CSRMacroApply\n\n object CSRField53Bits extends CSREnum with CSRMacroApply\n\n object CSRField54Bits extends CSREnum with CSRMacroApply\n\n", "right_context": "\n object CSRField56Bits extends CSREnum with CSRMacroApply\n\n object CSRField57Bits extends CSREnum with CSRMacroApply\n\n object CSRField58Bits extends CSREnum with CSRMacroApply\n\n object CSRField59Bits extends CSREnum with CSRMacroApply\n\n object CSRField60Bits extends CSREnum with CSRMacroApply\n\n object CSRField61Bits extends CSREnum with CSRMacroApply\n\n object CSRField62Bits extends CSREnum with CSRMacroApply\n\n object CSRField63Bits extends CSREnum with CSRMacroApply\n\n object CSRField64Bits extends CSREnum with CSRMacroApply\n\n object ContextStatus extends CSREnum with ContextStatusDef with RWApply\n object ContextStatusRO extends CSREnum with ContextStatusDef with ROApply\n trait ContextStatusDef { this: CSREnum =>\n val Off = Value(0.U)\n val Initial = Value(1.U)\n val Clean = Value(2.U)\n val Dirty = Value(3.U)\n }\n\n object BMAField extends CSREnum with WARLApply {\n val ResetBMA = Value(0.U)\n val TestBMA = Value(\"h4000000\".U)\n }\n\n object XLENField extends CSREnum with ROApply {\n val XLEN32 = Value(1.U)\n val XLEN64 = Value(2.U)\n val XLEN128 = Value(3.U)\n }\n\n object XtvecMode extends CSREnum with WARLApply {\n val Direct = Value(0.U)\n val Vectored = Value(1.U)\n\n override def isLegal(enumeration: CSREnumType): Bool = enumeration.isOneOf(Direct, Vectored)\n }\n\n object SatpMode extends CSREnum with WARLApply {\n val Bare = Value(0.U)\n val Sv39 = Value(8.U)\n val Sv48 = Value(9.U)\n val Sv57 = Value(10.U)\n val Sv64 = Value(11.U) // Reserved for page-based 64-bit virtual addressing\n\n // XiangShan only support Sv39 & Sv48 Page\n override def isLegal(enumeration: CSREnumType): Bool = enumeration.isOneOf(Bare, Sv39, Sv48)\n }\n\n object HgatpMode extends CSREnum with WARLApply {\n val Bare = Value(0.U)\n val Sv39x4 = Value(8.U)\n val Sv48x4 = Value(9.U)\n val Sv57x4 = Value(10.U)\n\n // XiangShan only support Sv39 & Sv48 Page\n override def isLegal(enumeration: CSREnumType): Bool = enumeration.isOneOf(Bare, Sv39x4, Sv48x4)\n }\n\n object EnvCBIE extends CSREnum with WARLApply {\n val Off = Value(\"b00\".U)\n val Flush = Value(\"b01\".U)\n val Inval = Value(\"b11\".U)\n\n override def isLegal(enumeration: CSREnumType): Bool = enumeration.isOneOf(Off, Flush, Inval)\n }\n\n object EnvPMM extends CSREnum with WARLApply {\n val Disable = Value(\"b00\".U)\n val PMLEN7 = Value(\"b10\".U)\n val PMLEN16 = Value(\"b11\".U)\n\n override def isLegal(enumeration: CSREnumType): Bool = enumeration.isOneOf(Disable, PMLEN7, PMLEN16)\n }\n\n object ReflectHelper {\n val mirror: ru.Mirror = ru.runtimeMirror(getClass.getClassLoader)\n\n def getCSRFieldMethodMirror(typeString: String, msb: Int, lsb: Int): ru.MethodMirror = {\n val moduleSymbol = mirror.typeOf[CSRDefines.type].termSymbol\n .info.decl(ru.TermName(s\"CSRField${msb - lsb + 1}Bits\")).asModule\n\n val methodSymbol = moduleSymbol\n .info.member(ru.TermName(typeString)).asMethod\n\n val instanceMirror: ru.InstanceMirror = mirror.reflect(mirror.reflectModule(moduleSymbol).instance)\n val methodMirror: ru.MethodMirror = instanceMirror.reflectMethod(methodSymbol)\n\n methodMirror\n }\n }\n\n object CSRWARLField {\n private def helper(msb: Int, lsb: Int, wfn: CSRWfnType, rfn: CSRRfnType): CSREnumType = {\n val methodMirror = ReflectHelper.getCSRFieldMethodMirror(\"WARL\", msb, lsb)\n methodMirror.apply(msb, lsb, wfn, rfn).asInstanceOf[CSREnumType]\n }\n\n def apply(msb: Int, lsb: Int, fn: CSRRfnType): CSREnumType = this.helper(msb, lsb, null, fn)\n\n def apply(bit: Int, fn: CSRRfnType): CSREnumType = this.helper(bit, bit, null, fn)\n\n def apply(msb: Int, lsb: Int, fn: CSRWfnType): CSREnumType = this.helper(msb, lsb, fn, null)\n\n def apply(bit: Int, fn: CSRWfnType): CSREnumType = this.helper(bit, bit, fn, null)\n }\n\n object CSRROField {\n private def helper(msb: Int, lsb: Int, rfn: CSRRfnType): CSREnumType = {\n val methodMirror = ReflectHelper.getCSRFieldMethodMirror(\"RO\", msb, lsb)\n methodMirror.apply(msb, lsb, rfn).asInstanceOf[CSREnumType]\n }\n\n def apply(msb: Int, lsb: Int, rfn: CSRRfnType): CSREnumType = this.helper(msb, lsb, rfn)\n\n def apply(bit: Int, rfn: CSRRfnType): CSREnumType = this.helper(bit, bit, rfn)\n\n def apply(msb: Int, lsb: Int): CSREnumType = this.helper(msb, lsb, null)\n\n def apply(bit: Int): CSREnumType = this.helper(bit, bit, null)\n }\n\n object CSRRWField {\n private def helper(msb: Int, lsb: Int) : CSREnumType = {\n val methodMirror: ru.MethodMirror = ReflectHelper.getCSRFieldMethodMirror(\"RW\", msb, lsb)\n methodMirror.apply(msb, lsb).asInstanceOf[CSREnumType]\n }\n\n def apply(msb: Int, lsb: Int) : CSREnumType = this.helper(msb, lsb)\n\n def apply(bit: Int): CSREnumType = this.helper(bit, bit)\n }\n\n object CSRWLRLField {\n private def helper(msb: Int, lsb: Int) : CSREnumType = {\n val methodMirror: ru.MethodMirror = ReflectHelper.getCSRFieldMethodMirror(\"WLRL\", msb, lsb)\n methodMirror.apply(msb, lsb).asInstanceOf[CSREnumType]\n }\n\n def apply(msb: Int, lsb: Int): CSREnumType = this.helper(msb, lsb)\n }\n\n object PrivMode extends CSREnum with RWApply {\n val U = Value(0.U)\n val S = Value(1.U)\n val M = Value(3.U)\n\n override def isLegal(enumeration: CSREnumType): Bool = enumeration.isOneOf(U, S, M)\n }\n\n object VirtMode extends CSREnum with RWApply {\n val Off = Value(0.U)\n val On = Value(1.U)\n }\n\n object DebugverMode extends CSREnum with DebugverModeDef with ROApply\n\n trait DebugverModeDef {\n this: CSREnum =>\n val None = Value(0.U)\n val Spec = Value(4.U)\n val Custom = Value(15.U)\n }\n}\n", "groundtruth": " object CSRField55Bits extends CSREnum with CSRMacroApply\n", "crossfile_context": ""}
{"task_id": "XiangShan", "path": "XiangShan/src/main/scala/xiangshan/backend/fu/NewCSR/DebugLevel.scala", "left_context": "package xiangshan.backend.fu.NewCSR\n\nimport freechips.rocketchip.devices.debug.DebugModuleKey\nimport org.chipsalliance.cde.config.Parameters\nimport freechips.rocketchip.rocket.CSRs\nimport chisel3._\nimport chisel3.util._\nimport utils.ConsecutiveOnes\nimport xiangshan.backend.fu.NewCSR.CSRDefines._\nimport xiangshan.backend.fu.NewCSR.CSRDefines.{\n CSRWARLField => WARL,\n CSRRWField => RW,\n CSRROField => RO,\n}\nimport xiangshan.backend.fu.NewCSR.CSRFunc._\nimport xiangshan.backend.fu.NewCSR.CSREvents._\nimport xiangshan.backend.fu.NewCSR.CSRBundles._\nimport CSRConfig._\nimport utility.SignExt\nimport xiangshan.TriggerAction\n\nimport scala.collection.immutable.SeqMap\n\n\ntrait DebugLevel { self: NewCSR =>\n val tselect = Module(new CSRModule(\"Tselect\", new TselectBundle(TriggerNum)) {\n when (this.w.wen && this.w.wdata < TriggerNum.U) {\n reg := this.w.wdata\n }.otherwise {\n reg := reg\n }\n })\n .setAddr(CSRs.tselect)\n\n val tdata1 = Module(new CSRModule(\"Tdata1\") with HasTdataSink {\n regOut := tdataRead.tdata1\n })\n .setAddr(CSRs.tdata1)\n\n val tdata2 = Module(new CSRModule(\"Tdata2\") with HasTdataSink {\n regOut := tdataRead.tdata2\n })\n .setAddr(CSRs.tdata2)\n\n val tdata1RegVec: Seq[CSRModule[_]] = Range(0, TriggerNum).map(i =>\n Module(new CSRModule(s\"Trigger$i\" + s\"_Tdata1\", new Tdata1Bundle) with HasTriggerBundle {\n when(wen){\n reg := wdata.writeTdata1(canWriteDmode, chainable).asUInt\n }\n })\n )\n val tdata2RegVec: Seq[CSRModule[_]] = Range(0, TriggerNum).map(i =>\n Module(new CSRModule(s\"Trigger$i\" + s\"_Tdata2\", new Tdata2Bundle))\n )\n\n val tinfo = Module(new CSRModule(\"Tinfo\", new TinfoBundle))\n .setAddr(CSRs.tinfo)\n\n val dcsr = Module(new CSRModule(\"Dcsr\", new DcsrBundle) with TrapEntryDEventSinkBundle with DretEventSinkBundle with HasNmipBundle {\n when(nmip){\n reg.NMIP := nmip\n }\n })\n .setAddr(CSRs.dcsr)\n\n val dpc = Module(new CSRModule(\"Dpc\", new Epc) with TrapEntryDEventSinkBundle)\n .setAddr(CSRs.dpc)\n\n val dscratch0 = Module(new CSRModule(\"Dscratch0\", new DscratchBundle))\n .setAddr(CSRs.dscratch0)\n\n val dscratch1 = Module(new CSRModule(\"Dscratch1\", new DscratchBundle))\n .setAddr(CSRs.dscratch1)\n\n val debugCSRMods = Seq(\n tdata1,\n tdata2,\n tselect,\n tinfo,\n dcsr,\n dpc,\n dscratch0,\n dscratch1,\n )\n\n val debugCSRMap: SeqMap[Int, (CSRAddrWriteBundle[_ <: CSRBundle], UInt)] = SeqMap.from(\n debugCSRMods.map(csr => csr.addr -> (csr.w -> csr.rdata)).iterator\n )\n\n val debugCSROutMap: SeqMap[Int, UInt] = SeqMap.from(\n debugCSRMods.map(csr => csr.addr -> csr.regOut.asInstanceOf[CSRBundle].asUInt).iterator\n )\n\n private val tdata1Rdata = Mux1H(\n tdata1RegVec.zipWithIndex.map{case (mod, idx) => (tselect.rdata === idx.U) -> mod.rdata}\n )\n\n private val tdata2Rdata = Mux1H(\n tdata2RegVec.zipWithIndex.map{case (mod, idx) => (tselect.rdata === idx.U) -> mod.rdata}\n )\n\n debugCSRMods.foreach { mod =>\n mod match {\n case m: HasTdataSink =>\n m.tdataRead.tdata1 := tdata1Rdata\n m.tdataRead.tdata2 := tdata2Rdata\n case _ =>\n }\n }\n\n}\n\n// tselect\nclass TselectBundle(triggerNum: Int) extends CSRBundle{\n override val len: Int = log2Up(triggerNum)\n val ALL = WARL(len - 1, 0, wNoEffectWhen(WriteTselect)).withReset(0.U)\n def WriteTselect(wdata: UInt) = {\n wdata >= triggerNum.U\n }\n}\n\n// tdata1\nclass Tdata1Bundle extends CSRBundle{\n val TYPE = Tdata1Type(63, 60, wNoFilter).withReset(Tdata1Type.Disabled)\n val DMODE = RW(59).withReset(0.U)\n val DATA = RW(58, 0).withReset(0.U)\n\n def getTriggerAction: CSREnumType = {\n val res = Wire(new Mcontrol6)\n res := this.asUInt\n res.ACTION\n }\n\n def writeTdata1(canWriteDmode: Bool, chainable: Bool): Tdata1Bundle = {\n val res = Wire(new Tdata1Bundle)\n res := this.asUInt\n val dmode = this.DMODE.asBool && canWriteDmode\n res.TYPE := this.TYPE.legalize.asUInt\n res.DMODE := dmode\n when(this.TYPE.isLegal) {\n val mcontrol6Res = Wire(new Mcontrol6)\n mcontrol6Res := this.DATA.asUInt\n res.DATA := mcontrol6Res.writeData(dmode, chainable).asUInt\n }.otherwise{\n res.DATA := 0.U\n }\n res\n }\n}\n\nclass Mcontrol6 extends CSRBundle{\n override val len: Int = 59\n // xiangshan don't support match = NAPOT\n val UNCERTAIN = RO(26).withReset(0.U)\n val HIT1 = RO(25).withReset(0.U)\n val VS = RW(24).withReset(0.U)\n val VU = RW(23).withReset(0.U)\n val HIT0 = RO(22).withReset(0.U)\n val SELECT = RO(21).withReset(0.U)\n val SIZE = RO(18, 16).withReset(0.U)\n val ACTION = TrigAction(15, 12, wNoFilter).withReset(TrigAction.BreakpointExp)\n val CHAIN = RW(11).withReset(0.U)\n val MATCH = TrigMatch(10, 7, wNoFilter).withReset(TrigMatch.EQ)\n val M = RW(6).withReset(0.U)\n val UNCERTAINEN = RO(5).withReset(0.U)\n val S = RW(4).withReset(0.U)\n val U = RW(3).withReset(0.U)\n val EXECUTE = RW(2).withReset(0.U)\n val STORE = RW(1).withReset(0.U)\n val LOAD = RW(0).withReset(0.U)\n\n def writeData(dmode: Bool, chainable: Bool): Mcontrol6 = {\n val res = Wire(new Mcontrol6)\n res := this.asUInt\n res.UNCERTAIN := 0.U\n res.HIT1 := 0.U\n res.HIT0 := 0.U\n res.SELECT := 0.U\n res.SIZE := 0.U\n res.ACTION := this.ACTION.legalize(dmode).asUInt\n res.CHAIN := this.CHAIN.asBool && chainable\n res.MATCH := this.MATCH.legalize.asUInt\n res.UNCERTAINEN := 0.U\n res\n }\n def isFetchTrigger: Bool = this.EXECUTE.asBool\n def isMemAccTrigger: Bool = this.STORE || this.LOAD\n}\n\n\nobject Tdata1Type extends CSREnum with WARLApply {\n val None = Value(0.U)\n val Legacy = Value(1.U)\n val Mcontrol = Value(2.U)\n val Icount = Value(3.U)\n val Itrigger = Value(4.U)\n val Etrigger = Value(5.U)\n val Mcontrol6 = Value(6.U)\n val Tmexttrigger = Value(7.U)\n val Disabled = Value(15.U)\n\n override def isLegal(enumeration: CSREnumType): Bool = enumeration.isOneOf(Mcontrol6)\n\n override def legalize(enumeration: CSREnumType): CSREnumType = {\n val res = WireInit(enumeration)\n when(!enumeration.isLegal){\n res := Disabled.asUInt\n }\n res\n }\n}\n\nobject TrigAction extends CSREnum with WARLApply {\n val BreakpointExp = Value(0.U) // raise breakpoint exception\n val DebugMode = Value(1.U) // enter debug mode\n val TraceOn = Value(2.U)\n val TraceOff = Value(3.U)\n val TraceNotify = Value(4.U)\n\n override def isLegal(enumeration: CSREnumType, dmode: Bool): Bool = enumeration.isOneOf(BreakpointExp) || enumeration.isOneOf(DebugMode) && dmode\n\n override def legalize(enumeration: CSREnumType, dmode: Bool): CSREnumType = {\n val res = WireInit(enumeration)\n when(!enumeration.isLegal(dmode)){\n res := BreakpointExp\n }\n res.asInstanceOf[CSREnumType]\n }\n}\n\nobject TrigMatch extends CSREnum with WARLApply {\n val EQ = Value(0.U)\n val NAPOT = Value(1.U)\n val GE = Value(2.U)\n val LT = Value(3.U)\n val MASK_LO = Value(4.U)\n val MASK_HI = Value(5.U)\n val NE = Value(8.U) // not eq\n val NNAPOT = Value(9.U) // not napot\n val NMASK_LO = Value(12.U) // not mask low\n val NMASK_HI = Value(13.U) // not mask high\n def isRVSpecLegal(enumeration: CSREnumType) : Bool = enumeration.isOneOf(\n EQ, NAPOT, GE, LT, MASK_LO, MASK_HI,\n NE, NNAPOT, NMASK_LO, NMASK_HI,\n )\n override def isLegal(enumeration: CSREnumType): Bool = enumeration.isOneOf(EQ, GE, LT)\n\n override def legalize(enumeration: CSREnumType): CSREnumType = {\n val res = WireInit(enumeration)\n when(!enumeration.isLegal){\n res := EQ\n }\n res.asInstanceOf[CSREnumType]\n }\n}\n\n\n// tdata2\nclass Tdata2Bundle extends OneFieldBundle\n\n// Tinfo\nclass TinfoBundle extends CSRBundle{\n // Version isn't in version 0.13\n val VERSION = RO(31, 24).withReset(0.U)\n // only support mcontrol6\n val MCONTROL6EN = RO(6).withReset(1.U)\n}\n\n// Dscratch\nclass DscratchBundle extends OneFieldBundle\n\n\nclass DcsrBundle extends CSRBundle {\n override val len: Int = 32\n val DEBUGVER = DcsrDebugVer(31, 28).withReset(DcsrDebugVer.Spec) // Debug implementation as it described in 0.13 draft\n val EXTCAUSE = RO(26, 24).withReset(0.U)\n val CETRIG = RW( 19).withReset(0.U)\n // All ebreak Privileges are RW, instead of WARL, since XiangShan support U/S/VU/VS.\n val EBREAKVS = RW( 17).withReset(0.U)\n val EBREAKVU = RW( 16).withReset(0.U)\n val EBREAKM = RW( 15).withReset(0.U)\n val EBREAKS = RW( 13).withReset(0.U)\n val EBREAKU = RW( 12).withReset(0.U)\n // STEPIE is RW, instead of WARL, since XiangShan support interrupts being enabled single stepping.\n val STEPIE = RW( 11).withReset(0.U)\n val STOPCOUNT = RW( 10).withReset(0.U)\n val STOPTIME = RW( 9).withReset(0.U)\n val CAUSE = DcsrCause( 8, 6).withReset(DcsrCause.None)\n val V = VirtMode( 5).withReset(VirtMode.Off)\n // MPRVEN is RW, instead of WARL, since XiangShan support use mstatus.mprv in debug mode\n // Whether use mstatus.mprv\n val MPRVEN = RW( 4).withReset(0.U)\n val NMIP = RO( 3).withReset(0.U)\n // MPRVEN is RW, instead of WARL, since XiangShan support use mstatus.mprv in debug mode\n val STEP = RW( 2).withReset(0.U)\n val PRV = PrivMode( 1, 0).withReset(PrivMode.M)\n}\n\nobject DcsrDebugVer extends CSREnum with ROApply {\n val None = Value(0.U)\n val Spec = Value(4.U)\n val Custom = Value(15.U)\n}\n\nobject DcsrCause extends CSREnum with ROApply {\n val None = Value(0.U)\n val Ebreak = Value(1.U)\n val Trigger = Value(2.U)\n val Haltreq = Value(3.U)\n val Step = Value(4.U)\n val Resethaltreq = Value(5.U)\n val Group = Value(6.U)\n val Other = Value(7.U)\n}\n\ntrait HasTdataSink { self: CSRModule[_] =>\n val tdataRead = IO(Input(new Bundle {\n val tdata1 = UInt(XLEN.W)\n val tdata2 = UInt(XLEN.W)\n }))\n}\ntrait HasTriggerBundle { self: CSRModule[_] =>\n val canWriteDmode = IO(Input(Bool()))\n val chainable = IO(Input(Bool()))\n}\n\ntrait HasNmipBundle { self: CSRModule[_] =>\n val nmip = IO(Input(Bool()))\n}\n\n/**\n * debug Module MMIO Addr\n */\ntrait DebugMMIO {\n implicit val p: Parameters\n\n def debugMMIO = p(DebugModuleKey).get\n\n def BASE = debugMMIO.baseAddress\n def DebugEntry = BASE + 0x800\n def DebugException = BASE + 0x808\n def HALTED = BASE + 0x100\n", "right_context": " def RESUMING = BASE + 0x108\n def EXCEPTION = BASE + 0x10C\n def WHERETO = BASE + 0x300\n def DATA = BASE + 0x380\n def IMPEBREAK = DATA - 0x4\n def PROGBUF = DATA - 4 * debugMMIO.nProgramBufferWords\n def ABSTRACT = PROGBUF - 4 * (if(debugMMIO.atzero) 2 else 5)\n def FLAGS = BASE + 0x400\n}\n\nobject TriggerUtil {\n /**\n * Check if chain vector is legal\n * @param chainVec\n * @param chainLen\n * @return true.B if the max length of chain don't exceed the permitted length\n */\n def TriggerCheckChainLegal(chainVec: Seq[Bool], chainLen: Int): Bool = {\n !ConsecutiveOnes(chainVec, chainLen)\n }\n\n /**\n * Generate Trigger action\n * @return triggerAction return\n * @param triggerCanFireVec\n * @param actionVec tdata.action\n * @param triggerCanRaiseBpExp from csr\n */\n def triggerActionGen(triggerAction: UInt, triggerCanFireVec: Vec[Bool], actionVec: Vec[UInt], triggerCanRaiseBpExp: Bool): Unit = {\n // More than one triggers can hit at the same time, but only fire one.\n // We select the first hit trigger to fire.\n val hasTriggerFire = triggerCanFireVec.asUInt.orR\n val triggerFireOH = PriorityEncoderOH(triggerCanFireVec)\n val triggerFireAction = PriorityMux(triggerFireOH, actionVec).asUInt\n val actionIsBPExp = hasTriggerFire && (triggerFireAction === TrigAction.BreakpointExp.asUInt)\n val actionIsDmode = hasTriggerFire && (triggerFireAction === TrigAction.DebugMode.asUInt)\n val breakPointExp = actionIsBPExp && triggerCanRaiseBpExp\n\n // todo: add more for trace\n triggerAction := MuxCase(TriggerAction.None, Seq(\n breakPointExp -> TriggerAction.BreakpointExp,\n actionIsDmode -> TriggerAction.DebugMode,\n ))\n }\n}", "groundtruth": " def GOING = BASE + 0x104\n", "crossfile_context": ""}
{"task_id": "XiangShan", "path": "XiangShan/src/main/scala/xiangshan/backend/fu/util/CSRConst.scala", "left_context": "/***************************************************************************************\n* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences\n* Copyright (c) 2020-2021 Peng Cheng Laboratory\n*\n* XiangShan is licensed under Mulan PSL v2.\n* You can use this software according to the terms and conditions of the Mulan PSL v2.\n* You may obtain a copy of Mulan PSL v2 at:\n* http://license.coscl.org.cn/MulanPSL2\n*\n* THIS SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS, WITHOUT WARRANTIES OF ANY KIND,\n* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,\n* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.\n*\n* See the Mulan PSL v2 for more details.\n***************************************************************************************/\n\npackage xiangshan.backend.fu.util\n\nimport chisel3._\nimport chisel3.util._\nimport freechips.rocketchip.rocket.CSRs\n\ntrait HasCSRConst {\n // Supervisor Custom Read/Write\n val Sbpctl = 0x5C0\n val Spfctl = 0x5C1\n val Slvpredctl = 0x5C2\n val Smblockctl = 0x5C3\n val Srnctl = 0x5C4\n /** 0x5C5-0x5E5 for cache instruction register*/\n val Scachebase = 0x5C5\n\n // Machine level PMA TODO: remove this\n val PmacfgBase = 0x7C0\n val PmaaddrBase = 0x7C8 // 64 entry at most\n\n // Machine level Bitmap Check(Custom Read/Write)\n val Mbmc = 0xBC2\n\n def privEcall = 0x000.U\n def privEbreak = 0x001.U\n def privMNret = 0x702.U\n def privMret = 0x302.U\n def privSret = 0x102.U\n def privUret = 0x002.U\n def privDret = 0x7b2.U\n\n def ModeM = 0x3.U\n def ModeH = 0x2.U\n def ModeS = 0x1.U\n def ModeU = 0x0.U\n\n def IRQ_USIP = 0\n def IRQ_SSIP = 1\n def IRQ_VSSIP = 2\n def IRQ_MSIP = 3\n\n def IRQ_UTIP = 4\n def IRQ_STIP = 5\n def IRQ_VSTIP = 6\n def IRQ_MTIP = 7\n\n def IRQ_UEIP = 8\n def IRQ_SEIP = 9\n def IRQ_VSEIP = 10\n def IRQ_MEIP = 11\n\n def IRQ_SGEIP = 12\n", "right_context": "\n val Hgatp_Mode_len = 4\n val Hgatp_Vmid_len = 16\n val Hgatp_Addr_len = 44\n\n val Satp_Mode_len = 4\n val Satp_Asid_len = 16\n val Satp_Addr_len = 44\n def satp_part_wmask(max_length: Int, length: Int) : UInt = {\n require(length > 0 && length <= max_length)\n ((1L << length) - 1).U(max_length.W)\n }\n\n val IntPriority = Seq(\n IRQ_DEBUG,\n IRQ_MEIP, IRQ_MSIP, IRQ_MTIP,\n IRQ_SEIP, IRQ_SSIP, IRQ_STIP,\n IRQ_UEIP, IRQ_USIP, IRQ_UTIP,\n IRQ_VSEIP, IRQ_VSSIP, IRQ_VSTIP, IRQ_SGEIP\n )\n\n def csrAccessPermissionCheck(addr: UInt, wen: Bool, mode: UInt, virt: Bool, hasH: Bool): UInt = {\n val readOnly = addr(11, 10) === \"b11\".U\n val lowestAccessPrivilegeLevel = addr(9,8)\n val priv = Mux(mode === ModeS, ModeH, mode)\n val ret = Wire(Bool()) //0.U: normal, 1.U: illegal_instruction, 2.U: virtual instruction\n when (lowestAccessPrivilegeLevel === ModeH && !hasH){\n ret := 1.U\n }.elsewhen (readOnly && wen) {\n ret := 1.U\n }.elsewhen (priv < lowestAccessPrivilegeLevel) {\n when(virt && lowestAccessPrivilegeLevel <= ModeH){\n ret := 2.U\n }.otherwise{\n ret := 1.U\n }\n }.otherwise{\n ret := 0.U\n }\n ret\n }\n\n def perfcntPermissionCheck(addr: UInt, mode: UInt, mmask: UInt, smask: UInt): Bool = {\n val index = UIntToOH(addr & 31.U)\n Mux(mode === ModeM, true.B, Mux(mode === ModeS, (index & mmask) =/= 0.U, (index & mmask & smask) =/= 0.U))\n }\n\n def dcsrPermissionCheck(addr: UInt, mModeCanWrite: UInt, debug: Bool): Bool = {\n // debug mode write only regs\n val isDebugReg = addr(11, 4) === \"h7b\".U\n Mux(!mModeCanWrite && isDebugReg, debug, true.B)\n }\n\n def triggerPermissionCheck(addr: UInt, mModeCanWrite: UInt, debug: Bool): Bool = {\n val isTriggerReg = addr(11, 4) === \"h7a\".U\n Mux(!mModeCanWrite && isTriggerReg, debug, true.B)\n }\n}\nobject CSRConst extends HasCSRConst\n", "groundtruth": " def IRQ_DEBUG = 17\n", "crossfile_context": ""}
{"task_id": "XiangShan", "path": "XiangShan/src/main/scala/xiangshan/backend/fu/wrapper/JumpUnit.scala", "left_context": "package xiangshan.backend.fu.wrapper\n\nimport org.chipsalliance.cde.config.Parameters\nimport chisel3._\nimport utility.{SignExt, ZeroExt}\nimport xiangshan.RedirectLevel\nimport xiangshan.backend.fu.{FuConfig, FuncUnit, JumpDataModule, PipedFuncUnit}\nimport xiangshan.backend.datapath.DataConfig.VAddrData\n\n\nclass JumpUnit(cfg: FuConfig)(implicit p: Parameters) extends PipedFuncUnit(cfg) {\n private val jumpDataModule = Module(new JumpDataModule)\n\n private val flushed = io.in.bits.ctrl.robIdx.needFlush(io.flush)\n\n // associated with AddrData's position of JmpCfg.srcData\n private val src = io.in.bits.data.src(0)\n private val pc = Mux(io.instrAddrTransType.get.shouldBeSext,\n SignExt(io.in.bits.data.pc.get, cfg.destDataBits),\n ZeroExt(io.in.bits.data.pc.get, cfg.destDataBits)\n )\n private val imm = io.in.bits.data.imm\n private val func = io.in.bits.ctrl.fuOpType\n private val isRVC = io.in.bits.ctrl.preDecode.get.isRVC\n\n jumpDataModule.io.src := src\n jumpDataModule.io.pc := pc\n jumpDataModule.io.imm := imm\n jumpDataModule.io.nextPcOffset := io.in.bits.data.nextPcOffset.get\n jumpDataModule.io.func := func\n jumpDataModule.io.isRVC := isRVC\n\n val jmpTarget = io.in.bits.ctrl.predictInfo.get.target\n val predTaken = io.in.bits.ctrl.predictInfo.get.taken\n\n val redirect = io.out.bits.res.redirect.get.bits\n", "right_context": " redirect.fullTarget := jumpDataModule.io.target\n redirect.cfiUpdate.predTaken := true.B\n redirect.cfiUpdate.taken := true.B\n redirect.cfiUpdate.target := jumpDataModule.io.target\n redirect.cfiUpdate.pc := io.in.bits.data.pc.get\n redirect.cfiUpdate.isMisPred := jumpDataModule.io.target(VAddrData().dataWidth - 1, 0) =/= jmpTarget || !predTaken\n redirect.cfiUpdate.backendIAF := io.instrAddrTransType.get.checkAccessFault(jumpDataModule.io.target)\n redirect.cfiUpdate.backendIPF := io.instrAddrTransType.get.checkPageFault(jumpDataModule.io.target)\n redirect.cfiUpdate.backendIGPF := io.instrAddrTransType.get.checkGuestPageFault(jumpDataModule.io.target)\n// redirect.debug_runahead_checkpoint_id := uop.debugInfo.runahead_checkpoint_id // Todo: assign it\n\n io.in.ready := io.out.ready\n io.out.valid := io.in.valid\n io.out.bits.res.data := jumpDataModule.io.result\n connect0LatencyCtrlSingal\n}\n", "groundtruth": " val redirectValid = io.out.bits.res.redirect.get.valid\n redirectValid := io.in.valid && !jumpDataModule.io.isAuipc\n redirect := 0.U.asTypeOf(redirect)\n redirect.level := RedirectLevel.flushAfter\n", "crossfile_context": ""}
{"task_id": "XiangShan", "path": "XiangShan/src/main/scala/xiangshan/backend/regcache/RegCacheTagTable.scala", "left_context": "/***************************************************************************************\n* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences\n* Copyright (c) 2020-2021 Peng Cheng Laboratory\n*\n* XiangShan is licensed under Mulan PSL v2.\n* You can use this software according to the terms and conditions of the Mulan PSL v2.\n* You may obtain a copy of Mulan PSL v2 at:\n* http://license.coscl.org.cn/MulanPSL2\n*\n* THIS SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS, WITHOUT WARRANTIES OF ANY KIND,\n* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,\n* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.\n*\n* See the Mulan PSL v2 for more details.\n***************************************************************************************/\n\npackage xiangshan.backend.regcache\n\nimport org.chipsalliance.cde.config.Parameters\nimport chisel3._\nimport chisel3.util._\nimport utils._\nimport utility._\nimport xiangshan._\nimport xiangshan.backend.Bundles._\nimport xiangshan.backend.BackendParams\nimport xiangshan.backend.issue.SchdBlockParams\nimport freechips.rocketchip.util.SeqToAugmentedSeq\n\nclass RegCacheTagTable(numReadPorts: Int)(implicit p: Parameters) extends XSModule {\n\n val io = IO(new RegCacheTagTableIO(numReadPorts))\n\n println(s\"[RegCacheTagTable] readPorts: ${numReadPorts}, \" +\n", "right_context": "\n println(s\"[RegCacheTagTable] addrWidth: ${RegCacheIdxWidth}, tagWidth: ${IntPhyRegIdxWidth}\")\n\n private val IntRegCacheReadSize = numReadPorts\n private val IntRegCacheWriteSize = backendParams.getIntExuRCWriteSize\n private val MemRegCacheReadSize = numReadPorts\n private val MemRegCacheWriteSize = backendParams.getMemExuRCWriteSize\n\n val IntRCTagTable = Module(new RegCacheTagModule(\"IntRCTagTable\", IntRegCacheSize, IntRegCacheReadSize, IntRegCacheWriteSize, \n RegCacheIdxWidth - 1, IntPhyRegIdxWidth))\n\n val MemRCTagTable = Module(new RegCacheTagModule(\"MemRCTagTable\", MemRegCacheSize, MemRegCacheReadSize, MemRegCacheWriteSize, \n RegCacheIdxWidth - 1, IntPhyRegIdxWidth))\n\n // read\n io.readPorts\n .lazyZip(IntRCTagTable.io.readPorts.lazyZip(MemRCTagTable.io.readPorts))\n .foreach{ case (r_in, (r_int, r_mem)) => \n r_int.ren := r_in.ren\n r_mem.ren := r_in.ren\n r_int.tag := r_in.tag\n r_mem.tag := r_in.tag\n val matchAlloc = io.allocPregs.map(x => x.valid && r_in.tag === x.bits).reduce(_ || _)\n r_in.valid := (r_int.valid || r_mem.valid) && !matchAlloc\n r_in.addr := Mux(r_int.valid, Cat(\"b0\".U, r_int.addr), Cat(\"b1\".U, r_mem.addr))\n }\n\n // write\n val wakeupFromIQNeedWriteRC = io.wakeupFromIQ.filter(_.bits.params.needWriteRegCache)\n val shiftLoadDependency = Wire(Vec(wakeupFromIQNeedWriteRC.size, Vec(LoadPipelineWidth, UInt(LoadDependencyWidth.W))))\n\n require(wakeupFromIQNeedWriteRC.size == IntRegCacheWriteSize + MemRegCacheWriteSize, \"wakeup size should be equal to RC write size\")\n\n shiftLoadDependency.zip(wakeupFromIQNeedWriteRC.map(_.bits.loadDependency)).zip(backendParams.intSchdParams.get.wakeUpInExuSources.map(_.name)).foreach {\n case ((deps, originalDeps), name) => deps.zip(originalDeps).zipWithIndex.foreach {\n case ((dep, originalDep), deqPortIdx) =>\n if (backendParams.getLdExuIdx(backendParams.allExuParams.find(_.name == name).get) == deqPortIdx)\n dep := 1.U\n else\n dep := originalDep << 1\n }\n }\n\n (IntRCTagTable.io.writePorts ++ MemRCTagTable.io.writePorts).lazyZip(wakeupFromIQNeedWriteRC).lazyZip(shiftLoadDependency)\n .foreach{ case (w, wakeup, ldDp) => \n w.wen := wakeup.valid && wakeup.bits.rfWen && !LoadShouldCancel(Some(wakeup.bits.loadDependency), io.ldCancel) && !(wakeup.bits.is0Lat && io.og0Cancel(wakeup.bits.params.exuIdx))\n w.addr := wakeup.bits.rcDest.get(RegCacheIdxWidth - 2, 0)\n w.tag := wakeup.bits.pdest\n w.loadDependency := ldDp\n }\n\n // cancel\n val allocVec = (IntRCTagTable.io.tagVec ++ MemRCTagTable.io.tagVec).map{ t => \n io.allocPregs.map(a => a.valid && a.bits === t).asUInt.orR\n }\n\n val replaceVec = IntRCTagTable.io.tagVec.map{ t => \n IntRCTagTable.io.writePorts.map(w => w.wen && w.tag === t).asUInt.orR\n } ++ MemRCTagTable.io.tagVec.map{ t => \n MemRCTagTable.io.writePorts.map(w => w.wen && w.tag === t).asUInt.orR\n }\n\n val ldCancelVec = (IntRCTagTable.io.loadDependencyVec ++ MemRCTagTable.io.loadDependencyVec).map{ ldDp => \n LoadShouldCancel(Some(ldDp), io.ldCancel)\n }\n\n val cancelVec = allocVec.lazyZip(replaceVec).lazyZip(ldCancelVec).lazyZip((IntRCTagTable.io.validVec ++ MemRCTagTable.io.validVec))\n .map{ case (alloc, rep, ldCancel, v) => \n (alloc || rep || ldCancel) && v\n }\n\n (IntRCTagTable.io.cancelVec ++ MemRCTagTable.io.cancelVec).zip(cancelVec).foreach{ case (cancelIn, cancel) => \n cancelIn := cancel\n }\n}\n\nclass RegCacheTagTableIO(numReadPorts: Int)(implicit p: Parameters) extends XSBundle {\n\n val readPorts = Vec(numReadPorts, new RCTagTableReadPort(RegCacheIdxWidth, IntPhyRegIdxWidth))\n\n val wakeupFromIQ: MixedVec[ValidIO[IssueQueueIQWakeUpBundle]] = Flipped(backendParams.intSchdParams.get.genIQWakeUpInValidBundle)\n\n // set preg state to invalid\n val allocPregs = Vec(RenameWidth, Flipped(ValidIO(UInt(IntPhyRegIdxWidth.W))))\n\n // cancelFromDatapath\n val og0Cancel = Input(ExuVec())\n\n // cancelFromMem\n val ldCancel = Vec(backendParams.LdExuCnt, Flipped(new LoadCancelIO))\n}\n", "groundtruth": " s\"writePorts: ${backendParams.getIntExuRCWriteSize} + ${backendParams.getMemExuRCWriteSize}\")\n", "crossfile_context": ""}
{"task_id": "XiangShan", "path": "XiangShan/src/main/scala/xiangshan/cache/dcache/mainpipe/AtomicsReplayUnit.scala", "left_context": "/***************************************************************************************\n* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences\n* Copyright (c) 2020-2021 Peng Cheng Laboratory\n*\n* XiangShan is licensed under Mulan PSL v2.\n* You can use this software according to the terms and conditions of the Mulan PSL v2.\n* You may obtain a copy of Mulan PSL v2 at:\n* http://license.coscl.org.cn/MulanPSL2\n*\n* THIS SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS, WITHOUT WARRANTIES OF ANY KIND,\n* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,\n* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.\n*\n* See the Mulan PSL v2 for more details.\n***************************************************************************************/\n\npackage xiangshan.cache\n\nimport org.chipsalliance.cde.config.Parameters\nimport chisel3._\nimport chisel3.util._\nimport utility.XSDebug\n\nclass AtomicsReplayEntry(implicit p: Parameters) extends DCacheModule\n{\n val io = IO(new Bundle {\n val lsu = Flipped(new AtomicWordIO)\n val pipe_req = Decoupled(new MainPipeReq)\n val pipe_resp = Flipped(ValidIO(new MainPipeResp))\n val block_lr = Input(Bool())\n\n val block_addr = Output(Valid(UInt()))\n })\n\n val s_invalid :: s_pipe_req :: s_pipe_resp :: s_resp :: Nil = Enum(4)\n val state = RegInit(s_invalid)\n\n val req = Reg(new DCacheWordReqWithVaddr)\n\n // assign default values to output signals\n io.lsu.req.ready := state === s_invalid\n io.lsu.resp.valid := false.B\n io.lsu.resp.bits := DontCare\n\n io.pipe_req.valid := false.B\n io.pipe_req.bits := DontCare\n\n io.block_addr.valid := state =/= s_invalid\n io.block_addr.bits := req.addr\n\n\n XSDebug(state =/= s_invalid, \"AtomicsReplayEntry: state: %d block_addr: %x\\n\", state, io.block_addr.bits)\n\n // --------------------------------------------\n // s_invalid: receive requests\n when (state === s_invalid) {\n when (io.lsu.req.fire) {\n req := io.lsu.req.bits\n state := s_pipe_req\n }\n }\n\n // --------------------------------------------\n // replay\n when (state === s_pipe_req) {\n io.pipe_req.valid := Mux(\n io.pipe_req.bits.cmd === M_XLR,\n !io.block_lr, // block lr to survive in lr storm\n true.B\n )\n\n val pipe_req = io.pipe_req.bits\n pipe_req := DontCare\n pipe_req.miss := false.B\n pipe_req.probe := false.B\n pipe_req.probe_need_data := false.B\n pipe_req.source := AMO_SOURCE.U\n pipe_req.cmd := req.cmd\n pipe_req.addr := get_block_addr(req.addr)\n pipe_req.vaddr := get_block_addr(req.vaddr)\n pipe_req.word_idx := get_word(req.addr)\n pipe_req.amo_data := req.data\n pipe_req.amo_mask := req.mask\n\n when (io.pipe_req.fire) {\n state := s_pipe_resp\n assert(!io.pipe_req.bits.vaddr === 0.U)\n }\n }\n\n val resp_data = Reg(UInt())\n val resp_id = Reg(UInt())\n val resp_error = Reg(Bool())\n when (state === s_pipe_resp) {\n // when not miss\n // everything is OK, simply send response back to sbuffer\n // when miss and not replay\n // wait for missQueue to handling miss and replaying our request\n // when miss and replay\n // req missed and fail to enter missQueue, manually replay it later\n // TODO: add assertions:\n // 1. add a replay delay counter?\n // 2. when req gets into MissQueue, it should not miss any more\n when (io.pipe_resp.fire) {\n when (io.pipe_resp.bits.miss) {\n when (io.pipe_resp.bits.replay) {\n state := s_pipe_req\n }\n } .otherwise {\n resp_data := io.pipe_resp.bits.data\n resp_id := io.pipe_resp.bits.id\n resp_error := io.pipe_resp.bits.error\n state := s_resp\n }\n }\n }\n\n // --------------------------------------------\n when (state === s_resp) {\n io.lsu.resp.valid := true.B\n io.lsu.resp.bits := DontCare\n io.lsu.resp.bits.data := resp_data\n io.lsu.resp.bits.id := resp_id\n io.lsu.resp.bits.error := resp_error\n\n", "right_context": " // debug output\n // when (io.lsu.req.fire) {\n // io.lsu.req.bits.dump()\n // }\n\n // when (io.lsu.resp.fire) {\n // io.lsu.resp.bits.dump()\n // }\n\n// when (io.pipe_req.fire) {\n// io.pipe_req.bits.dump()\n// }\n//\n// when (io.pipe_resp.fire) {\n// io.pipe_resp.bits.dump()\n// }\n}", "groundtruth": " when (io.lsu.resp.fire) {\n state := s_invalid\n }\n", "crossfile_context": ""}
{"task_id": "XiangShan", "path": "XiangShan/src/main/scala/xiangshan/mem/lsqueue/FreeList.scala", "left_context": "/***************************************************************************************\n* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences\n* Copyright (c) 2020-2021 Peng Cheng Laboratory\n*\n* XiangShan is licensed under Mulan PSL v2.\n* You can use this software according to the terms and conditions of the Mulan PSL v2.\n* You may obtain a copy of Mulan PSL v2 at:\n* http://license.coscl.org.cn/MulanPSL2\n*\n* THIS SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS, WITHOUT WARRANTIES OF ANY KIND,\n* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,\n* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.\n*\n* See the Mulan PSL v2 for more details.\n***************************************************************************************/\npackage xiangshan.mem\n\nimport org.chipsalliance.cde.config.Parameters\nimport chisel3._\nimport chisel3.util._\nimport utils._\nimport utility._\nimport xiangshan._\n\nclass FreeList(size: Int, allocWidth: Int, freeWidth: Int, enablePreAlloc: Boolean = false, moduleName: String = \"\")(implicit p: Parameters) extends XSModule\n with HasCircularQueuePtrHelper\n with HasPerfEvents\n{\n val io = IO(new Bundle() {\n val allocateReq = Input(Vec(allocWidth, Bool()))\n val allocateSlot = Output(Vec(allocWidth, UInt()))\n val canAllocate = Output(Vec(allocWidth, Bool()))\n val doAllocate = Input(Vec(allocWidth, Bool()))\n\n val free = Input(UInt(size.W))\n\n val validCount = Output(UInt())\n val empty = Output(Bool())\n })\n\n println(s\"FreeList: $moduleName, size \" + size)\n\n val freeList = RegInit(VecInit(\n // originally {0, 1, ..., size - 1} are free.\n Seq.tabulate(size)(i => i.U(log2Up(size).W))\n ))\n\n class FreeListPtr extends CircularQueuePtr[FreeListPtr](size)\n object FreeListPtr {\n def apply(f: Boolean, v: Int): FreeListPtr = {\n val ptr = Wire(new FreeListPtr)\n ptr.flag := f.B\n ptr.value := v.U\n ptr\n }\n }\n\n val headPtr = RegInit(FreeListPtr(false, 0))\n val headPtrNext = Wire(new FreeListPtr)\n val tailPtr = RegInit(FreeListPtr(true, 0))\n val tailPtrNext = Wire(new FreeListPtr)\n\n // legality check\n def getRemBits(input: UInt)(rem: Int): UInt = {\n", "right_context": " }\n\n // free logic\n val freeMask = RegInit(0.U(size.W))\n val freeSelMask = Wire(UInt(size.W))\n val freeSelMaskVec = Wire(Vec(freeWidth, UInt(size.W)))\n\n // update freeMask\n require((size % freeWidth) == 0)\n freeSelMask := freeSelMaskVec.reduce(_|_)\n freeMask := (io.free | freeMask) & ~freeSelMask\n\n val remFreeSelMaskVec = VecInit(Seq.tabulate(freeWidth)(rem => getRemBits((freeMask & ~freeSelMask))(rem)))\n val remFreeSelIndexOHVec = VecInit(Seq.tabulate(freeWidth)(fport => {\n val highIndexOH = PriorityEncoderOH(remFreeSelMaskVec(fport))\n val freeIndexOHVec = Wire(Vec(size, Bool()))\n freeIndexOHVec.foreach(e => e := false.B)\n for (i <- 0 until size / freeWidth) {\n freeIndexOHVec(i * freeWidth + fport) := highIndexOH(i)\n }\n freeIndexOHVec.asUInt\n }))\n\n val freeReq = GatedRegNext(VecInit(remFreeSelMaskVec.map(_.asUInt.orR)))\n val freeSlotOH = GatedRegNext(remFreeSelIndexOHVec)\n val doFree = freeReq.asUInt.orR\n\n for (i <- 0 until freeWidth) {\n val offset = PopCount(freeReq.take(i))\n val enqPtr = tailPtr + offset\n\n when (freeReq(i)) {\n freeList(enqPtr.value) := OHToUInt(freeSlotOH(i))\n }\n\n freeSelMaskVec(i) := Mux(freeReq(i), freeSlotOH(i), 0.U)\n }\n\n tailPtrNext := tailPtr + PopCount(freeReq)\n tailPtr := Mux(doFree, tailPtrNext, tailPtr)\n\n // allocate\n val doAllocate = io.doAllocate.asUInt.orR\n val numAllocate = PopCount(io.doAllocate)\n val freeSlotCnt = RegInit(size.U(log2Up(size + 1).W))\n\n for (i <- 0 until allocWidth) {\n val offset = PopCount(io.allocateReq.take(i))\n\n if (enablePreAlloc) {\n val deqPtr = headPtr + numAllocate + offset\n io.canAllocate(i) := RegEnable(isBefore(deqPtr, tailPtr), enablePreAlloc.B)\n io.allocateSlot(i) := RegEnable(freeList(deqPtr.value), enablePreAlloc.B)\n } else {\n val deqPtr = headPtr + offset\n io.canAllocate(i) := isBefore(deqPtr, tailPtr)\n io.allocateSlot(i) := freeList(deqPtr.value)\n }\n\n }\n\n headPtrNext := headPtr + numAllocate\n headPtr := Mux(doAllocate, headPtrNext, headPtr)\n freeSlotCnt := distanceBetween(tailPtrNext, headPtrNext)\n\n io.empty := freeSlotCnt === 0.U\n io.validCount := size.U - freeSlotCnt\n\n XSPerfAccumulate(\"empty\", io.empty)\n val perfEvents: Seq[(String, UInt)] = Seq(\n (\"empty\", io.empty)\n )\n generatePerfEvent()\n\n // unique check\n val enableFreeListCheck = false\n if (enableFreeListCheck) {\n val differentFlag = tailPtr.flag ^ headPtr.flag\n val headMask = UIntToMask(headPtr.value, size)\n val tailMask = UIntToMask(tailPtr.value, size)\n val validMask1 = Mux(differentFlag, ~tailMask, tailMask ^ headMask)\n val validMask2 = Mux(differentFlag, headMask, 0.U(size.W))\n val validMask = ~(validMask1 | validMask2)\n for (i <- 0 until size) {\n for (j <- i+1 until size) {\n if (i != j) {\n XSError(validMask(i) && validMask(j) && freeList(i) === freeList(j),s\"Found same entry in free list! (i=$i j=$j)\\n\")\n }\n }\n }\n }\n\n // end\n}", "groundtruth": " VecInit((0 until size / freeWidth).map(i => { input(freeWidth * i + rem) })).asUInt\n", "crossfile_context": ""}
{"task_id": "XiangShan", "path": "XiangShan/src/main/scala/xiangshan/mem/prefetch/L1StridePrefetcher.scala", "left_context": "/***************************************************************************************\n* Copyright (c) 2024 Beijing Institute of Open Source Chip (BOSC)\n* Copyright (c) 2020-2024 Institute of Computing Technology, Chinese Academy of Sciences\n* Copyright (c) 2020-2021 Peng Cheng Laboratory\n*\n* XiangShan is licensed under Mulan PSL v2.\n* You can use this software according to the terms and conditions of the Mulan PSL v2.\n* You may obtain a copy of Mulan PSL v2 at:\n* http://license.coscl.org.cn/MulanPSL2\n*\n* THIS SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS, WITHOUT WARRANTIES OF ANY KIND,\n* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,\n* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.\n*\n* See the Mulan PSL v2 for more details.\n*\n*\n* Acknowledgement\n*\n* This implementation is inspired by several key papers:\n* [1] Jean-Loup Baer, and Tien-Fu Chen. \"[An effective on-chip preloading scheme to reduce data access penalty.]\n* (https://doi.org/10.1145/125826.125932)\" ACM/IEEE Conference on Supercomputing. 1991.\n***************************************************************************************/\n\npackage xiangshan.mem.prefetch\n\nimport org.chipsalliance.cde.config.Parameters\nimport chisel3._\nimport chisel3.util._\nimport utils._\nimport utility._\nimport xiangshan._\nimport xiangshan.mem.L1PrefetchReq\nimport xiangshan.mem.Bundles.LsPrefetchTrainBundle\nimport xiangshan.mem.trace._\nimport xiangshan.cache.HasDCacheParameters\nimport xiangshan.cache.mmu._\nimport scala.collection.SeqLike\n\ntrait HasStridePrefetchHelper extends HasL1PrefetchHelper {\n val STRIDE_FILTER_SIZE = 6\n val STRIDE_ENTRY_NUM = 10\n val STRIDE_BITS = 10 + BLOCK_OFFSET\n val STRIDE_VADDR_BITS = 10 + BLOCK_OFFSET\n val STRIDE_CONF_BITS = 2\n\n // detail control\n val ALWAYS_UPDATE_PRE_VADDR = true\n val AGGRESIVE_POLICY = false // if true, prefetch degree is greater than 1, 1 otherwise\n val STRIDE_LOOK_AHEAD_BLOCKS = 2 // aggressive degree\n val LOOK_UP_STREAM = false // if true, avoid collision with stream\n\n val STRIDE_WIDTH_BLOCKS = if(AGGRESIVE_POLICY) STRIDE_LOOK_AHEAD_BLOCKS else 1\n\n def MAX_CONF = (1 << STRIDE_CONF_BITS) - 1\n}\n\nclass StrideMetaBundle(implicit p: Parameters) extends XSBundle with HasStridePrefetchHelper {\n val pre_vaddr = UInt(STRIDE_VADDR_BITS.W)\n val stride = UInt(STRIDE_BITS.W)\n val confidence = UInt(STRIDE_CONF_BITS.W)\n val hash_pc = UInt(HASH_TAG_WIDTH.W)\n\n def reset(index: Int) = {\n pre_vaddr := 0.U\n stride := 0.U\n confidence := 0.U\n hash_pc := index.U\n }\n\n def tag_match(valid1: Bool, valid2: Bool, new_hash_pc: UInt): Bool = {\n valid1 && valid2 && hash_pc === new_hash_pc\n }\n\n def alloc(vaddr: UInt, alloc_hash_pc: UInt) = {\n pre_vaddr := vaddr(STRIDE_VADDR_BITS - 1, 0)\n stride := 0.U\n confidence := 0.U\n hash_pc := alloc_hash_pc\n }\n\n def update(vaddr: UInt, always_update_pre_vaddr: Bool) = {\n val new_vaddr = vaddr(STRIDE_VADDR_BITS - 1, 0)\n val new_stride = new_vaddr - pre_vaddr\n val new_stride_blk = block_addr(new_stride)\n // NOTE: for now, disable negtive stride\n val stride_valid = new_stride_blk =/= 0.U && new_stride_blk =/= 1.U && new_stride(STRIDE_VADDR_BITS - 1) === 0.U\n val stride_match = new_stride === stride\n val low_confidence = confidence <= 1.U\n val can_send_pf = stride_valid && stride_match && confidence === MAX_CONF.U\n\n when(stride_valid) {\n when(stride_match) {\n confidence := Mux(confidence === MAX_CONF.U, confidence, confidence + 1.U)\n }.otherwise {\n confidence := Mux(confidence === 0.U, confidence, confidence - 1.U)\n when(low_confidence) {\n stride := new_stride\n }\n }\n pre_vaddr := new_vaddr\n }\n when(always_update_pre_vaddr) {\n pre_vaddr := new_vaddr\n }\n\n (can_send_pf, new_stride)\n }\n\n}\n\nclass StrideMetaArray(implicit p: Parameters) extends XSModule with HasStridePrefetchHelper {\n val io = IO(new XSBundle {\n val enable = Input(Bool())\n // TODO: flush all entry when process changing happens, or disable stream prefetch for a while\n val flush = Input(Bool())\n val dynamic_depth = Input(UInt(32.W)) // TODO: enable dynamic stride depth\n val train_req = Flipped(DecoupledIO(new PrefetchReqBundle))\n val l1_prefetch_req = ValidIO(new StreamPrefetchReqBundle)\n val l2_l3_prefetch_req = ValidIO(new StreamPrefetchReqBundle)\n // query Stream component to see if a stream pattern has already been detected\n val stream_lookup_req = ValidIO(new PrefetchReqBundle)\n val stream_lookup_resp = Input(Bool())\n })\n\n val array = Reg(Vec(STRIDE_ENTRY_NUM, new StrideMetaBundle))\n val valids = RegInit(VecInit(Seq.fill(STRIDE_ENTRY_NUM)(false.B)))\n\n def reset_array(i: Int): Unit = {\n valids(i) := false.B\n //only need to rest control signals for firendly area\n // array(i).reset(i)\n }\n\n val replacement = ReplacementPolicy.fromString(\"plru\", STRIDE_ENTRY_NUM)\n\n // s0: hash pc -> cam all entries\n val s0_can_accept = Wire(Bool())\n val s0_valid = io.train_req.fire\n val s0_vaddr = io.train_req.bits.vaddr\n val s0_pc = io.train_req.bits.pc\n val s0_pc_hash = pc_hash_tag(s0_pc)\n val s0_pc_match_vec = VecInit(array zip valids map { case (e, v) => e.tag_match(v, s0_valid, s0_pc_hash) }).asUInt\n val s0_hit = s0_pc_match_vec.orR\n val s0_index = Mux(s0_hit, OHToUInt(s0_pc_match_vec), replacement.way)\n io.train_req.ready := s0_can_accept\n io.stream_lookup_req.valid := s0_valid\n io.stream_lookup_req.bits := io.train_req.bits\n\n when(s0_valid) {\n replacement.access(s0_index)\n }\n\n assert(PopCount(s0_pc_match_vec) <= 1.U)\n XSPerfAccumulate(\"s0_valid\", s0_valid)\n XSPerfAccumulate(\"s0_hit\", s0_valid && s0_hit)\n XSPerfAccumulate(\"s0_miss\", s0_valid && !s0_hit)\n\n // s1: alloc or update\n val s1_valid = GatedValidRegNext(s0_valid)\n val s1_index = RegEnable(s0_index, s0_valid)\n val s1_pc_hash = RegEnable(s0_pc_hash, s0_valid)\n val s1_vaddr = RegEnable(s0_vaddr, s0_valid)\n val s1_hit = RegEnable(s0_hit, s0_valid)\n val s1_alloc = s1_valid && !s1_hit\n val s1_update = s1_valid && s1_hit\n val s1_stride = array(s1_index).stride\n val s1_new_stride = WireInit(0.U(STRIDE_BITS.W))\n val s1_can_send_pf = WireInit(false.B)\n s0_can_accept := !(s1_valid && s1_pc_hash === s0_pc_hash)\n\n val always_update = Constantin.createRecord(s\"always_update${p(XSCoreParamsKey).HartId}\", initValue = ALWAYS_UPDATE_PRE_VADDR)\n\n when(s1_alloc) {\n valids(s1_index) := true.B\n array(s1_index).alloc(\n vaddr = s1_vaddr,\n alloc_hash_pc = s1_pc_hash\n )\n }.elsewhen(s1_update) {\n val res = array(s1_index).update(s1_vaddr, always_update)\n s1_can_send_pf := res._1\n s1_new_stride := res._2\n }\n\n", "right_context": " val l1_stride_ratio = l1_stride_ratio_const(3, 0)\n val l2_stride_ratio_const = Constantin.createRecord(s\"l2_stride_ratio${p(XSCoreParamsKey).HartId}\", initValue = 5)\n val l2_stride_ratio = l2_stride_ratio_const(3, 0)\n // s2: calculate L1 & L2 pf addr\n val s2_valid = GatedValidRegNext(s1_valid && s1_can_send_pf)\n val s2_vaddr = RegEnable(s1_vaddr, s1_valid && s1_can_send_pf)\n val s2_stride = RegEnable(s1_stride, s1_valid && s1_can_send_pf)\n val s2_l1_depth = s2_stride << l1_stride_ratio\n val s2_l1_pf_vaddr = (s2_vaddr + s2_l1_depth)(VAddrBits - 1, 0)\n val s2_l2_depth = s2_stride << l2_stride_ratio\n val s2_l2_pf_vaddr = (s2_vaddr + s2_l2_depth)(VAddrBits - 1, 0)\n val s2_l1_pf_req_bits = (new StreamPrefetchReqBundle).getStreamPrefetchReqBundle(\n valid = s2_valid,\n vaddr = s2_l1_pf_vaddr,\n width = STRIDE_WIDTH_BLOCKS,\n decr_mode = false.B,\n sink = SINK_L1,\n source = L1_HW_PREFETCH_STRIDE,\n // TODO: add stride debug db, not useful for now\n t_pc = 0xdeadbeefL.U,\n t_va = 0xdeadbeefL.U\n )\n val s2_l2_pf_req_bits = (new StreamPrefetchReqBundle).getStreamPrefetchReqBundle(\n valid = s2_valid,\n vaddr = s2_l2_pf_vaddr,\n width = STRIDE_WIDTH_BLOCKS,\n decr_mode = false.B,\n sink = SINK_L2,\n source = L1_HW_PREFETCH_STRIDE,\n // TODO: add stride debug db, not useful for now\n t_pc = 0xdeadbeefL.U,\n t_va = 0xdeadbeefL.U\n )\n\n // s3: send l1 pf out\n val s3_valid = if (LOOK_UP_STREAM) GatedValidRegNext(s2_valid) && !io.stream_lookup_resp else GatedValidRegNext(s2_valid)\n val s3_l1_pf_req_bits = RegEnable(s2_l1_pf_req_bits, s2_valid)\n val s3_l2_pf_req_bits = RegEnable(s2_l2_pf_req_bits, s2_valid)\n\n // s4: send l2 pf out\n val s4_valid = GatedValidRegNext(s3_valid)\n val s4_l2_pf_req_bits = RegEnable(s3_l2_pf_req_bits, s3_valid)\n\n io.l1_prefetch_req.valid := s3_valid\n io.l1_prefetch_req.bits := s3_l1_pf_req_bits\n io.l2_l3_prefetch_req.valid := s4_valid\n io.l2_l3_prefetch_req.bits := s4_l2_pf_req_bits\n\n XSPerfAccumulate(\"pf_valid\", PopCount(Seq(io.l1_prefetch_req.valid, io.l2_l3_prefetch_req.valid)))\n XSPerfAccumulate(\"l1_pf_valid\", s3_valid)\n XSPerfAccumulate(\"l2_pf_valid\", s4_valid)\n XSPerfAccumulate(\"detect_stream\", io.stream_lookup_resp)\n XSPerfHistogram(\"high_conf_num\", PopCount(VecInit(array.map(_.confidence === MAX_CONF.U))).asUInt, true.B, 0, STRIDE_ENTRY_NUM, 1)\n for(i <- 0 until STRIDE_ENTRY_NUM) {\n XSPerfAccumulate(s\"entry_${i}_update\", i.U === s1_index && s1_update)\n for(j <- 0 until 4) {\n XSPerfAccumulate(s\"entry_${i}_disturb_${j}\", i.U === s1_index && s1_update &&\n j.U === s1_new_stride &&\n array(s1_index).confidence === MAX_CONF.U &&\n array(s1_index).stride =/= s1_new_stride\n )\n }\n }\n\n for(i <- 0 until STRIDE_ENTRY_NUM) {\n when(GatedValidRegNext(io.flush)) {\n reset_array(i)\n }\n }\n}\n", "groundtruth": " val l1_stride_ratio_const = Constantin.createRecord(s\"l1_stride_ratio${p(XSCoreParamsKey).HartId}\", initValue = 2)\n", "crossfile_context": ""}