xref: /XiangShan/src/main/scala/xiangshan/backend/CtrlBlock.scala (revision 14a67055130242df761c9ace8347e012d57b32a7)
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
18
19import chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.util._
22import freechips.rocketchip.diplomacy.{LazyModule, LazyModuleImp}
23import utils._
24import utility._
25import xiangshan._
26import xiangshan.backend.decode.{DecodeStage, FusionDecoder, ImmUnion}
27import xiangshan.backend.dispatch.{Dispatch, Dispatch2Rs, DispatchQueue}
28import xiangshan.backend.fu.PFEvent
29import xiangshan.backend.rename.{Rename, RenameTableWrapper}
30import xiangshan.backend.rob.{DebugLSIO, LsTopdownInfo, Rob, RobCSRIO, RobLsqIO, RobPtr}
31import xiangshan.frontend.{FtqPtr, FtqRead, Ftq_RF_Components}
32import xiangshan.mem.mdp.{LFST, SSIT, WaitTable}
33import xiangshan.ExceptionNO._
34import xiangshan.backend.exu.ExuConfig
35import xiangshan.mem.{LsqEnqCtrl, LsqEnqIO}
36
37class CtrlToFtqIO(implicit p: Parameters) extends XSBundle {
38  def numRedirect = exuParameters.JmpCnt + exuParameters.AluCnt
39  val rob_commits = Vec(CommitWidth, Valid(new RobCommitInfo))
40  val redirect = Valid(new Redirect)
41}
42
43class RedirectGenerator(implicit p: Parameters) extends XSModule
44  with HasCircularQueuePtrHelper {
45
46  class RedirectGeneratorIO(implicit p: Parameters) extends XSBundle {
47    def numRedirect = exuParameters.JmpCnt + exuParameters.AluCnt
48    val hartId = Input(UInt(8.W))
49    val exuMispredict = Vec(numRedirect, Flipped(ValidIO(new ExuOutput)))
50    val loadReplay = Flipped(ValidIO(new Redirect))
51    val flush = Input(Bool())
52    val redirectPcRead = new FtqRead(UInt(VAddrBits.W))
53    val stage2Redirect = ValidIO(new Redirect)
54    val stage3Redirect = ValidIO(new Redirect)
55    val memPredUpdate = Output(new MemPredUpdateReq)
56    val memPredPcRead = new FtqRead(UInt(VAddrBits.W)) // read req send form stage 2
57    val isMisspreRedirect = Output(Bool())
58  }
59  val io = IO(new RedirectGeneratorIO)
60  /*
61        LoadQueue  Jump  ALU0  ALU1  ALU2  ALU3   exception    Stage1
62          |         |      |    |     |     |         |
63          |============= reg & compare =====|         |       ========
64                            |                         |
65                            |                         |
66                            |                         |        Stage2
67                            |                         |
68                    redirect (flush backend)          |
69                    |                                 |
70               === reg ===                            |       ========
71                    |                                 |
72                    |----- mux (exception first) -----|        Stage3
73                            |
74                redirect (send to frontend)
75   */
76  def selectOldestRedirect(xs: Seq[Valid[Redirect]]): Vec[Bool] = {
77    val compareVec = (0 until xs.length).map(i => (0 until i).map(j => isAfter(xs(j).bits.robIdx, xs(i).bits.robIdx)))
78    val resultOnehot = VecInit((0 until xs.length).map(i => Cat((0 until xs.length).map(j =>
79      (if (j < i) !xs(j).valid || compareVec(i)(j)
80      else if (j == i) xs(i).valid
81      else !xs(j).valid || !compareVec(j)(i))
82    )).andR))
83    resultOnehot
84  }
85
86  def getRedirect(exuOut: Valid[ExuOutput]): ValidIO[Redirect] = {
87    val redirect = Wire(Valid(new Redirect))
88    redirect.valid := exuOut.valid && exuOut.bits.redirect.cfiUpdate.isMisPred
89    redirect.bits := exuOut.bits.redirect
90    redirect.bits.debugIsCtrl := true.B
91    redirect.bits.debugIsMemVio := false.B
92    redirect
93  }
94
95  val jumpOut = io.exuMispredict.head
96  val allRedirect = VecInit(io.exuMispredict.map(x => getRedirect(x)) :+ io.loadReplay)
97  val oldestOneHot = selectOldestRedirect(allRedirect)
98  val needFlushVec = VecInit(allRedirect.map(_.bits.robIdx.needFlush(io.stage2Redirect) || io.flush))
99  val oldestValid = VecInit(oldestOneHot.zip(needFlushVec).map{ case (v, f) => v && !f }).asUInt.orR
100  val oldestExuOutput = Mux1H(io.exuMispredict.indices.map(oldestOneHot), io.exuMispredict)
101  val oldestRedirect = Mux1H(oldestOneHot, allRedirect)
102  io.isMisspreRedirect := VecInit(io.exuMispredict.map(x => getRedirect(x).valid)).asUInt.orR
103  io.redirectPcRead.ptr := oldestRedirect.bits.ftqIdx
104  io.redirectPcRead.offset := oldestRedirect.bits.ftqOffset
105
106  val s1_jumpTarget = RegEnable(jumpOut.bits.redirect.cfiUpdate.target, jumpOut.valid)
107  val s1_imm12_reg = RegNext(oldestExuOutput.bits.uop.ctrl.imm(11, 0))
108  val s1_pd = RegNext(oldestExuOutput.bits.uop.cf.pd)
109  val s1_redirect_bits_reg = RegNext(oldestRedirect.bits)
110  val s1_redirect_valid_reg = RegNext(oldestValid)
111  val s1_redirect_onehot = RegNext(oldestOneHot)
112
113  // stage1 -> stage2
114  io.stage2Redirect.valid := s1_redirect_valid_reg && !io.flush
115  io.stage2Redirect.bits := s1_redirect_bits_reg
116
117  val s1_isReplay = s1_redirect_onehot.last
118  val s1_isJump = s1_redirect_onehot.head
119  val real_pc = io.redirectPcRead.data
120  val brTarget = real_pc + SignExt(ImmUnion.B.toImm32(s1_imm12_reg), XLEN)
121  val snpc = real_pc + Mux(s1_pd.isRVC, 2.U, 4.U)
122  val target = Mux(s1_isReplay,
123    real_pc, // replay from itself
124    Mux(s1_redirect_bits_reg.cfiUpdate.taken,
125      Mux(s1_isJump, s1_jumpTarget, brTarget),
126      snpc
127    )
128  )
129
130  val stage2CfiUpdate = io.stage2Redirect.bits.cfiUpdate
131  stage2CfiUpdate.pc := real_pc
132  stage2CfiUpdate.pd := s1_pd
133  // stage2CfiUpdate.predTaken := s1_redirect_bits_reg.cfiUpdate.predTaken
134  stage2CfiUpdate.target := target
135  // stage2CfiUpdate.taken := s1_redirect_bits_reg.cfiUpdate.taken
136  // stage2CfiUpdate.isMisPred := s1_redirect_bits_reg.cfiUpdate.isMisPred
137
138  val s2_target = RegEnable(target, s1_redirect_valid_reg)
139  val s2_pc = RegEnable(real_pc, s1_redirect_valid_reg)
140  val s2_redirect_bits_reg = RegEnable(s1_redirect_bits_reg, s1_redirect_valid_reg)
141  val s2_redirect_valid_reg = RegNext(s1_redirect_valid_reg && !io.flush, init = false.B)
142
143  io.stage3Redirect.valid := s2_redirect_valid_reg
144  io.stage3Redirect.bits := s2_redirect_bits_reg
145
146  // get pc from ftq
147  // valid only if redirect is caused by load violation
148  // store_pc is used to update store set
149  val store_pc = io.memPredPcRead(s1_redirect_bits_reg.stFtqIdx, s1_redirect_bits_reg.stFtqOffset)
150
151  // update load violation predictor if load violation redirect triggered
152  io.memPredUpdate.valid := RegNext(s1_isReplay && s1_redirect_valid_reg, init = false.B)
153  // update wait table
154  io.memPredUpdate.waddr := RegNext(XORFold(real_pc(VAddrBits-1, 1), MemPredPCWidth))
155  io.memPredUpdate.wdata := true.B
156  // update store set
157  io.memPredUpdate.ldpc := RegNext(XORFold(real_pc(VAddrBits-1, 1), MemPredPCWidth))
158  // store pc is ready 1 cycle after s1_isReplay is judged
159  io.memPredUpdate.stpc := XORFold(store_pc(VAddrBits-1, 1), MemPredPCWidth)
160
161  // // recover runahead checkpoint if redirect
162  // if (!env.FPGAPlatform) {
163  //   val runahead_redirect = Module(new DifftestRunaheadRedirectEvent)
164  //   runahead_redirect.io.clock := clock
165  //   runahead_redirect.io.coreid := io.hartId
166  //   runahead_redirect.io.valid := io.stage3Redirect.valid
167  //   runahead_redirect.io.pc :=  s2_pc // for debug only
168  //   runahead_redirect.io.target_pc := s2_target // for debug only
169  //   runahead_redirect.io.checkpoint_id := io.stage3Redirect.bits.debug_runahead_checkpoint_id // make sure it is right
170  // }
171}
172
173class CtrlBlock(dpExuConfigs: Seq[Seq[Seq[ExuConfig]]])(implicit p: Parameters) extends LazyModule
174  with HasWritebackSink with HasWritebackSource {
175  val rob = LazyModule(new Rob)
176
177  override def addWritebackSink(source: Seq[HasWritebackSource], index: Option[Seq[Int]]): HasWritebackSink = {
178    rob.addWritebackSink(Seq(this), Some(Seq(writebackSinks.length)))
179    super.addWritebackSink(source, index)
180  }
181
182  // duplicated dispatch2 here to avoid cross-module timing path loop.
183  val dispatch2 = dpExuConfigs.map(c => LazyModule(new Dispatch2Rs(c)))
184  lazy val module = new CtrlBlockImp(this)
185
186  override lazy val writebackSourceParams: Seq[WritebackSourceParams] = {
187    writebackSinksParams
188  }
189  override lazy val writebackSourceImp: HasWritebackSourceImp = module
190
191  override def generateWritebackIO(
192    thisMod: Option[HasWritebackSource] = None,
193    thisModImp: Option[HasWritebackSourceImp] = None
194  ): Unit = {
195    module.io.writeback.zip(writebackSinksImp(thisMod, thisModImp)).foreach(x => x._1 := x._2)
196  }
197}
198
199class CtrlBlockImp(outer: CtrlBlock)(implicit p: Parameters) extends LazyModuleImp(outer)
200  with HasXSParameter
201  with HasCircularQueuePtrHelper
202  with HasWritebackSourceImp
203  with HasPerfEvents
204{
205  val writebackLengths = outer.writebackSinksParams.map(_.length)
206
207  val io = IO(new Bundle {
208    val hartId = Input(UInt(8.W))
209    val cpu_halt = Output(Bool())
210    val frontend = Flipped(new FrontendToCtrlIO)
211    // to exu blocks
212    val allocPregs = Vec(RenameWidth, Output(new ResetPregStateReq))
213    val dispatch = Vec(3*dpParams.IntDqDeqWidth, DecoupledIO(new MicroOp))
214    val rsReady = Vec(outer.dispatch2.map(_.module.io.out.length).sum, Input(Bool()))
215    val enqLsq = Flipped(new LsqEnqIO)
216    val lqCancelCnt = Input(UInt(log2Up(VirtualLoadQueueSize + 1).W))
217    val sqCancelCnt = Input(UInt(log2Up(StoreQueueSize + 1).W))
218    val lqDeq = Input(UInt(log2Up(CommitWidth + 1).W))
219    val sqDeq = Input(UInt(log2Ceil(EnsbufferWidth + 1).W))
220    val sqCanAccept = Input(Bool())
221    val lqCanAccept = Input(Bool())
222    val ld_pc_read = Vec(exuParameters.LduCnt, Flipped(new FtqRead(UInt(VAddrBits.W))))
223    // from int block
224    val exuRedirect = Vec(exuParameters.AluCnt + exuParameters.JmpCnt, Flipped(ValidIO(new ExuOutput)))
225    val stIn = Vec(exuParameters.StuCnt, Flipped(ValidIO(new ExuInput)))
226    val memoryViolation = Flipped(ValidIO(new Redirect))
227    val jumpPc = Output(UInt(VAddrBits.W))
228    val jalr_target = Output(UInt(VAddrBits.W))
229    val robio = new Bundle {
230      // to int block
231      val toCSR = new RobCSRIO
232      val exception = ValidIO(new ExceptionInfo)
233      // to mem block
234      val lsq = new RobLsqIO
235      // debug
236      val debug_ls = Flipped(new DebugLSIO)
237      val lsTopdownInfo = Vec(exuParameters.LduCnt, Input(new LsTopdownInfo))
238    }
239    val csrCtrl = Input(new CustomCSRCtrlIO)
240    val perfInfo = Output(new Bundle{
241      val ctrlInfo = new Bundle {
242        val robFull   = Input(Bool())
243        val intdqFull = Input(Bool())
244        val fpdqFull  = Input(Bool())
245        val lsdqFull  = Input(Bool())
246      }
247    })
248    val writeback = MixedVec(writebackLengths.map(num => Vec(num, Flipped(ValidIO(new ExuOutput)))))
249    // redirect out
250    val redirect = ValidIO(new Redirect)
251    // debug
252    val debug_int_rat = Vec(32, Output(UInt(PhyRegIdxWidth.W)))
253    val debug_fp_rat = Vec(32, Output(UInt(PhyRegIdxWidth.W)))
254    val robDeqPtr = Output(new RobPtr)
255    val robHeadLsIssue = Input(Bool())
256  })
257
258  override def writebackSource: Option[Seq[Seq[Valid[ExuOutput]]]] = {
259    Some(io.writeback.map(writeback => {
260      val exuOutput = WireInit(writeback)
261      val timer = GTimer()
262      for ((wb_next, wb) <- exuOutput.zip(writeback)) {
263        wb_next.valid := RegNext(wb.valid && !wb.bits.uop.robIdx.needFlush(Seq(stage2Redirect, redirectForExu)))
264        wb_next.bits := RegNext(wb.bits)
265        wb_next.bits.uop.debugInfo.writebackTime := timer
266      }
267      exuOutput
268    }))
269  }
270
271  val decode = Module(new DecodeStage)
272  val fusionDecoder = Module(new FusionDecoder)
273  val rat = Module(new RenameTableWrapper)
274  val ssit = Module(new SSIT)
275  val waittable = Module(new WaitTable)
276  val rename = Module(new Rename)
277  val dispatch = Module(new Dispatch)
278  val intDq = Module(new DispatchQueue(dpParams.IntDqSize, RenameWidth, dpParams.IntDqDeqWidth))
279  val fpDq = Module(new DispatchQueue(dpParams.FpDqSize, RenameWidth, dpParams.FpDqDeqWidth))
280  val lsDq = Module(new DispatchQueue(dpParams.LsDqSize, RenameWidth, dpParams.LsDqDeqWidth))
281  val redirectGen = Module(new RedirectGenerator)
282  val rob = outer.rob.module
283
284  // jumpPc (2) + redirects (1) + loadPredUpdate (1) + jalr_target (1) + [ld pc (LduCnt)] + robWriteback (sum(writebackLengths)) + robFlush (1)
285  val PCMEMIDX_LD = 5
286  val pcMem = Module(new SyncDataModuleTemplate(
287    new Ftq_RF_Components, FtqSize,
288    6 + exuParameters.LduCnt, 1, "CtrlPcMem")
289  )
290  pcMem.io.wen.head   := RegNext(io.frontend.fromFtq.pc_mem_wen)
291  pcMem.io.waddr.head := RegNext(io.frontend.fromFtq.pc_mem_waddr)
292  pcMem.io.wdata.head := RegNext(io.frontend.fromFtq.pc_mem_wdata)
293
294  pcMem.io.raddr.last := rob.io.flushOut.bits.ftqIdx.value
295  val flushPC = pcMem.io.rdata.last.getPc(RegNext(rob.io.flushOut.bits.ftqOffset))
296
297  val flushRedirect = Wire(Valid(new Redirect))
298  flushRedirect.valid := RegNext(rob.io.flushOut.valid)
299  flushRedirect.bits := RegEnable(rob.io.flushOut.bits, rob.io.flushOut.valid)
300  flushRedirect.bits.debugIsCtrl := false.B
301  flushRedirect.bits.debugIsMemVio := false.B
302
303  val flushRedirectReg = Wire(Valid(new Redirect))
304  flushRedirectReg.valid := RegNext(flushRedirect.valid, init = false.B)
305  flushRedirectReg.bits := RegEnable(flushRedirect.bits, flushRedirect.valid)
306
307  val stage2Redirect = Mux(flushRedirect.valid, flushRedirect, redirectGen.io.stage2Redirect)
308  // Redirect will be RegNext at ExuBlocks.
309  val redirectForExu = RegNextWithEnable(stage2Redirect)
310
311  val exuRedirect = io.exuRedirect.map(x => {
312    val valid = x.valid && x.bits.redirectValid
313    val killedByOlder = x.bits.uop.robIdx.needFlush(Seq(stage2Redirect, redirectForExu))
314    val delayed = Wire(Valid(new ExuOutput))
315    delayed.valid := RegNext(valid && !killedByOlder, init = false.B)
316    delayed.bits := RegEnable(x.bits, x.valid)
317    delayed
318  })
319  val loadReplay = Wire(Valid(new Redirect))
320  loadReplay.valid := RegNext(io.memoryViolation.valid &&
321    !io.memoryViolation.bits.robIdx.needFlush(Seq(stage2Redirect, redirectForExu)),
322    init = false.B
323  )
324  val memVioBits = WireDefault(io.memoryViolation.bits)
325  memVioBits.debugIsCtrl := false.B
326  memVioBits.debugIsMemVio := true.B
327  loadReplay.bits := RegEnable(memVioBits, io.memoryViolation.valid)
328  pcMem.io.raddr(2) := redirectGen.io.redirectPcRead.ptr.value
329  redirectGen.io.redirectPcRead.data := pcMem.io.rdata(2).getPc(RegNext(redirectGen.io.redirectPcRead.offset))
330  pcMem.io.raddr(3) := redirectGen.io.memPredPcRead.ptr.value
331  redirectGen.io.memPredPcRead.data := pcMem.io.rdata(3).getPc(RegNext(redirectGen.io.memPredPcRead.offset))
332  redirectGen.io.hartId := io.hartId
333  redirectGen.io.exuMispredict <> exuRedirect
334  redirectGen.io.loadReplay <> loadReplay
335  redirectGen.io.flush := flushRedirect.valid
336
337  val frontendFlushValid = DelayN(flushRedirect.valid, 5)
338  val frontendFlushBits = RegEnable(flushRedirect.bits, flushRedirect.valid)
339  // When ROB commits an instruction with a flush, we notify the frontend of the flush without the commit.
340  // Flushes to frontend may be delayed by some cycles and commit before flush causes errors.
341  // Thus, we make all flush reasons to behave the same as exceptions for frontend.
342  for (i <- 0 until CommitWidth) {
343    // why flushOut: instructions with flushPipe are not commited to frontend
344    // If we commit them to frontend, it will cause flush after commit, which is not acceptable by frontend.
345    val is_commit = rob.io.commits.commitValid(i) && rob.io.commits.isCommit && !rob.io.flushOut.valid
346    io.frontend.toFtq.rob_commits(i).valid := RegNext(is_commit)
347    io.frontend.toFtq.rob_commits(i).bits := RegEnable(rob.io.commits.info(i), is_commit)
348  }
349  io.frontend.toFtq.redirect.valid := frontendFlushValid || redirectGen.io.stage2Redirect.valid
350  io.frontend.toFtq.redirect.bits := Mux(frontendFlushValid, frontendFlushBits, redirectGen.io.stage2Redirect.bits)
351  // Be careful here:
352  // T0: flushRedirect.valid, exception.valid
353  // T1: csr.redirect.valid
354  // T2: csr.exception.valid
355  // T3: csr.trapTarget
356  // T4: ctrlBlock.trapTarget
357  // T5: io.frontend.toFtq.stage2Redirect.valid
358  val pc_from_csr = io.robio.toCSR.isXRet || DelayN(rob.io.exception.valid, 4)
359  val rob_flush_pc = RegEnable(Mux(flushRedirect.bits.flushItself(),
360    flushPC, // replay inst
361    flushPC + Mux(flushRedirect.bits.isRVC, 2.U, 4.U) // flush pipe
362  ), flushRedirect.valid)
363  val flushTarget = Mux(pc_from_csr, io.robio.toCSR.trapTarget, rob_flush_pc)
364  when (frontendFlushValid) {
365    io.frontend.toFtq.redirect.bits.level := RedirectLevel.flush
366    io.frontend.toFtq.redirect.bits.cfiUpdate.target := RegNext(flushTarget)
367  }
368
369
370  val pendingRedirect = RegInit(false.B)
371  when (stage2Redirect.valid) {
372    pendingRedirect := true.B
373  }.elsewhen (RegNext(io.frontend.toFtq.redirect.valid)) {
374    pendingRedirect := false.B
375  }
376
377  decode.io.in <> io.frontend.cfVec
378  decode.io.stallReason.in <> io.frontend.stallReason
379  decode.io.csrCtrl := RegNext(io.csrCtrl)
380  decode.io.intRat <> rat.io.intReadPorts
381  decode.io.fpRat <> rat.io.fpReadPorts
382
383  // memory dependency predict
384  // when decode, send fold pc to mdp
385  for (i <- 0 until DecodeWidth) {
386    val mdp_foldpc = Mux(
387      decode.io.out(i).fire,
388      decode.io.in(i).bits.foldpc,
389      rename.io.in(i).bits.cf.foldpc
390    )
391    ssit.io.raddr(i) := mdp_foldpc
392    waittable.io.raddr(i) := mdp_foldpc
393  }
394  // currently, we only update mdp info when isReplay
395  ssit.io.update <> RegNext(redirectGen.io.memPredUpdate)
396  ssit.io.csrCtrl := RegNext(io.csrCtrl)
397  waittable.io.update <> RegNext(redirectGen.io.memPredUpdate)
398  waittable.io.csrCtrl := RegNext(io.csrCtrl)
399
400  // LFST lookup and update
401  dispatch.io.lfst := DontCare
402  if (LFSTEnable) {
403    val lfst = Module(new LFST)
404    lfst.io.redirect <> RegNext(io.redirect)
405    lfst.io.storeIssue <> RegNext(io.stIn)
406    lfst.io.csrCtrl <> RegNext(io.csrCtrl)
407    lfst.io.dispatch <> dispatch.io.lfst
408  }
409
410
411  rat.io.redirect := stage2Redirect.valid
412  rat.io.robCommits := rob.io.commits
413  rat.io.intRenamePorts := rename.io.intRenamePorts
414  rat.io.fpRenamePorts := rename.io.fpRenamePorts
415  rat.io.debug_int_rat <> io.debug_int_rat
416  rat.io.debug_fp_rat <> io.debug_fp_rat
417
418  // pipeline between decode and rename
419  for (i <- 0 until RenameWidth) {
420    // fusion decoder
421    val decodeHasException = io.frontend.cfVec(i).bits.exceptionVec(instrPageFault) || io.frontend.cfVec(i).bits.exceptionVec(instrAccessFault)
422    val disableFusion = decode.io.csrCtrl.singlestep || !decode.io.csrCtrl.fusion_enable
423    fusionDecoder.io.in(i).valid := io.frontend.cfVec(i).valid && !(decodeHasException || disableFusion)
424    fusionDecoder.io.in(i).bits := io.frontend.cfVec(i).bits.instr
425    if (i > 0) {
426      fusionDecoder.io.inReady(i - 1) := decode.io.out(i).ready
427    }
428
429    // Pipeline
430    val renamePipe = PipelineNext(decode.io.out(i), rename.io.in(i).ready,
431      stage2Redirect.valid || pendingRedirect)
432    renamePipe.ready := rename.io.in(i).ready
433    rename.io.in(i).valid := renamePipe.valid && !fusionDecoder.io.clear(i)
434    rename.io.in(i).bits := renamePipe.bits
435    rename.io.intReadPorts(i) := rat.io.intReadPorts(i).map(_.data)
436    rename.io.fpReadPorts(i) := rat.io.fpReadPorts(i).map(_.data)
437    rename.io.waittable(i) := RegEnable(waittable.io.rdata(i), decode.io.out(i).fire)
438
439    if (i < RenameWidth - 1) {
440      // fusion decoder sees the raw decode info
441      fusionDecoder.io.dec(i) := renamePipe.bits.ctrl
442      rename.io.fusionInfo(i) := fusionDecoder.io.info(i)
443
444      // update the first RenameWidth - 1 instructions
445      decode.io.fusion(i) := fusionDecoder.io.out(i).valid && rename.io.out(i).fire
446      when (fusionDecoder.io.out(i).valid) {
447        fusionDecoder.io.out(i).bits.update(rename.io.in(i).bits.ctrl)
448        // TODO: remove this dirty code for ftq update
449        val sameFtqPtr = rename.io.in(i).bits.cf.ftqPtr.value === rename.io.in(i + 1).bits.cf.ftqPtr.value
450        val ftqOffset0 = rename.io.in(i).bits.cf.ftqOffset
451        val ftqOffset1 = rename.io.in(i + 1).bits.cf.ftqOffset
452        val ftqOffsetDiff = ftqOffset1 - ftqOffset0
453        val cond1 = sameFtqPtr && ftqOffsetDiff === 1.U
454        val cond2 = sameFtqPtr && ftqOffsetDiff === 2.U
455        val cond3 = !sameFtqPtr && ftqOffset1 === 0.U
456        val cond4 = !sameFtqPtr && ftqOffset1 === 1.U
457        rename.io.in(i).bits.ctrl.commitType := Mux(cond1, 4.U, Mux(cond2, 5.U, Mux(cond3, 6.U, 7.U)))
458        XSError(!cond1 && !cond2 && !cond3 && !cond4, p"new condition $sameFtqPtr $ftqOffset0 $ftqOffset1\n")
459      }
460    }
461  }
462
463  rename.io.redirect := stage2Redirect
464  rename.io.robCommits <> rob.io.commits
465  rename.io.ssit <> ssit.io.rdata
466  rename.io.int_need_free := rat.io.int_need_free
467  rename.io.int_old_pdest := rat.io.int_old_pdest
468  rename.io.fp_old_pdest := rat.io.fp_old_pdest
469  rename.io.debug_int_rat <> rat.io.debug_int_rat
470  rename.io.debug_fp_rat <> rat.io.debug_fp_rat
471  rename.io.stallReason.in <> decode.io.stallReason.out
472
473  // pipeline between rename and dispatch
474  for (i <- 0 until RenameWidth) {
475    PipelineConnect(rename.io.out(i), dispatch.io.fromRename(i), dispatch.io.recv(i), stage2Redirect.valid)
476  }
477
478  dispatch.io.hartId := io.hartId
479  dispatch.io.redirect := stage2Redirect
480  dispatch.io.enqRob <> rob.io.enq
481  dispatch.io.toIntDq <> intDq.io.enq
482  dispatch.io.toFpDq <> fpDq.io.enq
483  dispatch.io.toLsDq <> lsDq.io.enq
484  dispatch.io.allocPregs <> io.allocPregs
485  dispatch.io.robHead := rob.io.debugRobHead
486  dispatch.io.stallReason <> rename.io.stallReason.out
487  dispatch.io.lqCanAccept := io.lqCanAccept
488  dispatch.io.sqCanAccept := io.sqCanAccept
489  dispatch.io.robHeadNotReady := rob.io.headNotReady
490  dispatch.io.robFull := rob.io.robFull
491  dispatch.io.singleStep := RegNext(io.csrCtrl.singlestep)
492
493  intDq.io.redirect <> redirectForExu
494  fpDq.io.redirect <> redirectForExu
495  lsDq.io.redirect <> redirectForExu
496
497  val dpqOut = intDq.io.deq ++ lsDq.io.deq ++ fpDq.io.deq
498  io.dispatch <> dpqOut
499
500  for (dp2 <- outer.dispatch2.map(_.module.io)) {
501    dp2.redirect := redirectForExu
502    if (dp2.readFpState.isDefined) {
503      dp2.readFpState.get := DontCare
504    }
505    if (dp2.readIntState.isDefined) {
506      dp2.readIntState.get := DontCare
507    }
508    if (dp2.enqLsq.isDefined) {
509      val lsqCtrl = Module(new LsqEnqCtrl)
510      lsqCtrl.io.redirect <> redirectForExu
511      lsqCtrl.io.enq <> dp2.enqLsq.get
512      lsqCtrl.io.lcommit := io.lqDeq
513      lsqCtrl.io.scommit := io.sqDeq
514      lsqCtrl.io.lqCancelCnt := io.lqCancelCnt
515      lsqCtrl.io.sqCancelCnt := io.sqCancelCnt
516      io.enqLsq <> lsqCtrl.io.enqLsq
517      rob.io.debugEnqLsq := io.enqLsq
518    }
519  }
520  for ((dp2In, i) <- outer.dispatch2.flatMap(_.module.io.in).zipWithIndex) {
521    dp2In.valid := dpqOut(i).valid
522    dp2In.bits := dpqOut(i).bits
523    // override ready here to avoid cross-module loop path
524    dpqOut(i).ready := dp2In.ready
525  }
526  for ((dp2Out, i) <- outer.dispatch2.flatMap(_.module.io.out).zipWithIndex) {
527    dp2Out.ready := io.rsReady(i)
528  }
529
530  val pingpong = RegInit(false.B)
531  pingpong := !pingpong
532  pcMem.io.raddr(0) := intDq.io.deqNext(0).cf.ftqPtr.value
533  pcMem.io.raddr(1) := intDq.io.deqNext(2).cf.ftqPtr.value
534  val jumpPcRead0 = pcMem.io.rdata(0).getPc(RegNext(intDq.io.deqNext(0).cf.ftqOffset))
535  val jumpPcRead1 = pcMem.io.rdata(1).getPc(RegNext(intDq.io.deqNext(2).cf.ftqOffset))
536  io.jumpPc := Mux(pingpong && (exuParameters.AluCnt > 2).B, jumpPcRead1, jumpPcRead0)
537  val jalrTargetReadPtr = Mux(pingpong && (exuParameters.AluCnt > 2).B,
538    io.dispatch(2).bits.cf.ftqPtr,
539    io.dispatch(0).bits.cf.ftqPtr)
540  pcMem.io.raddr(4) := (jalrTargetReadPtr + 1.U).value
541  val jalrTargetRead = pcMem.io.rdata(4).startAddr
542  val read_from_newest_entry = RegNext(jalrTargetReadPtr) === RegNext(io.frontend.fromFtq.newest_entry_ptr)
543  io.jalr_target := Mux(read_from_newest_entry, RegNext(io.frontend.fromFtq.newest_entry_target), jalrTargetRead)
544  for(i <- 0 until exuParameters.LduCnt){
545    // load s0 -> get rdata (s1) -> reg next (s2) -> output (s2)
546    pcMem.io.raddr(i + PCMEMIDX_LD) := io.ld_pc_read(i).ptr.value
547    io.ld_pc_read(i).data := pcMem.io.rdata(i + 5).getPc(RegNext(io.ld_pc_read(i).offset))
548  }
549
550  rob.io.hartId := io.hartId
551  io.cpu_halt := DelayN(rob.io.cpu_halt, 5)
552  rob.io.redirect := stage2Redirect
553  outer.rob.generateWritebackIO(Some(outer), Some(this))
554
555  io.redirect := stage2Redirect
556
557  // rob to int block
558  io.robio.toCSR <> rob.io.csr
559  // When wfi is disabled, it will not block ROB commit.
560  rob.io.csr.wfiEvent := io.robio.toCSR.wfiEvent
561  rob.io.wfi_enable := decode.io.csrCtrl.wfi_enable
562  io.robio.toCSR.perfinfo.retiredInstr <> RegNext(rob.io.csr.perfinfo.retiredInstr)
563  io.robio.exception := rob.io.exception
564  io.robio.exception.bits.uop.cf.pc := flushPC
565
566  // rob to mem block
567  io.robio.lsq <> rob.io.lsq
568
569  rob.io.debug_ls := io.robio.debug_ls
570  rob.io.debugHeadLsIssue := io.robHeadLsIssue
571  rob.io.lsTopdownInfo := io.robio.lsTopdownInfo
572  io.robDeqPtr := rob.io.robDeqPtr
573
574  io.perfInfo.ctrlInfo.robFull := RegNext(rob.io.robFull)
575  io.perfInfo.ctrlInfo.intdqFull := RegNext(intDq.io.dqFull)
576  io.perfInfo.ctrlInfo.fpdqFull := RegNext(fpDq.io.dqFull)
577  io.perfInfo.ctrlInfo.lsdqFull := RegNext(lsDq.io.dqFull)
578
579  val pfevent = Module(new PFEvent)
580  pfevent.io.distribute_csr := RegNext(io.csrCtrl.distribute_csr)
581  val csrevents = pfevent.io.hpmevent.slice(8,16)
582
583  val perfinfo = IO(new Bundle(){
584    val perfEventsRs      = Input(Vec(NumRs, new PerfEvent))
585    val perfEventsEu0     = Input(Vec(6, new PerfEvent))
586    val perfEventsEu1     = Input(Vec(6, new PerfEvent))
587  })
588
589  val allPerfEvents = Seq(decode, rename, dispatch, intDq, fpDq, lsDq, rob).flatMap(_.getPerf)
590  val hpmEvents = allPerfEvents ++ perfinfo.perfEventsEu0 ++ perfinfo.perfEventsEu1 ++ perfinfo.perfEventsRs
591  val perfEvents = HPerfMonitor(csrevents, hpmEvents).getPerfEvents
592  generatePerfEvent()
593}
594