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