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