when (intSrcsRectified(ui)) { bits(ui):=bit }


case _ => assert(false, f"unknown address ${addrSet.base}"); 0


require(memberID < aplic_params.membersNum,  f"memberID ${memberID} should less than membersNum ${aplic_params.membersNum}")


if (params.HasTEEIMSIC) Some(LazyModule(new TLRegIMSIC(params, beatBytes)(Parameters.empty))) else None


case object IMSICParameKey extends Field[IMSICParameters]


def apply(updateData: UInt, resetData: BigInt): UInt = apply(updateData, resetData, enable = true.B)


object CompileOptions {
  /** Compatibility mode semantics except Module implicit reset should be inferred instead of Bool */
  implicit val NotStrictInferReset = NotStrict.copy(inferModuleReset = true)
}


abstract class Crossing[T <: Data] extends RawModule {
  val io: CrossingIO[T]
}


Module (new AsyncResetRegVec(w, init)).suggestName(s"${name}_${i}")


val reg = if (resetType == SynchronizerResetType.NonSync) Reg(Bool()) else RegInit(init.B)


def option[T](z: => T): Option[T] = if (x) Some(z) else None


def set(ind: Int, data: LazyData): Context = copy(regMapping = regMapping.updated(ind, data))


      case SHT_SYMTAB => SymtabSection
      case SHT_REL => RelSection


      retired := false.B
    }
    previousReqs += thisReq


final case class BpfDescriptions(instructions: Map[Int, Seq[BpfInsn]], instrumentations: Seq[OpcodeHandler])


expect(peek(dut.io.ready(i)) == 0, s"Circuit should not finish its calculations before ${steps}th step")


      def test(x: Bool, t1: Int, t2: Int, label: String): Unit = {
        val expected = (t + 1) >= t1 && (t + 1) <= t2
        expect((peek(x) != 0) == expected, s"$label should be $expected")
      }


  val OP1_RS1  = 0.U(OP1_LEN.W)
  val OP1_PC   = 1.U(OP1_LEN.W)
  val OP1_NONE = 2.U(OP1_LEN.W)


          return (a, args.take(i-1) ++ args.drop(i + 1))
        }
      }
    }


  io.dmem.rdata := Cat(
    mem(io.dmem.addr + 3.U(WORD_LEN.W)),


        while (!c.io.exit.peek().litToBoolean) {
          c.clock.step(1)
        }


for (f <- new File("./riscv-tests-results").listFiles.filter(f => f.isFile && f.getName.endsWith(".hex"))) {


          c.clock.step(1)
        }
      }
    }
  }


class PrngIo(n: Int) extends Bundle {
  val seed = Input(Valid(UInt(n.W)))
  val y = Output(UInt(n.W))
}


when (io.extReset || io.wrap) { value := 0.U }


  val b = RegInit(UInt((n/2).W), 0.U)

  val do_reset = io.data.fire() && io.data.bits.cmd === k_reset.U
  val do_compute = io.data.fire() && io.data.bits.cmd === k_compute.U


when (io.enable)                        { count := count + 1.U }


class PisoCmd(n: Int) extends Bundle {
  val data = UInt(n.W)
  val count = UInt(log2Ceil(n).W)
}


def printfWarn (m: String, a: Bits*) { pp("[WARN] ",  printfSigil++m, a:_*) }


  when (io.load) {
    x := io.px
    y := io.py
    s := io.s
  }


override def cloneType = (new PointProjectiveBundle(w)).asInstanceOf[this.type]


    for (i <- 0 until numPoints) {
      xvec(i) := io.xs(i)
      yvec(i) := io.ys(i)
    }


          when (s === 2.S) {
            state := idle
            io.valid := true.B


val inverses = p1x === p2x && p1y === -p2y


val xregseq = io.pointsx map { x => RegEnable(x, 0.S, io.load) }


class EllipticCurve(A: BigInt, B: BigInt, P: BigInt) {
  val a: BigInt = A
  val b: BigInt = B
  val p: BigInt = P
  //val g: Point = G


allinputs = (0 until 1000) flatMap { i => allinputs }


def unary_- = new Point(this.x, this.y * -1, this.curve)


g zip e map { case (gi, ei) => gi * ei } reduce {_ + _}


val r_dmem_dat: DataChannel     = new DataChannel               // read operation


implicit def uintToBitPat(x: UInt): BitPat = BitPat(x)


def risingEdge(x: Bool): Bool = x && !RegNext(x)


when(time.andR) { timeh := timeh + 1.U }


when(byteenable(3)){ mem_3.write(addr_align, wdat_3) }


when(byteenable(2)){ mem_2.write(addr_align, wdat_2) }


/*
    if( (lp >= 20 && lp<=25) || lp == 65 || lp == 90){
      poke(signal = c.io.sw.w_waitrequest_sig, value = 1)
    }
    else{


		iotesters.Driver.execute(Array(), () => new CpuBus())(testerGen = c => {
			CpuBusTester(c, "src/sw/rv32ui-p-sw.hex", "src/sw/rv32ui-p-sw_tester.log")
		}) should be (true)


object FirrtlCompiler extends StageMain(new FrendaStage)


class FrendaException(msg: String) extends Exception(msg)


@inline def log(message: String): Unit = if (!silentMode) stream.println(message)


class FrendaPhase extends PhaseManager(FrendaPhase.targets)


  def run(annotations: AnnotationSeq): AnnotationSeq = {
    val result = new FrendaPhase().transform(annotations)
    FrendaOptions.fromAnnotations(result).executionContext.shutdown()
    result
  }


override def optionalPrerequisiteOf = Seq()


override def invalidates(a: Phase) = false


override def optionalPrerequisites = Seq()


object Dependencies {
  lazy val scalaTest = "org.scalatest" %% "scalatest" % "3.2.14"
  private val chiselVersion = "3.5.5"
  lazy val chisel3 = "edu.berkeley.cs" %% "chisel3" % chiselVersion
  lazy val chiselCompilerPlugin = "edu.berkeley.cs" %% "chisel3-plugin" % chiselVersion


        Some(b)
      else
        None
  }


case class PreserveAggregate(mode: PreserveAggregate.Type) extends NoTargetAnnotation with CIRCTOption


val firtoolOptions:    Seq[String] = Seq.empty) {


override def run(annotations: AnnotationSeq): AnnotationSeq = phaseManager.transform(annotations)


        case a: CIRCTOption          => a
        case a: FirrtlOption         => a
        case a: FirrtlFileAnnotation => a
      }


s"Invalid combination of circtOptions.target ${circtOptions.target} and split ${split}"


      outputFile.delete()

      val stage = new CIRCTStage

      stage.execute(


    it("should emit FIRRTL dialect") {

      ChiselStage.emitFIRRTLDialect(new ChiselStageSpec.Foo) should include(" firrtl.module")

    }


val raw_val = if(iType == 1) {Cat(io.pc, io.offset)} else {io.delta_path}


.elsewhen(state === s_query_read14)    { vault0.io.rdcol0 := 12.U }


         io.maxId := io.ids(1)
         io.maxNum := io.nums(1)
      }.otherwise{
         io.maxId := io.ids(2)


  wrindex := (io.wrrow << 4) + io.wrcol

  when(io.we) {
    mem(wrindex) := io.wrdata
    // printf("[PLANE WRITE] row %d col %d index %d val %d\n", io.wrrow, io.wrcol, wrindex, io.wrdata)


val qv0 = io.qv0_p0 + io.qv0_p1 + io.qv0_p2


      val rdrow1 = Input(Vec(3, UInt(7.W)))
      val rdcol1 = Input(UInt(4.W))


  def main(args: Array[String]): Unit = {
    PythiaRunner("pythia", tests, args)
  }


      step(3)
      poke(c.io.sigUpdate, 0)
      // step(1)


  backends foreach {backend =>
    it should s"correctly add randomly generated numbers and show carry in $backend" in {
      Driver(() => new MaxN, backend)((c) => new MaxNTests(c)) should be (true)
    }
  }


val max = if (qv0 >= qv1) {qv0} else {qv1}


     expect(c.io.rddata0(1), data0)
     expect(c.io.rddata0(2), data0)


errors += s"Pythia module $testName: throwable ${t.getMessage}"


val read_cmd_posted     = withClockAndReset(ACLK, reset) { RegInit(false.B) }


val state           = withClockAndReset(ACLK, reset) { RegInit(sIDLE) }


    class TransBundle(AddrWidth: Int) extends Bundle {
        val NumBytes    = UInt(32.W)
        val Address     = UInt(AddrWidth.W)
    }


val state       = withClockAndReset(ACLK, reset) { RegInit(sIDLE) }


is (4.U) { reg_data_out := reg_dst_addr }


            for (n <- 0 to 3) {
                when (RegIntf.WSTRB(n) === 1.U) {
                    reg_src_addr_v(n)   := RegIntf.WDATA(n*8+7, n*8)
                }
            }


case class RegFileConfig(AddrWidth: Int, DataWidth: Int, MagicID: Int)


    // Connections
    //

    controller.ACLK         := ACLK
    controller.ARESETn      := ARESETn


    // Width of AXI Address Bus
    AddrWidth: Int      = 32,
    // Width of AXI Data Bus


    val PSEL        = Output(Bool())
    val PENABLE     = Output(Bool())
    val PWRITE      = Output(Bool())
    val PWDATA      = Output(UInt(DataWidth.W))
    val PREADY      = Input(Bool())


    val RESP    = UInt(2.W)
    val LAST    = Bool()


val rdptr       = withClockAndReset(ACLK, reset) { RegInit(0.U(ADDR_WIDTH.W)) }


val aw_valid   = withClockAndReset(ACLK, reset) { RegInit(false.B) }


when (inIdx === 0.U) { startHead := bufHead }


val keep = take.map(if (_) 0x3 else 0x0)


class IceNetUnitTestConfig extends Config(
  new WithIceNetUnitTests ++ new BaseSubsystemConfig)


def NET_FULL_KEEP = ~0.U(NET_IF_BYTES.W)


def htonl(a: UInt) = reverse_bytes(a, 4)


val pauseDropCheck = if (usePauser) Some(PauseDropCheck(_, _, _)) else None


when (sendCompDone) { completing := false.B }


when (arb.io.in(1).bits.last) { outInProgress := false.B }


  def flipConnect(other: StreamIO) {
    in <> other.out
    other.in <> out
  }


      maskArr(wordaddr) := acq.bits.data(outer.dataBits - 1, 0)
    } .otherwise {
      dataArr(wordaddr) := acq.bits.data(outer.dataBits - 1, 0)


pl => (Seq.fill(pl.size-1) { false } ++ Seq(true))


  val io = IO(new Bundle {
    val clock = Input(Clock())
    val reset = Input(Bool())
    val stream = Decoupled(new StreamChannel(NET_IF_WIDTH))
    val macAddr = Output(UInt(48.W))


      output.bits.value2 := yInitial
      resultValid := true.B

      when(output.ready && resultValid) {
        busy := false.B


        io.arpModify.get.ipv4 := arpIn.srcIpv4
        io.arpModify.get.mac := arpIn.srcMac


      when(!ipv4In.isValid) {
        dropRest()
      }


      val outIface = WireInit(3.U)
      val nextHop = WireInit(Ipv4Addr("10.0.3.2"))


      val iface = io.config.iface(nextHop.iface)
      when(dstMac.valid) {
        // update ethernet header
        val ethOut = WireInit(ethIn)
        ethOut.ethSrc := iface.mac


val dstIsMe = ethIn.ethDst === io.config.iface(io.in.bits.id).mac


    val ethIn = io.in.bits.data.asTypeOf(new EtherHeader())
    // swap src and dst MAC
    val ethOut = WireDefault(ethIn)
    ethOut.ethSrc := ethIn.ethDst
    ethOut.ethDst := ethIn.ethSrc


Seq.fill(wb - bytes.length) { 0.toByte } ++ bytes


  when(io.modify.op === ArpOp.Remove) {
    when(table(idx).bits.ipv4 === io.modify.ipv4) {
      table(idx).valid := false.B
    }
  }


  iotesters.Driver.execute(args, () => new GCD) {
    c => new GCDUnitTester(c)
  }


  private val backendNames = if(firrtl.FileUtils.isCommandAvailable(Seq("verilator", "--version"))) {
    Array("firrtl", "verilator")
  }


      dut.input.setSourceClock(dut.clock)
      dut.output.initSink()


if (genSplitFiles) "--split-verilog" else ""


    when(io.en) {
        accu := nextWrap
    }


s"_${1 << regAddrWidth}x${regDataBytes * 8}"


        when(en) {
            when(wrap) {
                cnt := 0.U(width.W)


override def desiredName: String = super.desiredName + s"_${(1<<addrWidth)}_x_${gen.typeName}"


def apply(in:UInt) : UInt = { 1.U << in }


        })
        // use chisel3.PriorityEncoder !
        io.out := PriorityEncoder(io.in)
    }


override def desiredName = s"${super.desiredName}_${nWords}_x_${gen.typeName}"


override def desiredName = s"${super.desiredName}_${gen.typeName}"


override def desiredName = s"${super.desiredName}_${genUS.typeName}_to_${genDS.typeName}"


final def <<<(n: UInt): FixPoint = shiftLeft(n)


val b = IO( Input(Bool())).suggestName{"bbb"}


        axi4l.b.ready.poke(true)
        val awt = fork {
            while (!axi4l.aw.ready.peekBoolean()) {


def totalClocks: Long = clksArray.last + 1


                    if(y + step >= modu)
                        dut.io.wrapUp.expect(true)
                    else
                        dut.io.wrapUp.expect(false)
                    dut.io.wrapDown.expect(false)


class BrJumpIO extends Bundle {
  val disp = Input(UInt(13.W))
  val PC = Input(UInt(32.W))
}


val verilog = new FileWriter(new File(dir, s"${chirrtl.main}.v"))


  val ALU_SRA  = 13.U(4.W)
  val ALU_OR   = 6.U(4.W)


    val inst = Input(UInt(32.W))
    val mode = Output(UInt(4.W))
    val sel  = Output(UInt(3.W))
    val imm  = Output(UInt(3.W))


val rdReg = mods.indices map { i => RegInit(false.B) }


def s(i: Int): UInt = Utility.extendSign(io.imm(i, 0), 32)


def UNS(i: Int):UInt = Mux(~io.mode(2), Utility.extendSign(io.mem.data(i-1, 0), 32), io.mem.data(i-1, 0))


  when(io.writer.wen & io.writer.waddr.orR) {
    regs(io.writer.waddr) := io.writer.wdata
  }


    val inst = Input(UInt(32.W))
  })
  // Execute no Operation
}


    val in  = Input(Bool())
    val re  = Input(Bool())
    val out = Output(Bool())
  })


object Constants {
  val ALU = Map(
    "ADD"  -> 0L,
    "SUB"  -> 8L,
    "SLL"  -> 1L,


"DataPath" should s"pass ${test.name}" in {


when(done) { printf("\n"); stop(); stop() }


case object BuildSystem extends Field[Parameters => LazyModule]((p: Parameters) => new DigitalTop()(p))


Seq((cName: String) => if (cName.contains(name)) Some(fMHz) else None)


case BootROMLocated(x) => up(BootROMLocated(x), site).map(_.copy(contentFileName = s"${site(TargetDirKey)}/bootrom.rv${site(XLen)}.img"))


    (SBUS, L2,   TLBusWrapperConnection(xType = NoCrossing, driveClockFromMaster = Some(true), nodeBinding = BIND_STAR)()),
    (L2,  MBUS,  TLBusWrapperConnection.crossTo(
      xType = sbusToMbusXType,
      driveClockFromMaster = None,


  with sifive.blocks.devices.spi.HasPeripherySPIModuleImp
  with freechips.rocketchip.util.DontTouch


object Generator extends StageMain(new ChipyardStage)


ports.foreach({ p => p := DontCare; p.bits.tieoff() })


val p = IO(new ClockedAndResetIO(DataMirror.internal.chiselTypeClone[AXI4Bundle](m))).suggestName(s"axi4_mem_${i}")


tlBusWrapperLocationMap.lift(loc).foreach { _.clockGroupNode := asyncClockGroupsNode }


val maskROMs = p(MaskROMLocated(location)).map { MaskROM.attach(_, this, CBUS) }


case object BuildTop extends Field[Parameters => LazyModule]((p: Parameters) => new ChipTop()(p))


def addSuite(s: RocketTestSuite) { suites += (s.makeTargetName -> s) }


  def apply(clockIn: Clock, div: Int): Clock = {
    val clockDivider = Module(new ClockDividerN(div))
    clockDivider.io.clk_in := clockIn
    clockDivider.io.clk_out
  }


case None            => Some(s"${s.name}_${idx}")


s"  Output clock ${sink.name.get}, requested: ${requested} MHz, actual: ${actual} MHz (division of ${division})"


  new chipyard.harness.WithBlackBoxSimMem ++                    // add SimDRAM DRAM model for axi4 backing memory, if axi4 mem is enabled
  new chipyard.harness.WithSimSerial ++                         // add external serial-adapter and RAM
  new chipyard.harness.WithSimDebug ++                          // add SimJTAG or SimDTM adapters if debug module is enabled
  new chipyard.harness.WithGPIOTiedOff ++                       // tie-off chiptop GPIOs, if GPIOs are present


class SmallBoomConfig extends Config(
  new boom.common.WithNSmallBooms(1) ++                          // small boom config
  new chipyard.config.AbstractConfig)


  new freechips.rocketchip.subsystem.WithNBanks(0) ++             // remove L2$
  new freechips.rocketchip.subsystem.WithNoMemPort ++             // remove backing memory
  new freechips.rocketchip.subsystem.With1TinyCore ++             // single tiny rocket-core
  new chipyard.config.AbstractConfig)


Seq(new ConfigsAnnotation(configs map { config => if (config contains ".") s"${config}" else s"${packageName}.${config}" } ))


    Dependency[chipyard.stage.phases.GenerateTestSuiteMakefrags],
    Dependency[freechips.rocketchip.stage.phases.GenerateArtefacts],


    if (p.lift(XLen).nonEmpty)
      // If a custom test suite is set up, use the custom test suite
      annotations += CustomMakefragSnippet(p(TestSuitesKey).apply(tileParams, suiteHelper, p))

    RocketTestSuiteAnnotation(suiteHelper.suites.values.toSeq) +: annotations


case class CustomMakefragSnippet(val toMakefrag: String) extends NoTargetAnnotation with MakefragSnippet with Unserializable


class TestHarness(implicit val p: Parameters) extends Module {
  val io = IO(new Bundle { val success = Output(Bool()) })
  io.success := Module(new UnitTestSuite).io.finished
}


class UnitTestSuite(implicit p: Parameters) extends freechips.rocketchip.unittest.UnitTestSuite {
  ElaborationArtefacts.add("plusArgs", PlusArgArtefacts.serialize_cHeader)
}


it should s"select a reference of ${expected} MHz for ${freqStr} MHz" in {


  val lt = Mux(isSameSign, diff(xlen - 1), io.rs1(xlen - 1))
  val ltu = Mux(isSameSign, diff(xlen - 1), io.rs2(xlen - 1))
  val ge = !lt


.elsewhen(csr_addr === CSR.cyclehw) { cycleh := wdata }


case class CacheConfig(nWays: Int, nSets: Int, blockBytes: Int)


case class Config(core: CoreConfig, cache: CacheConfig, nasti: NastiBundleParameters)


alu.io.B := Mux(io.ctrl.B_sel === B_RS2, rs2, immGen.io.out)


  val Uimm = Cat(io.inst(31, 12), 0.U(12.W)).asSInt
  val Jimm = Cat(io.inst(31), io.inst(19, 12), io.inst(20), io.inst(30, 25), io.inst(24, 21), 0.U(1.W)).asSInt
  val Zimm = io.inst(19, 15).zext


  val rdata1 = Output(UInt(xlen.W))
  val rdata2 = Output(UInt(xlen.W))
  val wen = Input(Bool())
  val waddr = Input(UInt(5.W))
  val wdata = Input(UInt(xlen.W))


def apply(config: Config): Tile = new Tile(config.core, config.nasti, config.cache)


def rand_idx = rnd.nextInt(1 << slen).U(slen.W)


if (trace) printf("MEM[%x] => %x\n", daddr * (xlen / 8).U, dmem(daddr))


object IntegrationTest extends Tag("IntegrationTest")


  val CSRRWI = BigInt("101", 2).U(3.W)
  val CSRRSI = BigInt("110", 2).U(3.W)


def iimm(inst: UInt) = Cat(Cat(Seq.fill(21) { inst_31(inst) }), inst_30_25(inst), inst_24_21(inst), inst_20(inst))


if (trace) printf("MEM[%x] <= %x\n", (addr + off) * (nasti.dataBits / 8).U, write)


class big_bank1(w: Int, addr_w: Int) extends BlackBox{
    val io = IO(new TrueDualPort(w, addr_w))
}


            when(counter.ccnt===counter.cend){
                valid_out_reg := 0.U
                counter.ccnt := counter.ccnt-1.U
            }.elsewhen(counter.ccnt===0.U){


io.valid_out := (if(para_num==1) A(0).valid_out else Cat(0.U((para_num-1).W), A(0).valid_out))


        val result = Output(SInt(40.W))
    })

    val dsp48 = Module(new DSP48())


val cache = RegInit(VecInit(Seq.fill(64){0.S(w.W)}))


    val r64 = RegInit(0.U.asTypeOf(Vec(para_num, new AccumuRawData(w))))
    for(t <- 0 to para_num-1)


val rom_weight = if(StdPara.para_num==4) Module(new ROMWeight(StdPara.para_num)).io else Module(new ROMHalfWeight(StdPara.para_num)).io


    when(fuck.complete_output){
        io.ok := fuck.checksum===26782.U
    }


val rom_bias = if(StdPara.para_num==4) Module(new ROMBias(StdPara.para_num)).io else Module(new ROMHalfBias(StdPara.para_num)).io


            when(out_64_counter.inc()){
                out_state := 5.U
            }


val _min = (x: Int, y: Int) => (if(x>=y) y else x)


def apply(addr_w: Int, id_w: Int) = new Address(addr_w, id_w)


            is(ReadType.toMaxp){
                gen(state).go_maxp()
            }


when(if(x==6) cnt_ic.cend(x-1) else ~cnt_ic.cend(x)&&cnt_ic.cend(x-1)){


class WeightReaderBundle(val w: Int, val addr_w: Int) extends TransBundle{
    val addr_end = Input(UInt(addr_w.W))
    val begin_addr = Input(UInt(addr_w.W))
    val addr = Output(UInt(addr_w.W))
}


ret.small(i).cnt_invalid_end := (if(i==0) (loop_num*in_chan*h*loop_h).U else 0.U)


var t2 = bank_id_small(j%2)(if(i%2==1) 0 else 2)


vis(i)(j) = (if(i==1) (peek(dut.io.rd_addr1.addrs(j).addr)).toInt else (peek(dut.io.rd_addr2.addrs(j).addr)).toInt)


      is ("b101".U) {
        r_vn := Cat(reductionMux.io.o_data)
        r_vn_valid := 3.U
      }


out_switch.io.in1 := w_internal(2 * (if(i % 2 == 0) i + 1 else i - 1) * (LEVELS - 1) + (2 * (LEVELS - 2)) + 1)


            when (io.mat2(i)(j) =/= 0.U){
                matReg2(i)(j) := 1.U
            }.otherwise{


  when (rst) {
    r_adder := 0.U
    r_vn := 0.U
    r_vn_valid := 0.U
  } .elsewhen (r_valid) {


      }.otherwise {
        r_reduction_add(30.U + x.U) := 0.U
        r_reduction_cmd( 30.U +  x.U) := "b000".U
      }


        }.otherwise {
            r_lvl_output_ff(67) := r_lvl_output_ff(35)
            r_lvl_output_ff_valid(67) := r_lvl_output_ff_valid(35)
        }


    val i_data_bus = Input(Vec(NUM_PES, UInt(DATA_TYPE.W)))
     val i_data_bus2  = Input(Vec(NUM_PES, UInt(DATA_TYPE.W)))

    val o_valid = Output(Vec(NUM_PES, UInt(1.W)))


    val NUM_IN  : Int = 4,
    val SEL_IN: Int = 2,


  when (r_buffer_valid && io.i_valid) {
    o_validReg := true.B
  }.otherwise {


  when ((w_sel_in_left).asUInt < 2.U) {

    io.o_data(0) := w_data_left(w_sel_in_left)
  }.otherwise {


        }.otherwise{
            matReg1(i)(j) := bitmap.io.bitmap1(i)(j)
        }


    val in1 = Input(UInt(width.W))
    val sel0 = Input(Bool())


    val io = IO(new Bundle{
        val i_data_bus2 = Input(Vec(config.NUM_PES, UInt(config.DATA_TYPE.W)))
        val i_data_bus1  = Input(Vec(config.NUM_PES, UInt(config.DATA_TYPE.W)))
        val i_mux_bus   = Input(Vec(config.NUM_PES, UInt((config.LEVELS-1).W)))


        } else {
            val elementMul = vec1(index) * vec2(index)
            val result = multiply(vec1, vec2, index + 1)
            result(index) := elementMul
            result


            // dut.io.i_data_bus(7).poke(6.U)
            dut.io.i_valid.poke(1.B)
            dut.io.i_add_en.poke(1.U)
            dut.io.i_cmd.poke(5.U)


        for (j <- 0 until 4) {
          dut.io.mat1(i)(j).poke(inputData(i)(j).U)
          dut.io.mat2(i)(j).poke(inputData(i)(j).U)
        }


class EdgeAdderSwitchTester extends AnyFreeSpec with ChiselScalatestTester {
    "Edge Adder Switch Test" in {
        implicit val config = MagmasiConfig()


            dut.io.i_data.poke(2.U)
            dut.io.i_stationary.poke(1.U)
            dut.io.o_valid.expect(0.B)


val LEVELS   : Int = (2 * (math.log(4) / math.log(2))).toInt + 1


            dut.io.i_data(1).poke(4.U)
            dut.io.i_data(2).poke(5.U)
            dut.io.i_data(3).poke(6.U)
            dut.io.i_sel.poke(3.U)
            dut.clock.step(1)


      )
            val inputData1 = Seq(
        Seq(1, 2, 0, 0),


      for (i <- 0 until 4) {
        dut.io.i_data_bus1(i).poke(inputData(i).U)
      }


        val inputData = Seq(1, 2, 3, 4, 5, 6, 7, 8)
        for (i <- 0 until NUM_IN) {
            dut.io.buffer1(i).poke(inputData(i).U)
            dut.io.buffer2(i).poke(inputData(i).U)


      when(io.decoded_alu_op.output_mux) {
        // Set values to compare with NZP register in alu_out[2:0]
        val gt = io.reg_in.rs > io.reg_in.rt
        val eq = io.reg_in.rs === io.reg_in.rt
        val lt = io.reg_in.rs < io.reg_in.rt


            current_consumer(i)                       := first_write_idx

            mem_write_valid(i)   := true.B
            mem_write_address(i) := write_address


      lsu.io.enable        := enable
      lsu.io.core_state    := scheduler.io.core_state
      lsu.io.mem_rw_enable := decoder.io.mem_rw_enable
      lsu.io.mem_read_data := io.data_mem_read_data(i)


          decoded_reg_write_enable   := true.B
          decoded_reg_input_mux      := RegInputOp.ARITHMETIC
          decoded_alu_arithmetic_mux := AluOpCode.DIV
        }


      x := x - y
    }.otherwise {
      y := y - x


  when(!reset.asBool && io.device_control_write_enable) {
    device_control_register := io.device_control_data
  }


cf"Dispatch outputs: core_start=${core_start}, core_reset=${core_reset}, core_block_id=${core_block_id}, core_thread_count=${core_thread_count}, done=${done}\n"


  circt.stage.ChiselStage.emitSystemVerilogFile(new dcr.DeviceControlRegister(), args, firtoolOptions)
  circt.stage.ChiselStage.emitSystemVerilogFile(new controller.Controller(), args, firtoolOptions)
  circt.stage.ChiselStage.emitSystemVerilogFile(new gpu.Gpu(), args, firtoolOptions)


        when(io.core_state === CoreState.DECODE) {
          fetcher_state := FetcherState.IDLE
        }


when(x > y) { x := x - y }.otherwise { y := y - x }


          when(io.core_state === CoreState.UPDATE) {
            lsu_state := LSUState.IDLE
          }


    when(io.core_state === CoreState.UPDATE) {
      when(io.decoded_nzp_write_enable) {
        nzp := io.alu_out(2, 0)
      }
    }


          }
          is(RegInputOp.MEMORY) {
            registers(io.decoded_reg_address.rd) := io.lsu_out
          }
          is(RegInputOp.CONSTANT) {


        when(io.fetcher_state === FetcherState.FETCHED) {
          core_state := CoreState.DECODE
        }


object RegInputOp extends ChiselEnum {
  val ARITHMETIC = Value("b00".U)
  val MEMORY     = Value("b01".U)
  val CONSTANT   = Value("b10".U)
}


    // PC output
    var next_pc = Array.fill(ThreadsPerBlock)(0)


        if (core_state == CoreState.FETCH) {
          fetcher_state = FetcherState.FETCHING
          read_valid = true
          read_address = current_pc
        }


          if (dut.output.valid.peekValue().asBigInt == 1) {
            dut.output.bits.gcd.expect(BigInt(testValues(received)._1).gcd(testValues(received)._2))
            received += 1
          }


val write_enable    = if (read_enable) false else rng.nextBoolean() // Ensure not both enabled


  def update(
    enable:                   Boolean,
    block_id:                 Int,
    core_state:               CoreState.Type,


          core_state = CoreState.DONE
        } else {
          // Use the last thread's next_pc (same as in module)
          current_pc = next_pc(ThreadsPerBlock - 1)