xref: /XiangShan/src/main/scala/xiangshan/backend/rob/Rob.scala (revision 0f0389247d954d0a33001fd5dfee0f268a4e1712)
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.rob
18
19import chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.util._
22import difftest._
23import freechips.rocketchip.diplomacy.{LazyModule, LazyModuleImp}
24import utils._
25import utility._
26import xiangshan._
27import xiangshan.backend.exu.ExuConfig
28import xiangshan.frontend.FtqPtr
29
30class RobPtr(implicit p: Parameters) extends CircularQueuePtr[RobPtr](
31  p => p(XSCoreParamsKey).RobSize
32) with HasCircularQueuePtrHelper {
33
34  def needFlush(redirect: Valid[Redirect]): Bool = {
35    val flushItself = redirect.bits.flushItself() && this === redirect.bits.robIdx
36    redirect.valid && (flushItself || isAfter(this, redirect.bits.robIdx))
37  }
38
39  def needFlush(redirect: Seq[Valid[Redirect]]): Bool = VecInit(redirect.map(needFlush)).asUInt.orR
40}
41
42object RobPtr {
43  def apply(f: Bool, v: UInt)(implicit p: Parameters): RobPtr = {
44    val ptr = Wire(new RobPtr)
45    ptr.flag := f
46    ptr.value := v
47    ptr
48  }
49}
50
51class RobCSRIO(implicit p: Parameters) extends XSBundle {
52  val intrBitSet = Input(Bool())
53  val trapTarget = Input(UInt(VAddrBits.W))
54  val isXRet     = Input(Bool())
55  val wfiEvent   = Input(Bool())
56
57  val fflags     = Output(Valid(UInt(5.W)))
58  val dirty_fs   = Output(Bool())
59  val perfinfo   = new Bundle {
60    val retiredInstr = Output(UInt(3.W))
61  }
62
63  val vcsrFlag   = Output(Bool())
64}
65
66class RobLsqIO(implicit p: Parameters) extends XSBundle {
67  val lcommit = Output(UInt(log2Up(CommitWidth + 1).W))
68  val scommit = Output(UInt(log2Up(CommitWidth + 1).W))
69  val pendingld = Output(Bool())
70  val pendingst = Output(Bool())
71  val commit = Output(Bool())
72}
73
74class RobEnqIO(implicit p: Parameters) extends XSBundle {
75  val canAccept = Output(Bool())
76  val isEmpty = Output(Bool())
77  // valid vector, for robIdx gen and walk
78  val needAlloc = Vec(RenameWidth, Input(Bool()))
79  val req = Vec(RenameWidth, Flipped(ValidIO(new MicroOp)))
80  val resp = Vec(RenameWidth, Output(new RobPtr))
81}
82
83class RobDispatchData(implicit p: Parameters) extends RobCommitInfo
84
85class RobDeqPtrWrapper(implicit p: Parameters) extends XSModule with HasCircularQueuePtrHelper {
86  val io = IO(new Bundle {
87    // for commits/flush
88    val state = Input(UInt(2.W))
89    val deq_v = Vec(CommitWidth, Input(Bool()))
90    val deq_w = Vec(CommitWidth, Input(Bool()))
91    val exception_state = Flipped(ValidIO(new RobExceptionInfo))
92    // for flush: when exception occurs, reset deqPtrs to range(0, CommitWidth)
93    val intrBitSetReg = Input(Bool())
94    val hasNoSpecExec = Input(Bool())
95    val interrupt_safe = Input(Bool())
96    val blockCommit = Input(Bool())
97    // output: the CommitWidth deqPtr
98    val out = Vec(CommitWidth, Output(new RobPtr))
99    val next_out = Vec(CommitWidth, Output(new RobPtr))
100  })
101
102  val deqPtrVec = RegInit(VecInit((0 until CommitWidth).map(_.U.asTypeOf(new RobPtr))))
103
104  // for exceptions (flushPipe included) and interrupts:
105  // only consider the first instruction
106  val intrEnable = io.intrBitSetReg && !io.hasNoSpecExec && io.interrupt_safe
107  val exceptionEnable = io.deq_w(0) && io.exception_state.valid && io.exception_state.bits.not_commit && io.exception_state.bits.robIdx === deqPtrVec(0)
108  val redirectOutValid = io.state === 0.U && io.deq_v(0) && (intrEnable || exceptionEnable)
109
110  // for normal commits: only to consider when there're no exceptions
111  // we don't need to consider whether the first instruction has exceptions since it wil trigger exceptions.
112  val commit_exception = io.exception_state.valid && !isAfter(io.exception_state.bits.robIdx, deqPtrVec.last)
113  val canCommit = VecInit((0 until CommitWidth).map(i => io.deq_v(i) && io.deq_w(i)))
114  val normalCommitCnt = PriorityEncoder(canCommit.map(c => !c) :+ true.B)
115  // when io.intrBitSetReg or there're possible exceptions in these instructions,
116  // only one instruction is allowed to commit
117  val allowOnlyOne = commit_exception || io.intrBitSetReg
118  val commitCnt = Mux(allowOnlyOne, canCommit(0), normalCommitCnt)
119
120  val commitDeqPtrVec = VecInit(deqPtrVec.map(_ + commitCnt))
121  val deqPtrVec_next = Mux(io.state === 0.U && !redirectOutValid && !io.blockCommit, commitDeqPtrVec, deqPtrVec)
122
123  deqPtrVec := deqPtrVec_next
124
125  io.next_out := deqPtrVec_next
126  io.out      := deqPtrVec
127
128  when (io.state === 0.U) {
129    XSInfo(io.state === 0.U && commitCnt > 0.U, "retired %d insts\n", commitCnt)
130  }
131
132}
133
134class RobEnqPtrWrapper(implicit p: Parameters) extends XSModule with HasCircularQueuePtrHelper {
135  val io = IO(new Bundle {
136    // for input redirect
137    val redirect = Input(Valid(new Redirect))
138    // for enqueue
139    val allowEnqueue = Input(Bool())
140    val hasBlockBackward = Input(Bool())
141    val enq = Vec(RenameWidth, Input(Bool()))
142    val out = Output(Vec(RenameWidth, new RobPtr))
143  })
144
145  val enqPtrVec = RegInit(VecInit.tabulate(RenameWidth)(_.U.asTypeOf(new RobPtr)))
146
147  // enqueue
148  val canAccept = io.allowEnqueue && !io.hasBlockBackward
149  val dispatchNum = Mux(canAccept, PopCount(io.enq), 0.U)
150
151  for ((ptr, i) <- enqPtrVec.zipWithIndex) {
152    when(io.redirect.valid) {
153      ptr := Mux(io.redirect.bits.flushItself(), io.redirect.bits.robIdx + i.U, io.redirect.bits.robIdx + (i + 1).U)
154    }.otherwise {
155      ptr := ptr + dispatchNum
156    }
157  }
158
159  io.out := enqPtrVec
160
161}
162
163class RobExceptionInfo(implicit p: Parameters) extends XSBundle {
164  // val valid = Bool()
165  val robIdx = new RobPtr
166  val exceptionVec = ExceptionVec()
167  val flushPipe = Bool()
168  val isVset = Bool()
169  val replayInst = Bool() // redirect to that inst itself
170  val singleStep = Bool() // TODO add frontend hit beneath
171  val crossPageIPFFix = Bool()
172  val trigger = new TriggerCf
173
174//  def trigger_before = !trigger.getTimingBackend && trigger.getHitBackend
175//  def trigger_after = trigger.getTimingBackend && trigger.getHitBackend
176  def has_exception = exceptionVec.asUInt.orR || flushPipe || singleStep || replayInst || trigger.hit
177  def not_commit = exceptionVec.asUInt.orR || singleStep || replayInst || trigger.hit
178  // only exceptions are allowed to writeback when enqueue
179  def can_writeback = exceptionVec.asUInt.orR || singleStep || trigger.hit
180}
181
182class ExceptionGen(implicit p: Parameters) extends XSModule with HasCircularQueuePtrHelper {
183  val io = IO(new Bundle {
184    val redirect = Input(Valid(new Redirect))
185    val flush = Input(Bool())
186    val enq = Vec(RenameWidth, Flipped(ValidIO(new RobExceptionInfo)))
187    val wb = Vec(1 + LoadPipelineWidth + StorePipelineWidth, Flipped(ValidIO(new RobExceptionInfo)))
188    val out = ValidIO(new RobExceptionInfo)
189    val state = ValidIO(new RobExceptionInfo)
190  })
191
192  def getOldest(valid: Seq[Bool], bits: Seq[RobExceptionInfo]): (Seq[Bool], Seq[RobExceptionInfo]) = {
193    assert(valid.length == bits.length)
194    assert(isPow2(valid.length))
195    if (valid.length == 1) {
196      (valid, bits)
197    } else if (valid.length == 2) {
198      val res = Seq.fill(2)(Wire(ValidIO(chiselTypeOf(bits(0)))))
199      for (i <- res.indices) {
200        res(i).valid := valid(i)
201        res(i).bits := bits(i)
202      }
203      val oldest = Mux(!valid(1) || valid(0) && isAfter(bits(1).robIdx, bits(0).robIdx), res(0), res(1))
204      (Seq(oldest.valid), Seq(oldest.bits))
205    } else {
206      val left = getOldest(valid.take(valid.length / 2), bits.take(valid.length / 2))
207      val right = getOldest(valid.takeRight(valid.length / 2), bits.takeRight(valid.length / 2))
208      getOldest(left._1 ++ right._1, left._2 ++ right._2)
209    }
210  }
211
212  val currentValid = RegInit(false.B)
213  val current = Reg(new RobExceptionInfo)
214
215  // orR the exceptionVec
216  val lastCycleFlush = RegNext(io.flush)
217  val in_enq_valid = VecInit(io.enq.map(e => e.valid && e.bits.has_exception && !lastCycleFlush))
218  val in_wb_valid = io.wb.map(w => w.valid && w.bits.has_exception && !lastCycleFlush)
219
220  // s0: compare wb(1)~wb(LoadPipelineWidth) and wb(1 + LoadPipelineWidth)~wb(LoadPipelineWidth + StorePipelineWidth)
221  val wb_valid = in_wb_valid.zip(io.wb.map(_.bits)).map{ case (v, bits) => v && !(bits.robIdx.needFlush(io.redirect) || io.flush) }
222  val csr_wb_bits = io.wb(0).bits
223  val load_wb_bits = getOldest(in_wb_valid.slice(1, 1 + LoadPipelineWidth), io.wb.map(_.bits).slice(1, 1 + LoadPipelineWidth))._2(0)
224  val store_wb_bits = getOldest(in_wb_valid.slice(1 + LoadPipelineWidth, 1 + LoadPipelineWidth + StorePipelineWidth), io.wb.map(_.bits).slice(1 + LoadPipelineWidth, 1 + LoadPipelineWidth + StorePipelineWidth))._2(0)
225  val s0_out_valid = RegNext(VecInit(Seq(wb_valid(0), wb_valid.slice(1, 1 + LoadPipelineWidth).reduce(_ || _), wb_valid.slice(1 + LoadPipelineWidth, 1 + LoadPipelineWidth + StorePipelineWidth).reduce(_ || _))))
226  val s0_out_bits = RegNext(VecInit(Seq(csr_wb_bits, load_wb_bits, store_wb_bits)))
227
228  // s1: compare last four and current flush
229  val s1_valid = VecInit(s0_out_valid.zip(s0_out_bits).map{ case (v, b) => v && !(b.robIdx.needFlush(io.redirect) || io.flush) })
230  val compare_01_valid = s0_out_valid(0) || s0_out_valid(1)
231  val compare_01_bits = Mux(!s0_out_valid(0) || s0_out_valid(1) && isAfter(s0_out_bits(0).robIdx, s0_out_bits(1).robIdx), s0_out_bits(1), s0_out_bits(0))
232  val compare_bits = Mux(!s0_out_valid(2) || compare_01_valid && isAfter(s0_out_bits(2).robIdx, compare_01_bits.robIdx), compare_01_bits, s0_out_bits(2))
233  val s1_out_bits = RegNext(compare_bits)
234  val s1_out_valid = RegNext(s1_valid.asUInt.orR)
235
236  val enq_valid = RegNext(in_enq_valid.asUInt.orR && !io.redirect.valid && !io.flush)
237  val enq_bits = RegNext(ParallelPriorityMux(in_enq_valid, io.enq.map(_.bits)))
238
239  // s2: compare the input exception with the current one
240  // priorities:
241  // (1) system reset
242  // (2) current is valid: flush, remain, merge, update
243  // (3) current is not valid: s1 or enq
244  val current_flush = current.robIdx.needFlush(io.redirect) || io.flush
245  val s1_flush = s1_out_bits.robIdx.needFlush(io.redirect) || io.flush
246  when (currentValid) {
247    when (current_flush) {
248      currentValid := Mux(s1_flush, false.B, s1_out_valid)
249    }
250    when (s1_out_valid && !s1_flush) {
251      when (isAfter(current.robIdx, s1_out_bits.robIdx)) {
252        current := s1_out_bits
253      }.elsewhen (current.robIdx === s1_out_bits.robIdx) {
254        current.exceptionVec := (s1_out_bits.exceptionVec.asUInt | current.exceptionVec.asUInt).asTypeOf(ExceptionVec())
255        current.flushPipe := s1_out_bits.flushPipe || current.flushPipe
256        current.replayInst := s1_out_bits.replayInst || current.replayInst
257        current.singleStep := s1_out_bits.singleStep || current.singleStep
258        current.trigger := (s1_out_bits.trigger.asUInt | current.trigger.asUInt).asTypeOf(new TriggerCf)
259      }
260    }
261  }.elsewhen (s1_out_valid && !s1_flush) {
262    currentValid := true.B
263    current := s1_out_bits
264  }.elsewhen (enq_valid && !(io.redirect.valid || io.flush)) {
265    currentValid := true.B
266    current := enq_bits
267  }
268
269  io.out.valid   := s1_out_valid || enq_valid && enq_bits.can_writeback
270  io.out.bits    := Mux(s1_out_valid, s1_out_bits, enq_bits)
271  io.state.valid := currentValid
272  io.state.bits  := current
273
274}
275
276class RobFlushInfo(implicit p: Parameters) extends XSBundle {
277  val ftqIdx = new FtqPtr
278  val robIdx = new RobPtr
279  val ftqOffset = UInt(log2Up(PredictWidth).W)
280  val replayInst = Bool()
281}
282
283class Rob(implicit p: Parameters) extends LazyModule with HasWritebackSink with HasXSParameter {
284
285  lazy val module = new RobImp(this)
286
287  override def generateWritebackIO(
288    thisMod: Option[HasWritebackSource] = None,
289    thisModImp: Option[HasWritebackSourceImp] = None
290  ): Unit = {
291    val sources = writebackSinksImp(thisMod, thisModImp)
292    module.io.writeback.zip(sources).foreach(x => x._1 := x._2)
293  }
294}
295
296class RobImp(outer: Rob)(implicit p: Parameters) extends LazyModuleImp(outer)
297  with HasXSParameter with HasCircularQueuePtrHelper with HasPerfEvents {
298  val wbExuConfigs = outer.writebackSinksParams.map(_.exuConfigs)
299  val numWbPorts = wbExuConfigs.map(_.length)
300
301  val io = IO(new Bundle() {
302    val hartId = Input(UInt(8.W))
303    val redirect = Input(Valid(new Redirect))
304    val enq = new RobEnqIO
305    val flushOut = ValidIO(new Redirect)
306    val isVsetFlushPipe = Output(Bool())
307    val exception = ValidIO(new ExceptionInfo)
308    // exu + brq
309    val writeback = MixedVec(numWbPorts.map(num => Vec(num, Flipped(ValidIO(new ExuOutput)))))
310    val commits = Output(new RobCommitIO)
311    val lsq = new RobLsqIO
312    val robDeqPtr = Output(new RobPtr)
313    val csr = new RobCSRIO
314    val robFull = Output(Bool())
315    val cpu_halt = Output(Bool())
316    val wfi_enable = Input(Bool())
317  })
318
319  def selectWb(index: Int, func: Seq[ExuConfig] => Boolean): Seq[(Seq[ExuConfig], ValidIO[ExuOutput])] = {
320    wbExuConfigs(index).zip(io.writeback(index)).filter(x => func(x._1))
321  }
322  val exeWbSel = outer.selWritebackSinks(_.exuConfigs.length)
323  val fflagsWbSel = outer.selWritebackSinks(_.exuConfigs.count(_.exists(_.writeFflags)))
324  val fflagsPorts = selectWb(fflagsWbSel, _.exists(_.writeFflags))
325  val exceptionWbSel = outer.selWritebackSinks(_.exuConfigs.count(_.exists(_.needExceptionGen)))
326  val exceptionPorts = selectWb(fflagsWbSel, _.exists(_.needExceptionGen))
327  val exuWbPorts = selectWb(exeWbSel, _.forall(_ != StdExeUnitCfg))
328  val stdWbPorts = selectWb(exeWbSel, _.contains(StdExeUnitCfg))
329  println(s"Rob: size $RobSize, numWbPorts: $numWbPorts, commitwidth: $CommitWidth")
330  println(s"exuPorts: ${exuWbPorts.map(_._1.map(_.name))}")
331  println(s"stdPorts: ${stdWbPorts.map(_._1.map(_.name))}")
332  println(s"fflags: ${fflagsPorts.map(_._1.map(_.name))}")
333
334
335  val exuWriteback = exuWbPorts.map(_._2)
336  val stdWriteback = stdWbPorts.map(_._2)
337
338  // instvalid field
339  val valid = RegInit(VecInit(Seq.fill(RobSize)(false.B)))
340  // writeback status
341  val writebacked = Mem(RobSize, Bool())
342  val store_data_writebacked = Mem(RobSize, Bool())
343  // data for redirect, exception, etc.
344  val flagBkup = Mem(RobSize, Bool())
345  // some instructions are not allowed to trigger interrupts
346  // They have side effects on the states of the processor before they write back
347  val interrupt_safe = Mem(RobSize, Bool())
348
349  // data for debug
350  // Warn: debug_* prefix should not exist in generated verilog.
351  val debug_microOp = Mem(RobSize, new MicroOp)
352  val debug_exuData = Reg(Vec(RobSize, UInt(XLEN.W)))//for debug
353  val debug_exuDebug = Reg(Vec(RobSize, new DebugBundle))//for debug
354
355  // pointers
356  // For enqueue ptr, we don't duplicate it since only enqueue needs it.
357  val enqPtrVec = Wire(Vec(RenameWidth, new RobPtr))
358  val deqPtrVec = Wire(Vec(CommitWidth, new RobPtr))
359
360  val walkPtrVec = Reg(Vec(CommitWidth, new RobPtr))
361  val allowEnqueue = RegInit(true.B)
362
363  val enqPtr = enqPtrVec.head
364  val deqPtr = deqPtrVec(0)
365  val walkPtr = walkPtrVec(0)
366
367  val isEmpty = enqPtr === deqPtr
368  val isReplaying = io.redirect.valid && RedirectLevel.flushItself(io.redirect.bits.level)
369
370  /**
371    * states of Rob
372    */
373  val s_idle :: s_walk :: Nil = Enum(2)
374  val state = RegInit(s_idle)
375
376  /**
377    * Data Modules
378    *
379    * CommitDataModule: data from dispatch
380    * (1) read: commits/walk/exception
381    * (2) write: enqueue
382    *
383    * WritebackData: data from writeback
384    * (1) read: commits/walk/exception
385    * (2) write: write back from exe units
386    */
387  val dispatchData = Module(new SyncDataModuleTemplate(new RobDispatchData, RobSize, CommitWidth, RenameWidth))
388  val dispatchDataRead = dispatchData.io.rdata
389
390  val exceptionGen = Module(new ExceptionGen)
391  val exceptionDataRead = exceptionGen.io.state
392  val fflagsDataRead = Wire(Vec(CommitWidth, UInt(5.W)))
393
394  io.robDeqPtr := deqPtr
395
396  /**
397    * Enqueue (from dispatch)
398    */
399  // special cases
400  val hasBlockBackward = RegInit(false.B)
401  val hasNoSpecExec = RegInit(false.B)
402  val doingSvinval = RegInit(false.B)
403  // When blockBackward instruction leaves Rob (commit or walk), hasBlockBackward should be set to false.B
404  // To reduce registers usage, for hasBlockBackward cases, we allow enqueue after ROB is empty.
405  when (isEmpty) { hasBlockBackward:= false.B }
406  // When any instruction commits, hasNoSpecExec should be set to false.B
407  when (io.commits.hasWalkInstr || io.commits.hasCommitInstr) { hasNoSpecExec:= false.B }
408
409  // The wait-for-interrupt (WFI) instruction waits in the ROB until an interrupt might need servicing.
410  // io.csr.wfiEvent will be asserted if the WFI can resume execution, and we change the state to s_wfi_idle.
411  // It does not affect how interrupts are serviced. Note that WFI is noSpecExec and it does not trigger interrupts.
412  val hasWFI = RegInit(false.B)
413  io.cpu_halt := hasWFI
414  // WFI Timeout: 2^20 = 1M cycles
415  val wfi_cycles = RegInit(0.U(20.W))
416  when (hasWFI) {
417    wfi_cycles := wfi_cycles + 1.U
418  }.elsewhen (!hasWFI && RegNext(hasWFI)) {
419    wfi_cycles := 0.U
420  }
421  val wfi_timeout = wfi_cycles.andR
422  when (RegNext(RegNext(io.csr.wfiEvent)) || io.flushOut.valid || wfi_timeout) {
423    hasWFI := false.B
424  }
425
426  val allocatePtrVec = VecInit((0 until RenameWidth).map(i => enqPtrVec(PopCount(io.enq.needAlloc.take(i)))))
427  io.enq.canAccept := allowEnqueue && !hasBlockBackward
428  io.enq.resp      := allocatePtrVec
429  val canEnqueue = VecInit(io.enq.req.map(_.valid && io.enq.canAccept))
430  val timer = GTimer()
431  for (i <- 0 until RenameWidth) {
432    // we don't check whether io.redirect is valid here since redirect has higher priority
433    when (canEnqueue(i)) {
434      val enqUop = io.enq.req(i).bits
435      val enqIndex = allocatePtrVec(i).value
436      // store uop in data module and debug_microOp Vec
437      debug_microOp(enqIndex) := enqUop
438      debug_microOp(enqIndex).debugInfo.dispatchTime := timer
439      debug_microOp(enqIndex).debugInfo.enqRsTime := timer
440      debug_microOp(enqIndex).debugInfo.selectTime := timer
441      debug_microOp(enqIndex).debugInfo.issueTime := timer
442      debug_microOp(enqIndex).debugInfo.writebackTime := timer
443      when (enqUop.ctrl.blockBackward) {
444        hasBlockBackward := true.B
445      }
446      when (enqUop.ctrl.noSpecExec) {
447        hasNoSpecExec := true.B
448      }
449      val enqHasTriggerHit = io.enq.req(i).bits.cf.trigger.getHitFrontend
450      val enqHasException = ExceptionNO.selectFrontend(enqUop.cf.exceptionVec).asUInt.orR
451      // the begin instruction of Svinval enqs so mark doingSvinval as true to indicate this process
452      when(!enqHasTriggerHit && !enqHasException && FuType.isSvinvalBegin(enqUop.ctrl.fuType, enqUop.ctrl.fuOpType, enqUop.ctrl.flushPipe))
453      {
454        doingSvinval := true.B
455      }
456      // the end instruction of Svinval enqs so clear doingSvinval
457      when(!enqHasTriggerHit && !enqHasException && FuType.isSvinvalEnd(enqUop.ctrl.fuType, enqUop.ctrl.fuOpType, enqUop.ctrl.flushPipe))
458      {
459        doingSvinval := false.B
460      }
461      // when we are in the process of Svinval software code area , only Svinval.vma and end instruction of Svinval can appear
462      assert(!doingSvinval || (FuType.isSvinval(enqUop.ctrl.fuType, enqUop.ctrl.fuOpType, enqUop.ctrl.flushPipe) ||
463        FuType.isSvinvalEnd(enqUop.ctrl.fuType, enqUop.ctrl.fuOpType, enqUop.ctrl.flushPipe)))
464      when (enqUop.ctrl.isWFI && !enqHasException && !enqHasTriggerHit) {
465        hasWFI := true.B
466      }
467    }
468  }
469  val dispatchNum = Mux(io.enq.canAccept, PopCount(io.enq.req.map(_.valid)), 0.U)
470  io.enq.isEmpty   := RegNext(isEmpty && !VecInit(io.enq.req.map(_.valid)).asUInt.orR)
471
472  when (!io.wfi_enable) {
473    hasWFI := false.B
474  }
475  // sel vsetvl's flush position
476  val vs_idle :: vs_waitVinstr :: vs_waitFlush :: Nil = Enum(3)
477  val vsetvlState = RegInit(vs_idle)
478
479  val firstVInstrFtqPtr    = RegInit(0.U.asTypeOf(new FtqPtr))
480  val firstVInstrFtqOffset = RegInit(0.U.asTypeOf(UInt(log2Up(PredictWidth).W)))
481  val firstVInstrRobIdx    = RegInit(0.U.asTypeOf(new RobPtr))
482
483  val enq0            = io.enq.req(0)
484  val enq0IsVset      = FuType.isIntExu(enq0.bits.ctrl.fuType) && ALUOpType.isVset(enq0.bits.ctrl.fuOpType) && enq0.bits.ctrl.uopIdx.andR && canEnqueue(0)
485  val enq0IsVsetFlush = enq0IsVset && enq0.bits.ctrl.flushPipe
486  val enqIsVInstrVec = io.enq.req.zip(canEnqueue).map{case (req, fire) => FuType.isVpu(req.bits.ctrl.fuType) && fire}
487  // for vs_idle
488  val firstVInstrIdle = PriorityMux(enqIsVInstrVec.zip(io.enq.req).drop(1) :+ (true.B, 0.U.asTypeOf(io.enq.req(0).cloneType)))
489  // for vs_waitVinstr
490  val enqIsVInstrOrVset = (enqIsVInstrVec(0) || enq0IsVset) +: enqIsVInstrVec.drop(1)
491  val firstVInstrWait = PriorityMux(enqIsVInstrOrVset, io.enq.req)
492  when(vsetvlState === vs_idle){
493    firstVInstrFtqPtr    := firstVInstrIdle.bits.cf.ftqPtr
494    firstVInstrFtqOffset := firstVInstrIdle.bits.cf.ftqOffset
495    firstVInstrRobIdx    := firstVInstrIdle.bits.robIdx
496  }.elsewhen(vsetvlState === vs_waitVinstr){
497    firstVInstrFtqPtr    := firstVInstrWait.bits.cf.ftqPtr
498    firstVInstrFtqOffset := firstVInstrWait.bits.cf.ftqOffset
499    firstVInstrRobIdx    := firstVInstrWait.bits.robIdx
500  }
501
502  val hasVInstrAfterI = Cat(enqIsVInstrVec(0)).orR
503  when(vsetvlState === vs_idle){
504    when(enq0IsVsetFlush){
505      vsetvlState := Mux(hasVInstrAfterI, vs_waitFlush, vs_waitVinstr)
506    }
507  }.elsewhen(vsetvlState === vs_waitVinstr){
508    when(io.redirect.valid){
509      vsetvlState := vs_idle
510    }.elsewhen(Cat(enqIsVInstrOrVset).orR){
511      vsetvlState := vs_waitFlush
512    }
513  }.elsewhen(vsetvlState === vs_waitFlush){
514    when(io.redirect.valid){
515      vsetvlState := vs_idle
516    }
517  }
518
519  /**
520    * Writeback (from execution units)
521    */
522  for (wb <- exuWriteback) {
523    when (wb.valid) {
524      val wbIdx = wb.bits.uop.robIdx.value
525      debug_exuData(wbIdx) := wb.bits.data
526      debug_exuDebug(wbIdx) := wb.bits.debug
527      debug_microOp(wbIdx).debugInfo.enqRsTime := wb.bits.uop.debugInfo.enqRsTime
528      debug_microOp(wbIdx).debugInfo.selectTime := wb.bits.uop.debugInfo.selectTime
529      debug_microOp(wbIdx).debugInfo.issueTime := wb.bits.uop.debugInfo.issueTime
530      debug_microOp(wbIdx).debugInfo.writebackTime := wb.bits.uop.debugInfo.writebackTime
531
532      // debug for lqidx and sqidx
533      debug_microOp(wbIdx).lqIdx := wb.bits.uop.lqIdx
534      debug_microOp(wbIdx).sqIdx := wb.bits.uop.sqIdx
535
536      val debug_Uop = debug_microOp(wbIdx)
537      XSInfo(true.B,
538        p"writebacked pc 0x${Hexadecimal(debug_Uop.cf.pc)} wen ${debug_Uop.ctrl.rfWen} " +
539        p"data 0x${Hexadecimal(wb.bits.data)} ldst ${debug_Uop.ctrl.ldest} pdst ${debug_Uop.pdest} " +
540        p"skip ${wb.bits.debug.isMMIO} robIdx: ${wb.bits.uop.robIdx}\n"
541      )
542    }
543  }
544  val writebackNum = PopCount(exuWriteback.map(_.valid))
545  XSInfo(writebackNum =/= 0.U, "writebacked %d insts\n", writebackNum)
546
547
548  /**
549    * RedirectOut: Interrupt and Exceptions
550    */
551  val deqDispatchData = dispatchDataRead(0)
552  val debug_deqUop = debug_microOp(deqPtr.value)
553
554  val intrBitSetReg = RegNext(io.csr.intrBitSet)
555  val intrEnable = intrBitSetReg && !hasNoSpecExec && interrupt_safe(deqPtr.value)
556  val deqHasExceptionOrFlush = exceptionDataRead.valid && exceptionDataRead.bits.robIdx === deqPtr
557  val deqHasException = deqHasExceptionOrFlush && (exceptionDataRead.bits.exceptionVec.asUInt.orR ||
558    exceptionDataRead.bits.singleStep || exceptionDataRead.bits.trigger.hit)
559  val deqHasFlushPipe = deqHasExceptionOrFlush && exceptionDataRead.bits.flushPipe
560  val deqHasReplayInst = deqHasExceptionOrFlush && exceptionDataRead.bits.replayInst
561  val exceptionEnable = writebacked(deqPtr.value) && deqHasException
562
563  XSDebug(deqHasException && exceptionDataRead.bits.singleStep, "Debug Mode: Deq has singlestep exception\n")
564  XSDebug(deqHasException && exceptionDataRead.bits.trigger.getHitFrontend, "Debug Mode: Deq has frontend trigger exception\n")
565  XSDebug(deqHasException && exceptionDataRead.bits.trigger.getHitBackend, "Debug Mode: Deq has backend trigger exception\n")
566
567  val isFlushPipe = writebacked(deqPtr.value) && (deqHasFlushPipe || deqHasReplayInst)
568
569  val isVsetFlushPipe = writebacked(deqPtr.value) && deqHasFlushPipe && exceptionDataRead.bits.isVset
570  val needModifyFtqIdxOffset = isVsetFlushPipe && (vsetvlState === vs_waitFlush)
571  io.isVsetFlushPipe := RegNext(isVsetFlushPipe)
572  // io.flushOut will trigger redirect at the next cycle.
573  // Block any redirect or commit at the next cycle.
574  val lastCycleFlush = RegNext(io.flushOut.valid)
575
576  io.flushOut.valid := (state === s_idle) && valid(deqPtr.value) && (intrEnable || exceptionEnable || isFlushPipe) && !lastCycleFlush
577  io.flushOut.bits := DontCare
578  io.flushOut.bits.robIdx := Mux(needModifyFtqIdxOffset, firstVInstrRobIdx, deqPtr)
579  io.flushOut.bits.ftqIdx := Mux(needModifyFtqIdxOffset, firstVInstrFtqPtr, deqDispatchData.ftqIdx)
580  io.flushOut.bits.ftqOffset := Mux(needModifyFtqIdxOffset, firstVInstrFtqOffset, deqDispatchData.ftqOffset)
581  io.flushOut.bits.level := Mux(deqHasReplayInst || intrEnable || exceptionEnable || needModifyFtqIdxOffset, RedirectLevel.flush, RedirectLevel.flushAfter) // TODO use this to implement "exception next"
582  io.flushOut.bits.interrupt := true.B
583  XSPerfAccumulate("interrupt_num", io.flushOut.valid && intrEnable)
584  XSPerfAccumulate("exception_num", io.flushOut.valid && exceptionEnable)
585  XSPerfAccumulate("flush_pipe_num", io.flushOut.valid && isFlushPipe)
586  XSPerfAccumulate("replay_inst_num", io.flushOut.valid && isFlushPipe && deqHasReplayInst)
587
588  val exceptionHappen = (state === s_idle) && valid(deqPtr.value) && (intrEnable || exceptionEnable) && !lastCycleFlush
589  io.exception.valid := RegNext(exceptionHappen)
590  io.exception.bits.uop := RegEnable(debug_deqUop, exceptionHappen)
591  io.exception.bits.uop.ctrl.commitType := RegEnable(deqDispatchData.commitType, exceptionHappen)
592  io.exception.bits.uop.cf.exceptionVec := RegEnable(exceptionDataRead.bits.exceptionVec, exceptionHappen)
593  io.exception.bits.uop.ctrl.singleStep := RegEnable(exceptionDataRead.bits.singleStep, exceptionHappen)
594  io.exception.bits.uop.cf.crossPageIPFFix := RegEnable(exceptionDataRead.bits.crossPageIPFFix, exceptionHappen)
595  io.exception.bits.isInterrupt := RegEnable(intrEnable, exceptionHappen)
596  io.exception.bits.uop.cf.trigger := RegEnable(exceptionDataRead.bits.trigger, exceptionHappen)
597
598  XSDebug(io.flushOut.valid,
599    p"generate redirect: pc 0x${Hexadecimal(io.exception.bits.uop.cf.pc)} intr $intrEnable " +
600    p"excp $exceptionEnable flushPipe $isFlushPipe " +
601    p"Trap_target 0x${Hexadecimal(io.csr.trapTarget)} exceptionVec ${Binary(exceptionDataRead.bits.exceptionVec.asUInt)}\n")
602
603
604  /**
605    * Commits (and walk)
606    * They share the same width.
607    */
608  val walkCounter = Reg(UInt(log2Up(RobSize + 1).W))
609  val shouldWalkVec = VecInit((0 until CommitWidth).map(_.U < walkCounter))
610  val walkFinished = walkCounter <= CommitWidth.U
611
612  require(RenameWidth <= CommitWidth)
613
614  // wiring to csr
615  val (wflags, fpWen) = (0 until CommitWidth).map(i => {
616    val v = io.commits.commitValid(i)
617    val info = io.commits.info(i)
618    (v & info.wflags, v & info.fpWen)
619  }).unzip
620  val fflags = Wire(Valid(UInt(5.W)))
621  fflags.valid := io.commits.isCommit && VecInit(wflags).asUInt.orR
622  fflags.bits := wflags.zip(fflagsDataRead).map({
623    case (w, f) => Mux(w, f, 0.U)
624  }).reduce(_|_)
625  val dirty_fs = io.commits.isCommit && VecInit(fpWen).asUInt.orR
626
627  // when mispredict branches writeback, stop commit in the next 2 cycles
628  // TODO: don't check all exu write back
629  val misPredWb = Cat(VecInit(exuWriteback.map(wb =>
630    wb.bits.redirect.cfiUpdate.isMisPred && wb.bits.redirectValid
631  ))).orR
632  val misPredBlockCounter = Reg(UInt(3.W))
633  misPredBlockCounter := Mux(misPredWb,
634    "b111".U,
635    misPredBlockCounter >> 1.U
636  )
637  val misPredBlock = misPredBlockCounter(0)
638  val blockCommit = misPredBlock || isReplaying || lastCycleFlush || hasWFI
639
640  io.commits.isWalk := state === s_walk
641  io.commits.isCommit := state === s_idle && !blockCommit
642  val walk_v = VecInit(walkPtrVec.map(ptr => valid(ptr.value)))
643  val commit_v = VecInit(deqPtrVec.map(ptr => valid(ptr.value)))
644  // store will be commited iff both sta & std have been writebacked
645  val commit_w = VecInit(deqPtrVec.map(ptr => writebacked(ptr.value) && store_data_writebacked(ptr.value)))
646  val commit_exception = exceptionDataRead.valid && !isAfter(exceptionDataRead.bits.robIdx, deqPtrVec.last)
647  val commit_block = VecInit((0 until CommitWidth).map(i => !commit_w(i)))
648  val allowOnlyOneCommit = commit_exception || intrBitSetReg
649  // for instructions that may block others, we don't allow them to commit
650  for (i <- 0 until CommitWidth) {
651    // defaults: state === s_idle and instructions commit
652    // when intrBitSetReg, allow only one instruction to commit at each clock cycle
653    val isBlocked = if (i != 0) Cat(commit_block.take(i)).orR || allowOnlyOneCommit else intrEnable || deqHasException || deqHasReplayInst
654    io.commits.commitValid(i) := commit_v(i) && commit_w(i) && !isBlocked
655    io.commits.info(i)  := dispatchDataRead(i)
656
657    when (state === s_walk) {
658      io.commits.walkValid(i) := shouldWalkVec(i)
659      when (io.commits.isWalk && state === s_walk && shouldWalkVec(i)) {
660        XSError(!walk_v(i), s"why not $i???\n")
661      }
662    }
663
664    XSInfo(io.commits.isCommit && io.commits.commitValid(i),
665      "retired pc %x wen %d ldest %d pdest %x old_pdest %x data %x fflags: %b\n",
666      debug_microOp(deqPtrVec(i).value).cf.pc,
667      io.commits.info(i).rfWen,
668      io.commits.info(i).ldest,
669      io.commits.info(i).pdest,
670      io.commits.info(i).old_pdest,
671      debug_exuData(deqPtrVec(i).value),
672      fflagsDataRead(i)
673    )
674    XSInfo(state === s_walk && io.commits.walkValid(i), "walked pc %x wen %d ldst %d data %x\n",
675      debug_microOp(walkPtrVec(i).value).cf.pc,
676      io.commits.info(i).rfWen,
677      io.commits.info(i).ldest,
678      debug_exuData(walkPtrVec(i).value)
679    )
680  }
681  if (env.EnableDifftest) {
682    io.commits.info.map(info => dontTouch(info.pc))
683  }
684
685  // sync fflags/dirty_fs to csr
686  io.csr.fflags := RegNext(fflags)
687  io.csr.dirty_fs := RegNext(dirty_fs)
688
689  // sync v csr to csr
690//  io.csr.vcsrFlag := RegNext(isVsetFlushPipe)
691
692  // commit load/store to lsq
693  val ldCommitVec = VecInit((0 until CommitWidth).map(i => io.commits.commitValid(i) && io.commits.info(i).commitType === CommitType.LOAD))
694  val stCommitVec = VecInit((0 until CommitWidth).map(i => io.commits.commitValid(i) && io.commits.info(i).commitType === CommitType.STORE))
695  io.lsq.lcommit := RegNext(Mux(io.commits.isCommit, PopCount(ldCommitVec), 0.U))
696  io.lsq.scommit := RegNext(Mux(io.commits.isCommit, PopCount(stCommitVec), 0.U))
697  // indicate a pending load or store
698  io.lsq.pendingld := RegNext(io.commits.isCommit && io.commits.info(0).commitType === CommitType.LOAD && valid(deqPtr.value))
699  io.lsq.pendingst := RegNext(io.commits.isCommit && io.commits.info(0).commitType === CommitType.STORE && valid(deqPtr.value))
700  io.lsq.commit := RegNext(io.commits.isCommit && io.commits.commitValid(0))
701
702  /**
703    * state changes
704    * (1) redirect: switch to s_walk
705    * (2) walk: when walking comes to the end, switch to s_idle
706    */
707  val state_next = Mux(io.redirect.valid, s_walk, Mux(state === s_walk && walkFinished, s_idle, state))
708  XSPerfAccumulate("s_idle_to_idle",            state === s_idle && state_next === s_idle)
709  XSPerfAccumulate("s_idle_to_walk",            state === s_idle && state_next === s_walk)
710  XSPerfAccumulate("s_walk_to_idle",            state === s_walk && state_next === s_idle)
711  XSPerfAccumulate("s_walk_to_walk",            state === s_walk && state_next === s_walk)
712  state := state_next
713
714  /**
715    * pointers and counters
716    */
717  val deqPtrGenModule = Module(new RobDeqPtrWrapper)
718  deqPtrGenModule.io.state := state
719  deqPtrGenModule.io.deq_v := commit_v
720  deqPtrGenModule.io.deq_w := commit_w
721  deqPtrGenModule.io.exception_state := exceptionDataRead
722  deqPtrGenModule.io.intrBitSetReg := intrBitSetReg
723  deqPtrGenModule.io.hasNoSpecExec := hasNoSpecExec
724  deqPtrGenModule.io.interrupt_safe := interrupt_safe(deqPtr.value)
725  deqPtrGenModule.io.blockCommit := blockCommit
726  deqPtrVec := deqPtrGenModule.io.out
727  val deqPtrVec_next = deqPtrGenModule.io.next_out
728
729  val enqPtrGenModule = Module(new RobEnqPtrWrapper)
730  enqPtrGenModule.io.redirect := io.redirect
731  enqPtrGenModule.io.allowEnqueue := allowEnqueue
732  enqPtrGenModule.io.hasBlockBackward := hasBlockBackward
733  enqPtrGenModule.io.enq := VecInit(io.enq.req.map(_.valid))
734  enqPtrVec := enqPtrGenModule.io.out
735
736  val thisCycleWalkCount = Mux(walkFinished, walkCounter, CommitWidth.U)
737  // next walkPtrVec:
738  // (1) redirect occurs: update according to state
739  // (2) walk: move forwards
740  val walkPtrVec_next = Mux(io.redirect.valid,
741    deqPtrVec_next,
742    Mux(state === s_walk, VecInit(walkPtrVec.map(_ + CommitWidth.U)), walkPtrVec)
743  )
744  walkPtrVec := walkPtrVec_next
745
746  val numValidEntries = distanceBetween(enqPtr, deqPtr)
747  val isLastUopVec = io.commits.info.map(_.uopIdx.andR)
748  val commitCnt = PopCount(io.commits.commitValid.zip(isLastUopVec).map{case(isCommitValid, isLastUop) => isCommitValid && isLastUop})
749
750  allowEnqueue := numValidEntries + dispatchNum <= (RobSize - RenameWidth).U
751
752  val currentWalkPtr = Mux(state === s_walk, walkPtr, deqPtrVec_next(0))
753  val redirectWalkDistance = distanceBetween(io.redirect.bits.robIdx, deqPtrVec_next(0))
754  when (io.redirect.valid) {
755    // full condition:
756    // +& is used here because:
757    // When rob is full and the tail instruction causes a misprediction,
758    // the redirect robIdx is the deqPtr - 1. In this case, redirectWalkDistance
759    // is RobSize - 1.
760    // Since misprediction does not flush the instruction itself, flushItSelf is false.B.
761    // Previously we use `+` to count the walk distance and it causes overflows
762    // when RobSize is power of 2. We change it to `+&` to allow walkCounter to be RobSize.
763    // The width of walkCounter also needs to be changed.
764    // empty condition:
765    // When the last instruction in ROB commits and causes a flush, a redirect
766    // will be raised later. In such circumstances, the redirect robIdx is before
767    // the deqPtrVec_next(0) and will cause underflow.
768    walkCounter := Mux(isBefore(io.redirect.bits.robIdx, deqPtrVec_next(0)), 0.U,
769                       redirectWalkDistance +& !io.redirect.bits.flushItself())
770  }.elsewhen (state === s_walk) {
771    walkCounter := walkCounter - thisCycleWalkCount
772    XSInfo(p"rolling back: $enqPtr $deqPtr walk $walkPtr walkcnt $walkCounter\n")
773  }
774
775
776  /**
777    * States
778    * We put all the stage bits changes here.
779
780    * All events: (1) enqueue (dispatch); (2) writeback; (3) cancel; (4) dequeue (commit);
781    * All states: (1) valid; (2) writebacked; (3) flagBkup
782    */
783  val commitReadAddr = Mux(state === s_idle, VecInit(deqPtrVec.map(_.value)), VecInit(walkPtrVec.map(_.value)))
784
785  // redirect logic writes 6 valid
786  val redirectHeadVec = Reg(Vec(RenameWidth, new RobPtr))
787  val redirectTail = Reg(new RobPtr)
788  val redirectIdle :: redirectBusy :: Nil = Enum(2)
789  val redirectState = RegInit(redirectIdle)
790  val invMask = redirectHeadVec.map(redirectHead => isBefore(redirectHead, redirectTail))
791  when(redirectState === redirectBusy) {
792    redirectHeadVec.foreach(redirectHead => redirectHead := redirectHead + RenameWidth.U)
793    redirectHeadVec zip invMask foreach {
794      case (redirectHead, inv) => when(inv) {
795        valid(redirectHead.value) := false.B
796      }
797    }
798    when(!invMask.last) {
799      redirectState := redirectIdle
800    }
801  }
802  when(io.redirect.valid) {
803    redirectState := redirectBusy
804    when(redirectState === redirectIdle) {
805      redirectTail := enqPtr
806    }
807    redirectHeadVec.zipWithIndex.foreach { case (redirectHead, i) =>
808      redirectHead := Mux(io.redirect.bits.flushItself(), io.redirect.bits.robIdx + i.U, io.redirect.bits.robIdx + (i + 1).U)
809    }
810  }
811  // enqueue logic writes 6 valid
812  for (i <- 0 until RenameWidth) {
813    when (canEnqueue(i) && !io.redirect.valid) {
814      valid(allocatePtrVec(i).value) := true.B
815    }
816  }
817  // dequeue logic writes 6 valid
818  for (i <- 0 until CommitWidth) {
819    val commitValid = io.commits.isCommit && io.commits.commitValid(i)
820    when (commitValid) {
821      valid(commitReadAddr(i)) := false.B
822    }
823  }
824
825  // status field: writebacked
826  // enqueue logic set 6 writebacked to false
827  for (i <- 0 until RenameWidth) {
828    when (canEnqueue(i)) {
829      val enqHasException = ExceptionNO.selectFrontend(io.enq.req(i).bits.cf.exceptionVec).asUInt.orR
830      val enqHasTriggerHit = io.enq.req(i).bits.cf.trigger.getHitFrontend
831      val enqIsWritebacked = io.enq.req(i).bits.eliminatedMove
832      writebacked(allocatePtrVec(i).value) := enqIsWritebacked && !enqHasException && !enqHasTriggerHit
833      val isStu = io.enq.req(i).bits.ctrl.fuType === FuType.stu
834      store_data_writebacked(allocatePtrVec(i).value) := !isStu
835    }
836  }
837  when (exceptionGen.io.out.valid) {
838    val wbIdx = exceptionGen.io.out.bits.robIdx.value
839    writebacked(wbIdx) := true.B
840    store_data_writebacked(wbIdx) := true.B
841  }
842  // writeback logic set numWbPorts writebacked to true
843  for ((wb, cfgs) <- exuWriteback.zip(wbExuConfigs(exeWbSel))) {
844    when (wb.valid) {
845      val wbIdx = wb.bits.uop.robIdx.value
846      val wbHasException = ExceptionNO.selectByExu(wb.bits.uop.cf.exceptionVec, cfgs).asUInt.orR
847      val wbHasTriggerHit = wb.bits.uop.cf.trigger.getHitBackend
848      val wbHasFlushPipe = cfgs.exists(_.flushPipe).B && wb.bits.uop.ctrl.flushPipe
849      val wbHasReplayInst = cfgs.exists(_.replayInst).B && wb.bits.uop.ctrl.replayInst
850      val block_wb = wbHasException || wbHasFlushPipe || wbHasReplayInst || wbHasTriggerHit
851      writebacked(wbIdx) := !block_wb
852    }
853  }
854  // store data writeback logic mark store as data_writebacked
855  for (wb <- stdWriteback) {
856    when(RegNext(wb.valid)) {
857      store_data_writebacked(RegNext(wb.bits.uop.robIdx.value)) := true.B
858    }
859  }
860
861  // flagBkup
862  // enqueue logic set 6 flagBkup at most
863  for (i <- 0 until RenameWidth) {
864    when (canEnqueue(i)) {
865      flagBkup(allocatePtrVec(i).value) := allocatePtrVec(i).flag
866    }
867  }
868
869  // interrupt_safe
870  for (i <- 0 until RenameWidth) {
871    // We RegNext the updates for better timing.
872    // Note that instructions won't change the system's states in this cycle.
873    when (RegNext(canEnqueue(i))) {
874      // For now, we allow non-load-store instructions to trigger interrupts
875      // For MMIO instructions, they should not trigger interrupts since they may
876      // be sent to lower level before it writes back.
877      // However, we cannot determine whether a load/store instruction is MMIO.
878      // Thus, we don't allow load/store instructions to trigger an interrupt.
879      // TODO: support non-MMIO load-store instructions to trigger interrupts
880      val allow_interrupts = !CommitType.isLoadStore(io.enq.req(i).bits.ctrl.commitType)
881      interrupt_safe(RegNext(allocatePtrVec(i).value)) := RegNext(allow_interrupts)
882    }
883  }
884
885  /**
886    * read and write of data modules
887    */
888  val commitReadAddr_next = Mux(state_next === s_idle,
889    VecInit(deqPtrVec_next.map(_.value)),
890    VecInit(walkPtrVec_next.map(_.value))
891  )
892  dispatchData.io.wen := canEnqueue
893  dispatchData.io.waddr := allocatePtrVec.map(_.value)
894  dispatchData.io.wdata.zip(io.enq.req.map(_.bits)).foreach{ case (wdata, req) =>
895    wdata.ldest := req.ctrl.ldest
896    wdata.rfWen := req.ctrl.rfWen
897    wdata.fpWen := req.ctrl.fpWen
898    wdata.vecWen := req.ctrl.vecWen
899    wdata.wflags := req.ctrl.fpu.wflags
900    wdata.commitType := req.ctrl.commitType
901    wdata.pdest := req.pdest
902    wdata.old_pdest := req.old_pdest
903    wdata.ftqIdx := req.cf.ftqPtr
904    wdata.ftqOffset := req.cf.ftqOffset
905    wdata.isMove := req.eliminatedMove
906    wdata.pc := req.cf.pc
907    wdata.uopIdx := req.ctrl.uopIdx
908    wdata.vconfig := req.ctrl.vconfig
909  }
910  dispatchData.io.raddr := commitReadAddr_next
911
912  exceptionGen.io.redirect <> io.redirect
913  exceptionGen.io.flush := io.flushOut.valid
914  for (i <- 0 until RenameWidth) {
915    exceptionGen.io.enq(i).valid := canEnqueue(i)
916    exceptionGen.io.enq(i).bits.robIdx := io.enq.req(i).bits.robIdx
917    exceptionGen.io.enq(i).bits.exceptionVec := ExceptionNO.selectFrontend(io.enq.req(i).bits.cf.exceptionVec)
918    exceptionGen.io.enq(i).bits.flushPipe := io.enq.req(i).bits.ctrl.flushPipe
919    exceptionGen.io.enq(i).bits.isVset := FuType.isIntExu(io.enq.req(i).bits.ctrl.fuType) && ALUOpType.isVset(io.enq.req(i).bits.ctrl.fuOpType)
920    exceptionGen.io.enq(i).bits.replayInst := false.B
921    XSError(canEnqueue(i) && io.enq.req(i).bits.ctrl.replayInst, "enq should not set replayInst")
922    exceptionGen.io.enq(i).bits.singleStep := io.enq.req(i).bits.ctrl.singleStep
923    exceptionGen.io.enq(i).bits.crossPageIPFFix := io.enq.req(i).bits.cf.crossPageIPFFix
924    exceptionGen.io.enq(i).bits.trigger.clear()
925    exceptionGen.io.enq(i).bits.trigger.frontendHit := io.enq.req(i).bits.cf.trigger.frontendHit
926  }
927
928  println(s"ExceptionGen:")
929  val exceptionCases = exceptionPorts.map(_._1.flatMap(_.exceptionOut).distinct.sorted)
930  require(exceptionCases.length == exceptionGen.io.wb.length)
931  for ((((configs, wb), exc_wb), i) <- exceptionPorts.zip(exceptionGen.io.wb).zipWithIndex) {
932    exc_wb.valid                := wb.valid
933    exc_wb.bits.robIdx          := wb.bits.uop.robIdx
934    exc_wb.bits.exceptionVec    := ExceptionNO.selectByExu(wb.bits.uop.cf.exceptionVec, configs)
935    exc_wb.bits.flushPipe       := configs.exists(_.flushPipe).B && wb.bits.uop.ctrl.flushPipe
936    exc_wb.bits.isVset          := false.B
937    exc_wb.bits.replayInst      := configs.exists(_.replayInst).B && wb.bits.uop.ctrl.replayInst
938    exc_wb.bits.singleStep      := false.B
939    exc_wb.bits.crossPageIPFFix := false.B
940    // TODO: make trigger configurable
941    exc_wb.bits.trigger.clear()
942    exc_wb.bits.trigger.backendHit := wb.bits.uop.cf.trigger.backendHit
943    println(s"  [$i] ${configs.map(_.name)}: exception ${exceptionCases(i)}, " +
944      s"flushPipe ${configs.exists(_.flushPipe)}, " +
945      s"replayInst ${configs.exists(_.replayInst)}")
946  }
947
948  val fflags_wb = fflagsPorts.map(_._2)
949  val fflagsDataModule = Module(new SyncDataModuleTemplate(
950    UInt(5.W), RobSize, CommitWidth, fflags_wb.size)
951  )
952  for(i <- fflags_wb.indices){
953    fflagsDataModule.io.wen  (i) := fflags_wb(i).valid
954    fflagsDataModule.io.waddr(i) := fflags_wb(i).bits.uop.robIdx.value
955    fflagsDataModule.io.wdata(i) := fflags_wb(i).bits.fflags
956  }
957  fflagsDataModule.io.raddr := VecInit(deqPtrVec_next.map(_.value))
958  fflagsDataRead := fflagsDataModule.io.rdata
959
960
961  val instrCntReg = RegInit(0.U(64.W))
962  val fuseCommitCnt = PopCount(io.commits.commitValid.zip(io.commits.info).map{ case (v, i) => RegNext(v && CommitType.isFused(i.commitType)) })
963  val trueCommitCnt = RegNext(commitCnt) +& fuseCommitCnt
964  val retireCounter = Mux(RegNext(io.commits.isCommit), trueCommitCnt, 0.U)
965  val instrCnt = instrCntReg + retireCounter
966  instrCntReg := instrCnt
967  io.csr.perfinfo.retiredInstr := retireCounter
968  io.robFull := !allowEnqueue
969
970  /**
971    * debug info
972    */
973  XSDebug(p"enqPtr ${enqPtr} deqPtr ${deqPtr}\n")
974  XSDebug("")
975  for(i <- 0 until RobSize){
976    XSDebug(false, !valid(i), "-")
977    XSDebug(false, valid(i) && writebacked(i), "w")
978    XSDebug(false, valid(i) && !writebacked(i), "v")
979  }
980  XSDebug(false, true.B, "\n")
981
982  for(i <- 0 until RobSize) {
983    if(i % 4 == 0) XSDebug("")
984    XSDebug(false, true.B, "%x ", debug_microOp(i).cf.pc)
985    XSDebug(false, !valid(i), "- ")
986    XSDebug(false, valid(i) && writebacked(i), "w ")
987    XSDebug(false, valid(i) && !writebacked(i), "v ")
988    if(i % 4 == 3) XSDebug(false, true.B, "\n")
989  }
990
991  def ifCommit(counter: UInt): UInt = Mux(io.commits.isCommit, counter, 0.U)
992  def ifCommitReg(counter: UInt): UInt = Mux(RegNext(io.commits.isCommit), counter, 0.U)
993
994  val commitDebugUop = deqPtrVec.map(_.value).map(debug_microOp(_))
995  XSPerfAccumulate("clock_cycle", 1.U)
996  QueuePerf(RobSize, PopCount((0 until RobSize).map(valid(_))), !allowEnqueue)
997  XSPerfAccumulate("commitUop", ifCommit(commitCnt))
998  XSPerfAccumulate("commitInstr", ifCommitReg(trueCommitCnt))
999  val commitIsMove = commitDebugUop.map(_.ctrl.isMove)
1000  XSPerfAccumulate("commitInstrMove", ifCommit(PopCount(io.commits.commitValid.zip(commitIsMove).map{ case (v, m) => v && m })))
1001  val commitMoveElim = commitDebugUop.map(_.debugInfo.eliminatedMove)
1002  XSPerfAccumulate("commitInstrMoveElim", ifCommit(PopCount(io.commits.commitValid zip commitMoveElim map { case (v, e) => v && e })))
1003  XSPerfAccumulate("commitInstrFused", ifCommitReg(fuseCommitCnt))
1004  val commitIsLoad = io.commits.info.map(_.commitType).map(_ === CommitType.LOAD)
1005  val commitLoadValid = io.commits.commitValid.zip(commitIsLoad).map{ case (v, t) => v && t }
1006  XSPerfAccumulate("commitInstrLoad", ifCommit(PopCount(commitLoadValid)))
1007  val commitIsBranch = io.commits.info.map(_.commitType).map(_ === CommitType.BRANCH)
1008  val commitBranchValid = io.commits.commitValid.zip(commitIsBranch).map{ case (v, t) => v && t }
1009  XSPerfAccumulate("commitInstrBranch", ifCommit(PopCount(commitBranchValid)))
1010  val commitLoadWaitBit = commitDebugUop.map(_.cf.loadWaitBit)
1011  XSPerfAccumulate("commitInstrLoadWait", ifCommit(PopCount(commitLoadValid.zip(commitLoadWaitBit).map{ case (v, w) => v && w })))
1012  val commitIsStore = io.commits.info.map(_.commitType).map(_ === CommitType.STORE)
1013  XSPerfAccumulate("commitInstrStore", ifCommit(PopCount(io.commits.commitValid.zip(commitIsStore).map{ case (v, t) => v && t })))
1014  XSPerfAccumulate("writeback", PopCount((0 until RobSize).map(i => valid(i) && writebacked(i))))
1015  // XSPerfAccumulate("enqInstr", PopCount(io.dp1Req.map(_.fire)))
1016  // XSPerfAccumulate("d2rVnR", PopCount(io.dp1Req.map(p => p.valid && !p.ready)))
1017  XSPerfAccumulate("walkInstr", Mux(io.commits.isWalk, PopCount(io.commits.walkValid), 0.U))
1018  XSPerfAccumulate("walkCycle", state === s_walk)
1019  val deqNotWritebacked = valid(deqPtr.value) && !writebacked(deqPtr.value)
1020  val deqUopCommitType = io.commits.info(0).commitType
1021  XSPerfAccumulate("waitNormalCycle", deqNotWritebacked && deqUopCommitType === CommitType.NORMAL)
1022  XSPerfAccumulate("waitBranchCycle", deqNotWritebacked && deqUopCommitType === CommitType.BRANCH)
1023  XSPerfAccumulate("waitLoadCycle", deqNotWritebacked && deqUopCommitType === CommitType.LOAD)
1024  XSPerfAccumulate("waitStoreCycle", deqNotWritebacked && deqUopCommitType === CommitType.STORE)
1025  XSPerfAccumulate("robHeadPC", io.commits.info(0).pc)
1026  val dispatchLatency = commitDebugUop.map(uop => uop.debugInfo.dispatchTime - uop.debugInfo.renameTime)
1027  val enqRsLatency = commitDebugUop.map(uop => uop.debugInfo.enqRsTime - uop.debugInfo.dispatchTime)
1028  val selectLatency = commitDebugUop.map(uop => uop.debugInfo.selectTime - uop.debugInfo.enqRsTime)
1029  val issueLatency = commitDebugUop.map(uop => uop.debugInfo.issueTime - uop.debugInfo.selectTime)
1030  val executeLatency = commitDebugUop.map(uop => uop.debugInfo.writebackTime - uop.debugInfo.issueTime)
1031  val rsFuLatency = commitDebugUop.map(uop => uop.debugInfo.writebackTime - uop.debugInfo.enqRsTime)
1032  val commitLatency = commitDebugUop.map(uop => timer - uop.debugInfo.writebackTime)
1033  def latencySum(cond: Seq[Bool], latency: Seq[UInt]): UInt = {
1034    cond.zip(latency).map(x => Mux(x._1, x._2, 0.U)).reduce(_ +& _)
1035  }
1036  for (fuType <- FuType.functionNameMap.keys) {
1037    val fuName = FuType.functionNameMap(fuType)
1038    val commitIsFuType = io.commits.commitValid.zip(commitDebugUop).map(x => x._1 && x._2.ctrl.fuType === fuType.U )
1039    XSPerfAccumulate(s"${fuName}_instr_cnt", ifCommit(PopCount(commitIsFuType)))
1040    XSPerfAccumulate(s"${fuName}_latency_dispatch", ifCommit(latencySum(commitIsFuType, dispatchLatency)))
1041    XSPerfAccumulate(s"${fuName}_latency_enq_rs", ifCommit(latencySum(commitIsFuType, enqRsLatency)))
1042    XSPerfAccumulate(s"${fuName}_latency_select", ifCommit(latencySum(commitIsFuType, selectLatency)))
1043    XSPerfAccumulate(s"${fuName}_latency_issue", ifCommit(latencySum(commitIsFuType, issueLatency)))
1044    XSPerfAccumulate(s"${fuName}_latency_execute", ifCommit(latencySum(commitIsFuType, executeLatency)))
1045    XSPerfAccumulate(s"${fuName}_latency_enq_rs_execute", ifCommit(latencySum(commitIsFuType, rsFuLatency)))
1046    XSPerfAccumulate(s"${fuName}_latency_commit", ifCommit(latencySum(commitIsFuType, commitLatency)))
1047    if (fuType == FuType.fmac.litValue) {
1048      val commitIsFma = commitIsFuType.zip(commitDebugUop).map(x => x._1 && x._2.ctrl.fpu.ren3 )
1049      XSPerfAccumulate(s"${fuName}_instr_cnt_fma", ifCommit(PopCount(commitIsFma)))
1050      XSPerfAccumulate(s"${fuName}_latency_enq_rs_execute_fma", ifCommit(latencySum(commitIsFma, rsFuLatency)))
1051      XSPerfAccumulate(s"${fuName}_latency_execute_fma", ifCommit(latencySum(commitIsFma, executeLatency)))
1052    }
1053  }
1054
1055  //difftest signals
1056  val firstValidCommit = (deqPtr + PriorityMux(io.commits.commitValid, VecInit(List.tabulate(CommitWidth)(_.U(log2Up(CommitWidth).W))))).value
1057
1058  val wdata = Wire(Vec(CommitWidth, UInt(XLEN.W)))
1059  val wpc = Wire(Vec(CommitWidth, UInt(XLEN.W)))
1060
1061  for(i <- 0 until CommitWidth) {
1062    val idx = deqPtrVec(i).value
1063    wdata(i) := debug_exuData(idx)
1064    wpc(i) := SignExt(commitDebugUop(i).cf.pc, XLEN)
1065  }
1066
1067  if (env.EnableDifftest) {
1068    for (i <- 0 until CommitWidth) {
1069      val difftest = Module(new DifftestInstrCommit)
1070      // assgin default value
1071      difftest.io := DontCare
1072
1073      difftest.io.clock    := clock
1074      difftest.io.coreid   := io.hartId
1075      difftest.io.index    := i.U
1076
1077      val ptr = deqPtrVec(i).value
1078      val uop = commitDebugUop(i)
1079      val exuOut = debug_exuDebug(ptr)
1080      val exuData = debug_exuData(ptr)
1081      difftest.io.valid    := RegNext(RegNext(RegNext(io.commits.commitValid(i) && io.commits.isCommit)))
1082      difftest.io.pc       := RegNext(RegNext(RegNext(SignExt(uop.cf.pc, XLEN))))
1083      difftest.io.instr    := RegNext(RegNext(RegNext(uop.cf.instr)))
1084      difftest.io.robIdx   := RegNext(RegNext(RegNext(ZeroExt(ptr, 10))))
1085      difftest.io.lqIdx    := RegNext(RegNext(RegNext(ZeroExt(uop.lqIdx.value, 7))))
1086      difftest.io.sqIdx    := RegNext(RegNext(RegNext(ZeroExt(uop.sqIdx.value, 7))))
1087      difftest.io.isLoad   := RegNext(RegNext(RegNext(io.commits.info(i).commitType === CommitType.LOAD)))
1088      difftest.io.isStore  := RegNext(RegNext(RegNext(io.commits.info(i).commitType === CommitType.STORE)))
1089      difftest.io.special  := RegNext(RegNext(RegNext(CommitType.isFused(io.commits.info(i).commitType))))
1090      // when committing an eliminated move instruction,
1091      // we must make sure that skip is properly set to false (output from EXU is random value)
1092      difftest.io.skip     := RegNext(RegNext(RegNext(Mux(uop.eliminatedMove, false.B, exuOut.isMMIO || exuOut.isPerfCnt))))
1093      difftest.io.isRVC    := RegNext(RegNext(RegNext(uop.cf.pd.isRVC)))
1094      difftest.io.rfwen    := RegNext(RegNext(RegNext(io.commits.commitValid(i) && io.commits.info(i).rfWen && io.commits.info(i).ldest =/= 0.U)))
1095      difftest.io.fpwen    := RegNext(RegNext(RegNext(io.commits.commitValid(i) && io.commits.info(i).fpWen)))
1096      difftest.io.wpdest   := RegNext(RegNext(RegNext(io.commits.info(i).pdest)))
1097      difftest.io.wdest    := RegNext(RegNext(RegNext(io.commits.info(i).ldest)))
1098
1099      difftest.io.isVsetFirst := RegNext(RegNext(RegNext(io.commits.commitValid(i) && !io.commits.info(i).uopIdx.orR)))
1100      // // runahead commit hint
1101      // val runahead_commit = Module(new DifftestRunaheadCommitEvent)
1102      // runahead_commit.io.clock := clock
1103      // runahead_commit.io.coreid := io.hartId
1104      // runahead_commit.io.index := i.U
1105      // runahead_commit.io.valid := difftest.io.valid &&
1106      //   (commitBranchValid(i) || commitIsStore(i))
1107      // // TODO: is branch or store
1108      // runahead_commit.io.pc    := difftest.io.pc
1109    }
1110  }
1111  else if (env.AlwaysBasicDiff) {
1112    // These are the structures used by difftest only and should be optimized after synthesis.
1113    val dt_eliminatedMove = Mem(RobSize, Bool())
1114    val dt_isRVC = Mem(RobSize, Bool())
1115    val dt_exuDebug = Reg(Vec(RobSize, new DebugBundle))
1116    for (i <- 0 until RenameWidth) {
1117      when (canEnqueue(i)) {
1118        dt_eliminatedMove(allocatePtrVec(i).value) := io.enq.req(i).bits.eliminatedMove
1119        dt_isRVC(allocatePtrVec(i).value) := io.enq.req(i).bits.cf.pd.isRVC
1120      }
1121    }
1122    for (wb <- exuWriteback) {
1123      when (wb.valid) {
1124        val wbIdx = wb.bits.uop.robIdx.value
1125        dt_exuDebug(wbIdx) := wb.bits.debug
1126      }
1127    }
1128    // Always instantiate basic difftest modules.
1129    for (i <- 0 until CommitWidth) {
1130      val commitInfo = io.commits.info(i)
1131      val ptr = deqPtrVec(i).value
1132      val exuOut = dt_exuDebug(ptr)
1133      val eliminatedMove = dt_eliminatedMove(ptr)
1134      val isRVC = dt_isRVC(ptr)
1135
1136      val difftest = Module(new DifftestBasicInstrCommit)
1137      difftest.io.clock   := clock
1138      difftest.io.coreid  := io.hartId
1139      difftest.io.index   := i.U
1140      difftest.io.valid   := RegNext(RegNext(RegNext(io.commits.commitValid(i) && io.commits.isCommit)))
1141      difftest.io.special := RegNext(RegNext(RegNext(CommitType.isFused(commitInfo.commitType))))
1142      difftest.io.skip    := RegNext(RegNext(RegNext(Mux(eliminatedMove, false.B, exuOut.isMMIO || exuOut.isPerfCnt))))
1143      difftest.io.isRVC   := RegNext(RegNext(RegNext(isRVC)))
1144      difftest.io.rfwen   := RegNext(RegNext(RegNext(io.commits.commitValid(i) && commitInfo.rfWen && commitInfo.ldest =/= 0.U)))
1145      difftest.io.fpwen   := RegNext(RegNext(RegNext(io.commits.commitValid(i) && commitInfo.fpWen)))
1146      difftest.io.wpdest  := RegNext(RegNext(RegNext(commitInfo.pdest)))
1147      difftest.io.wdest   := RegNext(RegNext(RegNext(commitInfo.ldest)))
1148    }
1149  }
1150
1151  if (env.EnableDifftest) {
1152    for (i <- 0 until CommitWidth) {
1153      val difftest = Module(new DifftestLoadEvent)
1154      difftest.io.clock  := clock
1155      difftest.io.coreid := io.hartId
1156      difftest.io.index  := i.U
1157
1158      val ptr = deqPtrVec(i).value
1159      val uop = commitDebugUop(i)
1160      val exuOut = debug_exuDebug(ptr)
1161      difftest.io.valid  := RegNext(RegNext(RegNext(io.commits.commitValid(i) && io.commits.isCommit)))
1162      difftest.io.paddr  := RegNext(RegNext(RegNext(exuOut.paddr)))
1163      difftest.io.opType := RegNext(RegNext(RegNext(uop.ctrl.fuOpType)))
1164      difftest.io.fuType := RegNext(RegNext(RegNext(uop.ctrl.fuType)))
1165    }
1166  }
1167
1168  // Always instantiate basic difftest modules.
1169  if (env.EnableDifftest) {
1170    val dt_isXSTrap = Mem(RobSize, Bool())
1171    for (i <- 0 until RenameWidth) {
1172      when (canEnqueue(i)) {
1173        dt_isXSTrap(allocatePtrVec(i).value) := io.enq.req(i).bits.ctrl.isXSTrap
1174      }
1175    }
1176    val trapVec = io.commits.commitValid.zip(deqPtrVec).map{ case (v, d) => io.commits.isCommit && v && dt_isXSTrap(d.value) }
1177    val hitTrap = trapVec.reduce(_||_)
1178    val trapCode = PriorityMux(wdata.zip(trapVec).map(x => x._2 -> x._1))
1179    val trapPC = SignExt(PriorityMux(wpc.zip(trapVec).map(x => x._2 ->x._1)), XLEN)
1180    val difftest = Module(new DifftestTrapEvent)
1181    difftest.io.clock    := clock
1182    difftest.io.coreid   := io.hartId
1183    difftest.io.valid    := hitTrap
1184    difftest.io.code     := trapCode
1185    difftest.io.pc       := trapPC
1186    difftest.io.cycleCnt := timer
1187    difftest.io.instrCnt := instrCnt
1188    difftest.io.hasWFI   := hasWFI
1189  }
1190  else if (env.AlwaysBasicDiff) {
1191    val dt_isXSTrap = Mem(RobSize, Bool())
1192    for (i <- 0 until RenameWidth) {
1193      when (canEnqueue(i)) {
1194        dt_isXSTrap(allocatePtrVec(i).value) := io.enq.req(i).bits.ctrl.isXSTrap
1195      }
1196    }
1197    val trapVec = io.commits.commitValid.zip(deqPtrVec).map{ case (v, d) => io.commits.isCommit && v && dt_isXSTrap(d.value) }
1198    val hitTrap = trapVec.reduce(_||_)
1199    val difftest = Module(new DifftestBasicTrapEvent)
1200    difftest.io.clock    := clock
1201    difftest.io.coreid   := io.hartId
1202    difftest.io.valid    := hitTrap
1203    difftest.io.cycleCnt := timer
1204    difftest.io.instrCnt := instrCnt
1205  }
1206
1207  val validEntriesBanks = (0 until (RobSize + 63) / 64).map(i => RegNext(PopCount(valid.drop(i * 64).take(64))))
1208  val validEntries = RegNext(ParallelOperation(validEntriesBanks, (a: UInt, b: UInt) => a +& b))
1209  val commitMoveVec = VecInit(io.commits.commitValid.zip(commitIsMove).map{ case (v, m) => v && m })
1210  val commitLoadVec = VecInit(commitLoadValid)
1211  val commitBranchVec = VecInit(commitBranchValid)
1212  val commitLoadWaitVec = VecInit(commitLoadValid.zip(commitLoadWaitBit).map{ case (v, w) => v && w })
1213  val commitStoreVec = VecInit(io.commits.commitValid.zip(commitIsStore).map{ case (v, t) => v && t })
1214  val perfEvents = Seq(
1215    ("rob_interrupt_num      ", io.flushOut.valid && intrEnable                                       ),
1216    ("rob_exception_num      ", io.flushOut.valid && exceptionEnable                                  ),
1217    ("rob_flush_pipe_num     ", io.flushOut.valid && isFlushPipe                                      ),
1218    ("rob_replay_inst_num    ", io.flushOut.valid && isFlushPipe && deqHasReplayInst                  ),
1219    ("rob_commitUop          ", ifCommit(commitCnt)                                                   ),
1220    ("rob_commitInstr        ", ifCommitReg(trueCommitCnt)                                            ),
1221    ("rob_commitInstrMove    ", ifCommitReg(PopCount(RegNext(commitMoveVec)))                         ),
1222    ("rob_commitInstrFused   ", ifCommitReg(fuseCommitCnt)                                            ),
1223    ("rob_commitInstrLoad    ", ifCommitReg(PopCount(RegNext(commitLoadVec)))                         ),
1224    ("rob_commitInstrBranch  ", ifCommitReg(PopCount(RegNext(commitBranchVec)))                       ),
1225    ("rob_commitInstrLoadWait", ifCommitReg(PopCount(RegNext(commitLoadWaitVec)))                     ),
1226    ("rob_commitInstrStore   ", ifCommitReg(PopCount(RegNext(commitStoreVec)))                        ),
1227    ("rob_walkInstr          ", Mux(io.commits.isWalk, PopCount(io.commits.walkValid), 0.U)           ),
1228    ("rob_walkCycle          ", (state === s_walk)                                                    ),
1229    ("rob_1_4_valid          ", validEntries <= (RobSize / 4).U                                       ),
1230    ("rob_2_4_valid          ", validEntries >  (RobSize / 4).U && validEntries <= (RobSize / 2).U    ),
1231    ("rob_3_4_valid          ", validEntries >  (RobSize / 2).U && validEntries <= (RobSize * 3 / 4).U),
1232    ("rob_4_4_valid          ", validEntries >  (RobSize * 3 / 4).U                                   ),
1233  )
1234  generatePerfEvent()
1235}
1236