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