xref: /XiangShan/src/main/scala/xiangshan/backend/rename/Rename.scala (revision 870f462d572cd0ef6bf86c91dcda5a5fab6e99d3)
1/***************************************************************************************
2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3* Copyright (c) 2020-2021 Peng Cheng Laboratory
4*
5* XiangShan is licensed under Mulan PSL v2.
6* You can use this software according to the terms and conditions of the Mulan PSL v2.
7* You may obtain a copy of Mulan PSL v2 at:
8*          http://license.coscl.org.cn/MulanPSL2
9*
10* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13*
14* See the Mulan PSL v2 for more details.
15***************************************************************************************/
16
17package xiangshan.backend.rename
18
19import chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.util._
22import utility._
23import utils._
24import xiangshan._
25import xiangshan.backend.decode.{FusionDecodeInfo, Imm_I, Imm_LUI_LOAD, Imm_U}
26import xiangshan.backend.fu.FuType
27import xiangshan.backend.rename.freelist._
28import xiangshan.backend.rob.RobPtr
29import xiangshan.backend.rename.freelist._
30import xiangshan.mem.mdp._
31import xiangshan.backend.Bundles.{DecodedInst, DynInst}
32
33class Rename(implicit p: Parameters) extends XSModule with HasCircularQueuePtrHelper with HasPerfEvents {
34
35  // params alias
36  private val numRegSrc = backendParams.numRegSrc
37  private val numVecRegSrc = backendParams.numVecRegSrc
38  private val numVecRatPorts = numVecRegSrc + 1 // +1 dst
39
40  println(s"[Rename] numRegSrc: $numRegSrc")
41
42  val io = IO(new Bundle() {
43    val redirect = Flipped(ValidIO(new Redirect))
44    val robCommits = Input(new RobCommitIO)
45    // from decode
46    val in = Vec(RenameWidth, Flipped(DecoupledIO(new DecodedInst)))
47    val fusionInfo = Vec(DecodeWidth - 1, Flipped(new FusionDecodeInfo))
48    // ssit read result
49    val ssit = Flipped(Vec(RenameWidth, Output(new SSITEntry)))
50    // waittable read result
51    val waittable = Flipped(Vec(RenameWidth, Output(Bool())))
52    // to rename table
53    val intReadPorts = Vec(RenameWidth, Vec(3, Input(UInt(PhyRegIdxWidth.W))))
54    val fpReadPorts = Vec(RenameWidth, Vec(4, Input(UInt(PhyRegIdxWidth.W))))
55    val vecReadPorts = Vec(RenameWidth, Vec(numVecRatPorts, Input(UInt(PhyRegIdxWidth.W))))
56    val intRenamePorts = Vec(RenameWidth, Output(new RatWritePort))
57    val fpRenamePorts = Vec(RenameWidth, Output(new RatWritePort))
58    val vecRenamePorts = Vec(RenameWidth, Output(new RatWritePort))
59    // from rename table
60    val int_old_pdest = Vec(CommitWidth, Input(UInt(PhyRegIdxWidth.W)))
61    val fp_old_pdest = Vec(CommitWidth, Input(UInt(PhyRegIdxWidth.W)))
62    val int_need_free = Vec(CommitWidth, Input(Bool()))
63    // to dispatch1
64    val out = Vec(RenameWidth, DecoupledIO(new DynInst))
65    // for snapshots
66    val snpt = Input(new SnapshotPort)
67    // debug arch ports
68    val debug_int_rat = Vec(32, Input(UInt(PhyRegIdxWidth.W)))
69    val debug_vconfig_rat = Input(UInt(PhyRegIdxWidth.W))
70    val debug_fp_rat = Vec(32, Input(UInt(PhyRegIdxWidth.W)))
71    val debug_vec_rat = Vec(32, Input(UInt(PhyRegIdxWidth.W)))
72    // perf only
73    val stallReason = new Bundle {
74      val in = Flipped(new StallReasonIO(RenameWidth))
75      val out = new StallReasonIO(RenameWidth)
76    }
77  })
78
79  // create free list and rat
80  val intFreeList = Module(new MEFreeList(IntPhyRegs))
81  val fpFreeList = Module(new StdFreeList(VfPhyRegs - FpLogicRegs - VecLogicRegs))
82
83  intFreeList.io.commit    <> io.robCommits
84  intFreeList.io.debug_rat <> io.debug_int_rat
85  fpFreeList.io.commit     <> io.robCommits
86  fpFreeList.io.debug_rat  <> io.debug_fp_rat
87
88  // decide if given instruction needs allocating a new physical register (CfCtrl: from decode; RobCommitInfo: from rob)
89  // fp and vec share `fpFreeList`
90  def needDestReg[T <: DecodedInst](reg_t: RegType, x: T): Bool = reg_t match {
91    case Reg_I => x.rfWen && x.ldest =/= 0.U
92    case Reg_F => x.fpWen
93    case Reg_V => x.vecWen
94  }
95  def needDestRegCommit[T <: RobCommitInfo](reg_t: RegType, x: T): Bool = {
96    reg_t match {
97      case Reg_I => x.rfWen
98      case Reg_F => x.fpWen
99      case Reg_V => x.vecWen
100    }
101  }
102  def needDestRegWalk[T <: RobCommitInfo](reg_t: RegType, x: T): Bool = {
103    reg_t match {
104      case Reg_I => x.rfWen && x.ldest =/= 0.U
105      case Reg_F => x.fpWen
106      case Reg_V => x.vecWen
107    }
108  }
109
110  // connect [redirect + walk] ports for __float point__ & __integer__ free list
111  Seq(fpFreeList, intFreeList).foreach { case fl =>
112    fl.io.redirect := io.redirect.valid
113    fl.io.walk := io.robCommits.isWalk
114  }
115  // only when both fp and int free list and dispatch1 has enough space can we do allocation
116  // when isWalk, freelist can definitely allocate
117  intFreeList.io.doAllocate := fpFreeList.io.canAllocate && io.out(0).ready || io.robCommits.isWalk
118  fpFreeList.io.doAllocate := intFreeList.io.canAllocate && io.out(0).ready || io.robCommits.isWalk
119
120  //           dispatch1 ready ++ float point free list ready ++ int free list ready      ++ not walk
121  val canOut = io.out(0).ready && fpFreeList.io.canAllocate && intFreeList.io.canAllocate && !io.robCommits.isWalk
122
123
124  // speculatively assign the instruction with an robIdx
125  val validCount = PopCount(io.in.map(in => in.valid && in.bits.lastUop)) // number of instructions waiting to enter rob (from decode)
126  val robIdxHead = RegInit(0.U.asTypeOf(new RobPtr))
127  val lastCycleMisprediction = RegNext(io.redirect.valid && !io.redirect.bits.flushItself())
128  val robIdxHeadNext = Mux(io.redirect.valid, io.redirect.bits.robIdx, // redirect: move ptr to given rob index
129         Mux(lastCycleMisprediction, robIdxHead + 1.U, // mis-predict: not flush robIdx itself
130                         Mux(canOut, robIdxHead + validCount, // instructions successfully entered next stage: increase robIdx
131                      /* default */  robIdxHead))) // no instructions passed by this cycle: stick to old value
132  robIdxHead := robIdxHeadNext
133
134  /**
135    * Rename: allocate free physical register and update rename table
136    */
137  val uops = Wire(Vec(RenameWidth, new DynInst))
138  uops.foreach( uop => {
139    uop.srcState      := DontCare
140    uop.robIdx        := DontCare
141    uop.debugInfo     := DontCare
142    uop.lqIdx         := DontCare
143    uop.sqIdx         := DontCare
144    uop.waitForRobIdx := DontCare
145    uop.singleStep    := DontCare
146    uop.snapshot      := DontCare
147  })
148
149  require(RenameWidth >= CommitWidth)
150  val needVecDest    = Wire(Vec(RenameWidth, Bool()))
151  val needFpDest     = Wire(Vec(RenameWidth, Bool()))
152  val needIntDest    = Wire(Vec(RenameWidth, Bool()))
153  val hasValid = Cat(io.in.map(_.valid)).orR
154
155  val isMove = io.in.map(_.bits.isMove)
156
157  val walkNeedIntDest = WireDefault(VecInit(Seq.fill(RenameWidth)(false.B)))
158  val walkNeedFpDest = WireDefault(VecInit(Seq.fill(RenameWidth)(false.B)))
159  val walkNeedVecDest = WireDefault(VecInit(Seq.fill(RenameWidth)(false.B)))
160  val walkIsMove = WireDefault(VecInit(Seq.fill(RenameWidth)(false.B)))
161
162  val intSpecWen = Wire(Vec(RenameWidth, Bool()))
163  val fpSpecWen  = Wire(Vec(RenameWidth, Bool()))
164  val vecSpecWen = Wire(Vec(RenameWidth, Bool()))
165
166  val walkIntSpecWen = WireDefault(VecInit(Seq.fill(RenameWidth)(false.B)))
167
168  val walkPdest = Wire(Vec(RenameWidth, UInt(PhyRegIdxWidth.W)))
169
170  // uop calculation
171  for (i <- 0 until RenameWidth) {
172    for ((name, data) <- uops(i).elements) {
173      if (io.in(i).bits.elements.contains(name)) {
174        data := io.in(i).bits.elements(name)
175      }
176    }
177
178    // update cf according to ssit result
179    uops(i).storeSetHit := io.ssit(i).valid
180    uops(i).loadWaitStrict := io.ssit(i).strict && io.ssit(i).valid
181    uops(i).ssid := io.ssit(i).ssid
182
183    // update cf according to waittable result
184    uops(i).loadWaitBit := io.waittable(i)
185
186    uops(i).replayInst := false.B // set by IQ or MemQ
187    // alloc a new phy reg, fp and vec share the `fpFreeList`
188    needVecDest   (i) := io.in(i).valid && needDestReg(Reg_V,       io.in(i).bits)
189    needFpDest    (i) := io.in(i).valid && needDestReg(Reg_F,       io.in(i).bits)
190    needIntDest   (i) := io.in(i).valid && needDestReg(Reg_I,       io.in(i).bits)
191    if (i < CommitWidth) {
192      walkNeedIntDest(i) := io.robCommits.walkValid(i) && needDestRegWalk(Reg_I, io.robCommits.info(i))
193      walkNeedFpDest(i) := io.robCommits.walkValid(i) && needDestRegWalk(Reg_F, io.robCommits.info(i))
194      walkNeedVecDest(i) := io.robCommits.walkValid(i) && needDestRegWalk(Reg_V, io.robCommits.info(i))
195      walkIsMove(i) := io.robCommits.info(i).isMove
196    }
197    fpFreeList.io.allocateReq(i) := needFpDest(i) || needVecDest(i)
198    fpFreeList.io.walkReq(i) := walkNeedFpDest(i) || walkNeedVecDest(i)
199    intFreeList.io.allocateReq(i) := needIntDest(i) && !isMove(i)
200    intFreeList.io.walkReq(i) := walkNeedIntDest(i) && !walkIsMove(i)
201
202    // no valid instruction from decode stage || all resources (dispatch1 + both free lists) ready
203    io.in(i).ready := !hasValid || canOut
204
205    uops(i).robIdx := robIdxHead + PopCount(io.in.take(i).map(in => in.valid && in.bits.lastUop))
206
207    uops(i).psrc(0) := Mux1H(uops(i).srcType(0), Seq(io.intReadPorts(i)(0), io.fpReadPorts(i)(0), io.vecReadPorts(i)(0)))
208    uops(i).psrc(1) := Mux1H(uops(i).srcType(1), Seq(io.intReadPorts(i)(1), io.fpReadPorts(i)(1), io.vecReadPorts(i)(1)))
209    uops(i).psrc(2) := Mux1H(uops(i).srcType(2)(2, 1), Seq(io.fpReadPorts(i)(2), io.vecReadPorts(i)(2)))
210    uops(i).psrc(3) := io.vecReadPorts(i)(3)
211    uops(i).psrc(4) := io.vecReadPorts(i)(4) // Todo: vl read port
212
213    // int psrc2 should be bypassed from next instruction if it is fused
214    if (i < RenameWidth - 1) {
215      when (io.fusionInfo(i).rs2FromRs2 || io.fusionInfo(i).rs2FromRs1) {
216        uops(i).psrc(1) := Mux(io.fusionInfo(i).rs2FromRs2, io.intReadPorts(i + 1)(1), io.intReadPorts(i + 1)(0))
217      }.elsewhen(io.fusionInfo(i).rs2FromZero) {
218        uops(i).psrc(1) := 0.U
219      }
220    }
221    uops(i).psrc(2) := io.fpReadPorts(i)(2)
222    // Todo
223    // uops(i).old_pdest := Mux(uops(i).ctrl.rfWen, io.intReadPorts(i).last, io.fpReadPorts(i).last)
224    uops(i).eliminatedMove := isMove(i)
225
226    // update pdest
227    uops(i).pdest := MuxCase(0.U, Seq(
228      needIntDest(i)                    -> intFreeList.io.allocatePhyReg(i),
229      (needFpDest(i) || needVecDest(i)) -> fpFreeList.io.allocatePhyReg(i),
230    ))
231
232    // Assign performance counters
233    uops(i).debugInfo.renameTime := GTimer()
234
235    io.out(i).valid := io.in(i).valid && intFreeList.io.canAllocate && fpFreeList.io.canAllocate && !io.robCommits.isWalk
236    io.out(i).bits := uops(i)
237    // Todo: move these shit in decode stage
238    // dirty code for fence. The lsrc is passed by imm.
239    when (io.out(i).bits.fuType === FuType.fence.U) {
240      io.out(i).bits.imm := Cat(io.in(i).bits.lsrc(1), io.in(i).bits.lsrc(0))
241    }
242
243    // dirty code for SoftPrefetch (prefetch.r/prefetch.w)
244//    when (io.in(i).bits.isSoftPrefetch) {
245//      io.out(i).bits.fuType := FuType.ldu.U
246//      io.out(i).bits.fuOpType := Mux(io.in(i).bits.lsrc(1) === 1.U, LSUOpType.prefetch_r, LSUOpType.prefetch_w)
247//      io.out(i).bits.selImm := SelImm.IMM_S
248//      io.out(i).bits.imm := Cat(io.in(i).bits.imm(io.in(i).bits.imm.getWidth - 1, 5), 0.U(5.W))
249//    }
250
251    // write speculative rename table
252    // we update rat later inside commit code
253    intSpecWen(i) := needIntDest(i) && intFreeList.io.canAllocate && intFreeList.io.doAllocate && !io.robCommits.isWalk && !io.redirect.valid
254    fpSpecWen(i) := needFpDest(i) && fpFreeList.io.canAllocate && fpFreeList.io.doAllocate && !io.robCommits.isWalk && !io.redirect.valid
255    vecSpecWen(i) := needVecDest(i) && fpFreeList.io.canAllocate && fpFreeList.io.doAllocate && !io.robCommits.isWalk && !io.redirect.valid
256
257    if (i < CommitWidth) {
258      walkIntSpecWen(i) := walkNeedIntDest(i) && !io.redirect.valid
259      walkPdest(i) := io.robCommits.info(i).pdest
260    } else {
261      walkPdest(i) := io.out(i).bits.pdest
262    }
263  }
264
265  /**
266    * How to set psrc:
267    * - bypass the pdest to psrc if previous instructions write to the same ldest as lsrc
268    * - default: psrc from RAT
269    * How to set pdest:
270    * - Mux(isMove, psrc, pdest_from_freelist).
271    *
272    * The critical path of rename lies here:
273    * When move elimination is enabled, we need to update the rat with psrc.
274    * However, psrc maybe comes from previous instructions' pdest, which comes from freelist.
275    *
276    * If we expand these logic for pdest(N):
277    * pdest(N) = Mux(isMove(N), psrc(N), freelist_out(N))
278    *          = Mux(isMove(N), Mux(bypass(N, N - 1), pdest(N - 1),
279    *                           Mux(bypass(N, N - 2), pdest(N - 2),
280    *                           ...
281    *                           Mux(bypass(N, 0),     pdest(0),
282    *                                                 rat_out(N))...)),
283    *                           freelist_out(N))
284    */
285  // a simple functional model for now
286  io.out(0).bits.pdest := Mux(isMove(0), uops(0).psrc.head, uops(0).pdest)
287
288  // psrc(n) + pdest(1)
289  val bypassCond: Vec[MixedVec[UInt]] = Wire(Vec(numRegSrc + 1, MixedVec(List.tabulate(RenameWidth-1)(i => UInt((i+1).W)))))
290  require(io.in(0).bits.srcType.size == io.in(0).bits.numSrc)
291  private val pdestLoc = io.in.head.bits.srcType.size // 2 vector src: v0, vl&vtype
292  println(s"[Rename] idx of pdest in bypassCond $pdestLoc")
293  for (i <- 1 until RenameWidth) {
294    val vecCond = io.in(i).bits.srcType.map(_ === SrcType.vp) :+ needVecDest(i)
295    val fpCond  = io.in(i).bits.srcType.map(_ === SrcType.fp) :+ needFpDest(i)
296    val intCond = io.in(i).bits.srcType.map(_ === SrcType.xp) :+ needIntDest(i)
297    val target = io.in(i).bits.lsrc :+ io.in(i).bits.ldest
298    for (((((cond1, cond2), cond3), t), j) <- vecCond.zip(fpCond).zip(intCond).zip(target).zipWithIndex) {
299      val destToSrc = io.in.take(i).zipWithIndex.map { case (in, j) =>
300        val indexMatch = in.bits.ldest === t
301        val writeMatch =  cond3 && needIntDest(j) || cond2 && needFpDest(j) || cond1 && needVecDest(j)
302        indexMatch && writeMatch
303      }
304      bypassCond(j)(i - 1) := VecInit(destToSrc).asUInt
305    }
306    io.out(i).bits.psrc(0) := io.out.take(i).map(_.bits.pdest).zip(bypassCond(0)(i-1).asBools).foldLeft(uops(i).psrc(0)) {
307      (z, next) => Mux(next._2, next._1, z)
308    }
309    io.out(i).bits.psrc(1) := io.out.take(i).map(_.bits.pdest).zip(bypassCond(1)(i-1).asBools).foldLeft(uops(i).psrc(1)) {
310      (z, next) => Mux(next._2, next._1, z)
311    }
312    io.out(i).bits.psrc(2) := io.out.take(i).map(_.bits.pdest).zip(bypassCond(2)(i-1).asBools).foldLeft(uops(i).psrc(2)) {
313      (z, next) => Mux(next._2, next._1, z)
314    }
315    io.out(i).bits.psrc(3) := io.out.take(i).map(_.bits.pdest).zip(bypassCond(3)(i-1).asBools).foldLeft(uops(i).psrc(3)) {
316      (z, next) => Mux(next._2, next._1, z)
317    }
318    io.out(i).bits.psrc(4) := io.out.take(i).map(_.bits.pdest).zip(bypassCond(4)(i-1).asBools).foldLeft(uops(i).psrc(4)) {
319      (z, next) => Mux(next._2, next._1, z)
320    }
321    io.out(i).bits.pdest := Mux(isMove(i), io.out(i).bits.psrc(0), uops(i).pdest)
322
323    // Todo: better implementation for fields reuse
324    // For fused-lui-load, load.src(0) is replaced by the imm.
325    val last_is_lui = io.in(i - 1).bits.selImm === SelImm.IMM_U && io.in(i - 1).bits.srcType(0) =/= SrcType.pc
326    val this_is_load = io.in(i).bits.fuType === FuType.ldu.U
327    val lui_to_load = io.in(i - 1).valid && io.in(i - 1).bits.ldest === io.in(i).bits.lsrc(0)
328    val fused_lui_load = last_is_lui && this_is_load && lui_to_load && false.B // Todo: enable it
329    when (fused_lui_load) {
330      // The first LOAD operand (base address) is replaced by LUI-imm and stored in {psrc, imm}
331      val lui_imm = io.in(i - 1).bits.imm(19, 0)
332      val ld_imm = io.in(i).bits.imm
333      io.out(i).bits.srcType(0) := SrcType.imm
334      io.out(i).bits.imm := Imm_LUI_LOAD().immFromLuiLoad(lui_imm, ld_imm)
335      val psrcWidth = uops(i).psrc.head.getWidth
336      val lui_imm_in_imm = 20/*Todo: uops(i).imm.getWidth*/ - Imm_I().len
337      val left_lui_imm = Imm_U().len - lui_imm_in_imm
338      require(2 * psrcWidth >= left_lui_imm, "cannot fused lui and load with psrc")
339      io.out(i).bits.psrc(0) := lui_imm(lui_imm_in_imm + psrcWidth - 1, lui_imm_in_imm)
340      io.out(i).bits.psrc(1) := lui_imm(lui_imm.getWidth - 1, lui_imm_in_imm + psrcWidth)
341    }
342
343  }
344
345  val hasCFI = VecInit(io.in.map(in => (!in.bits.preDecodeInfo.notCFI || FuType.isJump(in.bits.fuType)) && in.fire)).asUInt.orR
346  val snapshotCtr = RegInit((4 * CommitWidth).U)
347  val allowSnpt = if (EnableRenameSnapshot) !snapshotCtr.orR else false.B
348  io.out.head.bits.snapshot := hasCFI && allowSnpt
349  when(io.out.head.fire && io.out.head.bits.snapshot) {
350    snapshotCtr := (4 * CommitWidth).U - PopCount(io.out.map(_.fire))
351  }.elsewhen(io.out.head.fire) {
352    snapshotCtr := Mux(snapshotCtr < PopCount(io.out.map(_.fire)), 0.U, snapshotCtr - PopCount(io.out.map(_.fire)))
353  }
354
355  intFreeList.io.snpt := io.snpt
356  fpFreeList.io.snpt := io.snpt
357  intFreeList.io.snpt.snptEnq := io.out.head.fire && io.out.head.bits.snapshot
358  fpFreeList.io.snpt.snptEnq := io.out.head.fire && io.out.head.bits.snapshot
359
360  /**
361    * Instructions commit: update freelist and rename table
362    */
363  for (i <- 0 until CommitWidth) {
364    val commitValid = io.robCommits.isCommit && io.robCommits.commitValid(i)
365    val walkValid = io.robCommits.isWalk && io.robCommits.walkValid(i)
366
367    // I. RAT Update
368    // When redirect happens (mis-prediction), don't update the rename table
369    io.intRenamePorts(i).wen  := intSpecWen(i)
370    io.intRenamePorts(i).addr := uops(i).ldest
371    io.intRenamePorts(i).data := io.out(i).bits.pdest
372
373    io.fpRenamePorts(i).wen  := fpSpecWen(i)
374    io.fpRenamePorts(i).addr := uops(i).ldest
375    io.fpRenamePorts(i).data := fpFreeList.io.allocatePhyReg(i)
376
377    io.vecRenamePorts(i).wen := vecSpecWen(i)
378    io.vecRenamePorts(i).addr := uops(i).ldest
379    io.vecRenamePorts(i).data := fpFreeList.io.allocatePhyReg(i)
380
381    // II. Free List Update
382    intFreeList.io.freeReq(i) := io.int_need_free(i)
383    intFreeList.io.freePhyReg(i) := RegNext(io.int_old_pdest(i))
384    fpFreeList.io.freeReq(i)  := RegNext(commitValid && (needDestRegCommit(Reg_F, io.robCommits.info(i)) || needDestRegCommit(Reg_V, io.robCommits.info(i))))
385    fpFreeList.io.freePhyReg(i) := io.fp_old_pdest(i)
386  }
387
388  /*
389  Debug and performance counters
390   */
391  def printRenameInfo(in: DecoupledIO[DecodedInst], out: DecoupledIO[DynInst]) = {
392    XSInfo(out.fire, p"pc:${Hexadecimal(in.bits.pc)} in(${in.valid},${in.ready}) " +
393      p"lsrc(0):${in.bits.lsrc(0)} -> psrc(0):${out.bits.psrc(0)} " +
394      p"lsrc(1):${in.bits.lsrc(1)} -> psrc(1):${out.bits.psrc(1)} " +
395      p"lsrc(2):${in.bits.lsrc(2)} -> psrc(2):${out.bits.psrc(2)} " +
396      p"ldest:${in.bits.ldest} -> pdest:${out.bits.pdest}\n"
397    )
398  }
399
400  for ((x,y) <- io.in.zip(io.out)) {
401    printRenameInfo(x, y)
402  }
403
404  val debugRedirect = RegEnable(io.redirect.bits, io.redirect.valid)
405  // bad speculation
406  val recStall = io.redirect.valid || io.robCommits.isWalk
407  val ctrlRecStall = Mux(io.redirect.valid, io.redirect.bits.debugIsCtrl, io.robCommits.isWalk && debugRedirect.debugIsCtrl)
408  val mvioRecStall = Mux(io.redirect.valid, io.redirect.bits.debugIsMemVio, io.robCommits.isWalk && debugRedirect.debugIsMemVio)
409  val otherRecStall = recStall && !(ctrlRecStall || mvioRecStall)
410  XSPerfAccumulate("recovery_stall", recStall)
411  XSPerfAccumulate("control_recovery_stall", ctrlRecStall)
412  XSPerfAccumulate("mem_violation_recovery_stall", mvioRecStall)
413  XSPerfAccumulate("other_recovery_stall", otherRecStall)
414  // freelist stall
415  val notRecStall = !io.out.head.valid && !recStall
416  val intFlStall = notRecStall && hasValid && !intFreeList.io.canAllocate
417  val fpFlStall = notRecStall && hasValid && !fpFreeList.io.canAllocate
418  // other stall
419  val otherStall = notRecStall && !intFlStall && !fpFlStall
420
421  io.stallReason.in.backReason.valid := io.stallReason.out.backReason.valid || !io.in.head.ready
422  io.stallReason.in.backReason.bits := Mux(io.stallReason.out.backReason.valid, io.stallReason.out.backReason.bits,
423    MuxCase(TopDownCounters.OtherCoreStall.id.U, Seq(
424      ctrlRecStall  -> TopDownCounters.ControlRecoveryStall.id.U,
425      mvioRecStall  -> TopDownCounters.MemVioRecoveryStall.id.U,
426      otherRecStall -> TopDownCounters.OtherRecoveryStall.id.U,
427      intFlStall    -> TopDownCounters.IntFlStall.id.U,
428      fpFlStall     -> TopDownCounters.FpFlStall.id.U
429    )
430  ))
431  io.stallReason.out.reason.zip(io.stallReason.in.reason).zip(io.in.map(_.valid)).foreach { case ((out, in), valid) =>
432    out := Mux(io.stallReason.in.backReason.valid,
433               io.stallReason.in.backReason.bits,
434               Mux(valid, TopDownCounters.NoStall.id.U, in))
435  }
436
437  XSDebug(io.robCommits.isWalk, p"Walk Recovery Enabled\n")
438  XSDebug(io.robCommits.isWalk, p"validVec:${Binary(io.robCommits.walkValid.asUInt)}\n")
439  for (i <- 0 until CommitWidth) {
440    val info = io.robCommits.info(i)
441    XSDebug(io.robCommits.isWalk && io.robCommits.walkValid(i), p"[#$i walk info] pc:${Hexadecimal(info.pc)} " +
442      p"ldest:${info.ldest} rfWen:${info.rfWen} fpWen:${info.fpWen} vecWen:${info.vecWen}")
443  }
444
445  XSDebug(p"inValidVec: ${Binary(Cat(io.in.map(_.valid)))}\n")
446
447  XSPerfAccumulate("in", Mux(RegNext(io.in(0).ready), PopCount(io.in.map(_.valid)), 0.U))
448  XSPerfAccumulate("utilization", PopCount(io.in.map(_.valid)))
449  XSPerfAccumulate("waitInstr", PopCount((0 until RenameWidth).map(i => io.in(i).valid && !io.in(i).ready)))
450  XSPerfAccumulate("stall_cycle_dispatch", hasValid && !io.out(0).ready && fpFreeList.io.canAllocate && intFreeList.io.canAllocate && !io.robCommits.isWalk)
451  XSPerfAccumulate("stall_cycle_fp", hasValid && io.out(0).ready && !fpFreeList.io.canAllocate && intFreeList.io.canAllocate && !io.robCommits.isWalk)
452  XSPerfAccumulate("stall_cycle_int", hasValid && io.out(0).ready && fpFreeList.io.canAllocate && !intFreeList.io.canAllocate && !io.robCommits.isWalk)
453  XSPerfAccumulate("stall_cycle_walk", hasValid && io.out(0).ready && fpFreeList.io.canAllocate && intFreeList.io.canAllocate && io.robCommits.isWalk)
454
455  XSPerfHistogram("slots_fire", PopCount(io.out.map(_.fire)), true.B, 0, RenameWidth+1, 1)
456  // Explaination: when out(0) not fire, PopCount(valid) is not meaningfull
457  XSPerfHistogram("slots_valid_pure", PopCount(io.in.map(_.valid)), io.out(0).fire, 0, RenameWidth+1, 1)
458  XSPerfHistogram("slots_valid_rough", PopCount(io.in.map(_.valid)), true.B, 0, RenameWidth+1, 1)
459
460  XSPerfAccumulate("move_instr_count", PopCount(io.out.map(out => out.fire && out.bits.isMove)))
461  val is_fused_lui_load = io.out.map(o => o.fire && o.bits.fuType === FuType.ldu.U && o.bits.srcType(0) === SrcType.imm)
462  XSPerfAccumulate("fused_lui_load_instr_count", PopCount(is_fused_lui_load))
463
464
465  val renamePerf = Seq(
466    ("rename_in                  ", PopCount(io.in.map(_.valid & io.in(0).ready ))                                                               ),
467    ("rename_waitinstr           ", PopCount((0 until RenameWidth).map(i => io.in(i).valid && !io.in(i).ready))                                  ),
468    ("rename_stall_cycle_dispatch", hasValid && !io.out(0).ready &&  fpFreeList.io.canAllocate &&  intFreeList.io.canAllocate && !io.robCommits.isWalk),
469    ("rename_stall_cycle_fp      ", hasValid &&  io.out(0).ready && !fpFreeList.io.canAllocate &&  intFreeList.io.canAllocate && !io.robCommits.isWalk),
470    ("rename_stall_cycle_int     ", hasValid &&  io.out(0).ready &&  fpFreeList.io.canAllocate && !intFreeList.io.canAllocate && !io.robCommits.isWalk),
471    ("rename_stall_cycle_walk    ", hasValid &&  io.out(0).ready &&  fpFreeList.io.canAllocate &&  intFreeList.io.canAllocate &&  io.robCommits.isWalk)
472  )
473  val intFlPerf = intFreeList.getPerfEvents
474  val fpFlPerf = fpFreeList.getPerfEvents
475  val perfEvents = renamePerf ++ intFlPerf ++ fpFlPerf
476  generatePerfEvent()
477}
478