xref: /XiangShan/src/main/scala/xiangshan/backend/CtrlBlock.scala (revision 2451989835a019d3c4848f7879147f7649adb760)
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 utility._
24import utils._
25import xiangshan.ExceptionNO._
26import xiangshan._
27import xiangshan.backend.Bundles.{DecodedInst, DynInst, ExceptionInfo, ExuOutput}
28import xiangshan.backend.ctrlblock.{MemCtrl, RedirectGenerator}
29import xiangshan.backend.datapath.DataConfig.VAddrData
30import xiangshan.backend.decode.{DecodeStage, FusionDecoder}
31import xiangshan.backend.dispatch.{Dispatch, DispatchQueue}
32import xiangshan.backend.fu.PFEvent
33import xiangshan.backend.fu.vector.Bundles.VType
34import xiangshan.backend.rename.{Rename, RenameTableWrapper}
35import xiangshan.backend.rob.{Rob, RobCSRIO, RobLsqIO}
36import xiangshan.frontend.{FtqRead, Ftq_RF_Components}
37
38class CtrlToFtqIO(implicit p: Parameters) extends XSBundle {
39  def numRedirect = backendParams.numRedirect
40  val rob_commits = Vec(CommitWidth, Valid(new RobCommitInfo))
41  val redirect = Valid(new Redirect)
42}
43
44class CtrlBlock(params: BackendParams)(implicit p: Parameters) extends LazyModule {
45  val rob = LazyModule(new Rob(params))
46
47  lazy val module = new CtrlBlockImp(this)(p, params)
48
49}
50
51class CtrlBlockImp(
52  override val wrapper: CtrlBlock
53)(implicit
54  p: Parameters,
55  params: BackendParams
56) extends LazyModuleImp(wrapper)
57  with HasXSParameter
58  with HasCircularQueuePtrHelper
59  with HasPerfEvents
60{
61  val pcMemRdIndexes = new NamedIndexes(Seq(
62    "exu"       -> params.numPcReadPort,
63    "redirect"  -> 1,
64    "memPred"   -> 1,
65    "robFlush"  -> 1,
66    "load"      -> params.LduCnt,
67  ))
68
69  private val numPcMemReadForExu = params.numPcReadPort
70  private val numPcMemRead = pcMemRdIndexes.maxIdx
71
72  private val numTargetMemRead = numPcMemReadForExu
73
74  println(s"pcMem read num: $numPcMemRead")
75  println(s"pcMem read num for exu: $numPcMemReadForExu")
76  println(s"targetMem read num: $numTargetMemRead")
77
78  val io = IO(new CtrlBlockIO())
79
80  val decode = Module(new DecodeStage)
81  val fusionDecoder = Module(new FusionDecoder)
82  val rat = Module(new RenameTableWrapper)
83  val rename = Module(new Rename)
84  val dispatch = Module(new Dispatch)
85  val intDq = Module(new DispatchQueue(dpParams.IntDqSize, RenameWidth, dpParams.IntDqDeqWidth))
86  val fpDq = Module(new DispatchQueue(dpParams.FpDqSize, RenameWidth, dpParams.FpDqDeqWidth))
87  val lsDq = Module(new DispatchQueue(dpParams.LsDqSize, RenameWidth, dpParams.LsDqDeqWidth))
88  val redirectGen = Module(new RedirectGenerator)
89  private val pcMem = Module(new SyncDataModuleTemplate(new Ftq_RF_Components, FtqSize, numPcMemRead, 1, "BackendPC"))
90  private val targetMem = Module(new SyncDataModuleTemplate(UInt(VAddrData().dataWidth.W), FtqSize, numTargetMemRead, 1))
91  private val rob = wrapper.rob.module
92  private val memCtrl = Module(new MemCtrl(params))
93
94  private val disableFusion = decode.io.csrCtrl.singlestep || !decode.io.csrCtrl.fusion_enable
95
96  private val s0_robFlushRedirect = rob.io.flushOut
97  private val s1_robFlushRedirect = Wire(Valid(new Redirect))
98  s1_robFlushRedirect.valid := RegNext(s0_robFlushRedirect.valid)
99  s1_robFlushRedirect.bits := RegEnable(s0_robFlushRedirect.bits, s0_robFlushRedirect.valid)
100
101  pcMem.io.raddr(pcMemRdIndexes("robFlush").head) := s0_robFlushRedirect.bits.ftqIdx.value
102  private val s1_robFlushPc = pcMem.io.rdata(pcMemRdIndexes("robFlush").head).getPc(RegNext(s0_robFlushRedirect.bits.ftqOffset))
103  private val s3_redirectGen = redirectGen.io.stage2Redirect
104  private val s1_s3_redirect = Mux(s1_robFlushRedirect.valid, s1_robFlushRedirect, s3_redirectGen)
105  private val s2_s4_pendingRedirectValid = RegInit(false.B)
106  when (s1_s3_redirect.valid) {
107    s2_s4_pendingRedirectValid := true.B
108  }.elsewhen (RegNext(io.frontend.toFtq.redirect.valid)) {
109    s2_s4_pendingRedirectValid := false.B
110  }
111
112  // Redirect will be RegNext at ExuBlocks and IssueBlocks
113  val s2_s4_redirect = RegNextWithEnable(s1_s3_redirect)
114  val s3_s5_redirect = RegNextWithEnable(s2_s4_redirect)
115
116  private val delayedNotFlushedWriteBack = io.fromWB.wbData.map(x => {
117    val valid = x.valid
118    val killedByOlder = x.bits.robIdx.needFlush(Seq(s1_s3_redirect, s2_s4_redirect, s3_s5_redirect))
119    val delayed = Wire(Valid(new ExuOutput(x.bits.params)))
120    delayed.valid := RegNext(valid && !killedByOlder)
121    delayed.bits := RegEnable(x.bits, x.valid)
122    delayed
123  })
124
125  private val exuPredecode = VecInit(
126    delayedNotFlushedWriteBack.filter(_.bits.redirect.nonEmpty).map(x => x.bits.predecodeInfo.get)
127  )
128
129  private val exuRedirects: IndexedSeq[ValidIO[Redirect]] = delayedNotFlushedWriteBack.filter(_.bits.redirect.nonEmpty).map(x => {
130    val out = Wire(Valid(new Redirect()))
131    out.valid := x.valid && x.bits.redirect.get.valid && x.bits.redirect.get.bits.cfiUpdate.isMisPred
132    out.bits := x.bits.redirect.get.bits
133    out
134  })
135
136  private val memViolation = io.fromMem.violation
137  val loadReplay = Wire(ValidIO(new Redirect))
138  loadReplay.valid := RegNext(memViolation.valid &&
139    !memViolation.bits.robIdx.needFlush(Seq(s1_s3_redirect, s2_s4_redirect))
140  )
141  loadReplay.bits := RegEnable(memViolation.bits, memViolation.valid)
142
143  val pdestReverse = rob.io.commits.info.map(info => info.pdest).reverse
144
145  pcMem.io.raddr(pcMemRdIndexes("redirect").head) := redirectGen.io.redirectPcRead.ptr.value
146  redirectGen.io.redirectPcRead.data := pcMem.io.rdata(pcMemRdIndexes("redirect").head).getPc(RegNext(redirectGen.io.redirectPcRead.offset))
147  pcMem.io.raddr(pcMemRdIndexes("memPred").head) := redirectGen.io.memPredPcRead.ptr.value
148  redirectGen.io.memPredPcRead.data := pcMem.io.rdata(pcMemRdIndexes("memPred").head).getPc(RegNext(redirectGen.io.memPredPcRead.offset))
149
150  for ((pcMemIdx, i) <- pcMemRdIndexes("load").zipWithIndex) {
151    pcMem.io.raddr(pcMemIdx) := io.memLdPcRead(i).ptr.value
152    io.memLdPcRead(i).data := pcMem.io.rdata(pcMemIdx).getPc(RegNext(io.memLdPcRead(i).offset))
153  }
154
155  redirectGen.io.hartId := io.fromTop.hartId
156  redirectGen.io.exuRedirect := exuRedirects
157  redirectGen.io.exuOutPredecode := exuPredecode // garded by exuRedirect.valid
158  redirectGen.io.loadReplay <> loadReplay
159
160  redirectGen.io.robFlush := s1_robFlushRedirect.valid
161
162  val s6_frontendFlushValid = DelayN(s1_robFlushRedirect.valid, 5)
163  val frontendFlushBits = RegEnable(s1_robFlushRedirect.bits, s1_robFlushRedirect.valid) // ??
164  // When ROB commits an instruction with a flush, we notify the frontend of the flush without the commit.
165  // Flushes to frontend may be delayed by some cycles and commit before flush causes errors.
166  // Thus, we make all flush reasons to behave the same as exceptions for frontend.
167  for (i <- 0 until CommitWidth) {
168    // why flushOut: instructions with flushPipe are not commited to frontend
169    // If we commit them to frontend, it will cause flush after commit, which is not acceptable by frontend.
170    val s1_isCommit = rob.io.commits.commitValid(i) && rob.io.commits.isCommit && !s0_robFlushRedirect.valid
171    io.frontend.toFtq.rob_commits(i).valid := RegNext(s1_isCommit)
172    io.frontend.toFtq.rob_commits(i).bits := RegEnable(rob.io.commits.info(i), s1_isCommit)
173  }
174  io.frontend.toFtq.redirect.valid := s6_frontendFlushValid || s3_redirectGen.valid
175  io.frontend.toFtq.redirect.bits := Mux(s6_frontendFlushValid, frontendFlushBits, s3_redirectGen.bits)
176  // Be careful here:
177  // T0: rob.io.flushOut, s0_robFlushRedirect
178  // T1: s1_robFlushRedirect, rob.io.exception.valid
179  // T2: csr.redirect.valid
180  // T3: csr.exception.valid
181  // T4: csr.trapTarget
182  // T5: ctrlBlock.trapTarget
183  // T6: io.frontend.toFtq.stage2Redirect.valid
184  val s2_robFlushPc = RegEnable(Mux(s1_robFlushRedirect.bits.flushItself(),
185    s1_robFlushPc, // replay inst
186    s1_robFlushPc + 4.U // flush pipe
187  ), s1_robFlushRedirect.valid)
188  private val s2_csrIsXRet = io.robio.csr.isXRet
189  private val s5_csrIsTrap = DelayN(rob.io.exception.valid, 4)
190  private val s2_s5_trapTargetFromCsr = io.robio.csr.trapTarget
191
192  val flushTarget = Mux(s2_csrIsXRet || s5_csrIsTrap, s2_s5_trapTargetFromCsr, s2_robFlushPc)
193  when (s6_frontendFlushValid) {
194    io.frontend.toFtq.redirect.bits.level := RedirectLevel.flush
195    io.frontend.toFtq.redirect.bits.cfiUpdate.target := RegNext(flushTarget)
196  }
197
198  if (env.EnableTopDown) {
199    val stage2Redirect_valid_when_pending = s2_s4_pendingRedirectValid && s1_s3_redirect.valid
200
201    val stage2_redirect_cycles = RegInit(false.B)                                         // frontend_bound->fetch_lantency->stage2_redirect
202    val MissPredPending = RegInit(false.B); val branch_resteers_cycles = RegInit(false.B) // frontend_bound->fetch_lantency->stage2_redirect->branch_resteers
203    val RobFlushPending = RegInit(false.B); val robFlush_bubble_cycles = RegInit(false.B) // frontend_bound->fetch_lantency->stage2_redirect->robflush_bubble
204    val LdReplayPending = RegInit(false.B); val ldReplay_bubble_cycles = RegInit(false.B) // frontend_bound->fetch_lantency->stage2_redirect->ldReplay_bubble
205
206    when(redirectGen.io.isMisspreRedirect) { MissPredPending := true.B }
207    when(s1_robFlushRedirect.valid)              { RobFlushPending := true.B }
208    when(redirectGen.io.loadReplay.valid)  { LdReplayPending := true.B }
209
210    when (RegNext(io.frontend.toFtq.redirect.valid)) {
211      when(s2_s4_pendingRedirectValid) {                             stage2_redirect_cycles := true.B }
212      when(MissPredPending) { MissPredPending := false.B; branch_resteers_cycles := true.B }
213      when(RobFlushPending) { RobFlushPending := false.B; robFlush_bubble_cycles := true.B }
214      when(LdReplayPending) { LdReplayPending := false.B; ldReplay_bubble_cycles := true.B }
215    }
216
217    when(VecInit(decode.io.out.map(x => x.valid)).asUInt.orR){
218      when(stage2_redirect_cycles) { stage2_redirect_cycles := false.B }
219      when(branch_resteers_cycles) { branch_resteers_cycles := false.B }
220      when(robFlush_bubble_cycles) { robFlush_bubble_cycles := false.B }
221      when(ldReplay_bubble_cycles) { ldReplay_bubble_cycles := false.B }
222    }
223
224    XSPerfAccumulate("stage2_redirect_cycles", stage2_redirect_cycles)
225    XSPerfAccumulate("branch_resteers_cycles", branch_resteers_cycles)
226    XSPerfAccumulate("robFlush_bubble_cycles", robFlush_bubble_cycles)
227    XSPerfAccumulate("ldReplay_bubble_cycles", ldReplay_bubble_cycles)
228    XSPerfAccumulate("s2Redirect_pend_cycles", stage2Redirect_valid_when_pending)
229  }
230
231  // vtype commit
232  decode.io.commitVType.bits := io.fromDataPath.vtype
233  decode.io.commitVType.valid := RegNext(rob.io.isVsetFlushPipe)
234
235  io.toDataPath.vtypeAddr := rob.io.vconfigPdest
236
237  // vtype walk
238  val isVsetSeq = rob.io.commits.walkValid.zip(rob.io.commits.info).map { case (valid, info) => valid && info.isVset }.reverse
239  val walkVTypeReverse = rob.io.commits.info.map(info => info.vtype).reverse
240  val walkVType = PriorityMux(isVsetSeq, walkVTypeReverse)
241
242  decode.io.walkVType.bits := walkVType.asTypeOf(new VType)
243  decode.io.walkVType.valid := rob.io.commits.isWalk && isVsetSeq.reduce(_ || _)
244
245  decode.io.isRedirect := s1_s3_redirect.valid
246
247  decode.io.in.zip(io.frontend.cfVec).foreach { case (decodeIn, frontendCf) =>
248    decodeIn.valid := frontendCf.valid
249    frontendCf.ready := decodeIn.ready
250    decodeIn.bits.connectCtrlFlow(frontendCf.bits)
251  }
252  decode.io.csrCtrl := RegNext(io.csrCtrl)
253  decode.io.intRat <> rat.io.intReadPorts
254  decode.io.fpRat <> rat.io.fpReadPorts
255  decode.io.vecRat <> rat.io.vecReadPorts
256  decode.io.fusion := 0.U.asTypeOf(decode.io.fusion) // Todo
257
258  val decodeHasException = decode.io.out.map(x => x.bits.exceptionVec(instrPageFault) || x.bits.exceptionVec(instrAccessFault))
259  // fusion decoder
260  for (i <- 0 until DecodeWidth) {
261    fusionDecoder.io.in(i).valid := decode.io.out(i).valid && !(decodeHasException(i) || disableFusion)
262    fusionDecoder.io.in(i).bits := decode.io.out(i).bits.instr
263    if (i > 0) {
264      fusionDecoder.io.inReady(i - 1) := decode.io.out(i).ready
265    }
266  }
267
268  private val decodePipeRename = Wire(Vec(RenameWidth, DecoupledIO(new DecodedInst)))
269
270  for (i <- 0 until RenameWidth) {
271    PipelineConnect(decode.io.out(i), decodePipeRename(i), rename.io.in(i).ready,
272      s1_s3_redirect.valid || s2_s4_pendingRedirectValid, moduleName = Some("decodePipeRenameModule"))
273
274    decodePipeRename(i).ready := rename.io.in(i).ready
275    rename.io.in(i).valid := decodePipeRename(i).valid && !fusionDecoder.io.clear(i)
276    rename.io.in(i).bits := decodePipeRename(i).bits
277  }
278
279  for (i <- 0 until RenameWidth - 1) {
280    fusionDecoder.io.dec(i) := decodePipeRename(i).bits
281    rename.io.fusionInfo(i) := fusionDecoder.io.info(i)
282
283    // update the first RenameWidth - 1 instructions
284    decode.io.fusion(i) := fusionDecoder.io.out(i).valid && rename.io.out(i).fire
285    when (fusionDecoder.io.out(i).valid) {
286      fusionDecoder.io.out(i).bits.update(rename.io.in(i).bits)
287      // TODO: remove this dirty code for ftq update
288      val sameFtqPtr = rename.io.in(i).bits.ftqPtr.value === rename.io.in(i + 1).bits.ftqPtr.value
289      val ftqOffset0 = rename.io.in(i).bits.ftqOffset
290      val ftqOffset1 = rename.io.in(i + 1).bits.ftqOffset
291      val ftqOffsetDiff = ftqOffset1 - ftqOffset0
292      val cond1 = sameFtqPtr && ftqOffsetDiff === 1.U
293      val cond2 = sameFtqPtr && ftqOffsetDiff === 2.U
294      val cond3 = !sameFtqPtr && ftqOffset1 === 0.U
295      val cond4 = !sameFtqPtr && ftqOffset1 === 1.U
296      rename.io.in(i).bits.commitType := Mux(cond1, 4.U, Mux(cond2, 5.U, Mux(cond3, 6.U, 7.U)))
297      XSError(!cond1 && !cond2 && !cond3 && !cond4, p"new condition $sameFtqPtr $ftqOffset0 $ftqOffset1\n")
298    }
299
300  }
301
302  // memory dependency predict
303  // when decode, send fold pc to mdp
304  private val mdpFlodPcVec = Wire(Vec(DecodeWidth, UInt(MemPredPCWidth.W)))
305  for (i <- 0 until DecodeWidth) {
306    mdpFlodPcVec(i) := Mux(
307      decode.io.out(i).fire,
308      decode.io.in(i).bits.foldpc,
309      rename.io.in(i).bits.foldpc
310    )
311  }
312
313  // currently, we only update mdp info when isReplay
314  memCtrl.io.redirect := s1_s3_redirect
315  memCtrl.io.csrCtrl := io.csrCtrl                          // RegNext in memCtrl
316  memCtrl.io.stIn := io.fromMem.stIn                        // RegNext in memCtrl
317  memCtrl.io.memPredUpdate := redirectGen.io.memPredUpdate  // RegNext in memCtrl
318  memCtrl.io.mdpFlodPcVec := mdpFlodPcVec
319  memCtrl.io.dispatchLFSTio <> dispatch.io.lfst
320
321  rat.io.redirect := s1_s3_redirect.valid
322  rat.io.robCommits := rob.io.rabCommits
323  rat.io.diffCommits := rob.io.diffCommits
324  rat.io.intRenamePorts := rename.io.intRenamePorts
325  rat.io.fpRenamePorts := rename.io.fpRenamePorts
326  rat.io.vecRenamePorts := rename.io.vecRenamePorts
327
328  rename.io.redirect := s1_s3_redirect
329  rename.io.robCommits <> rob.io.rabCommits
330  rename.io.waittable := (memCtrl.io.waitTable2Rename zip decode.io.out).map{ case(waittable2rename, decodeOut) =>
331    RegEnable(waittable2rename, decodeOut.fire)
332  }
333  rename.io.ssit := memCtrl.io.ssit2Rename
334  rename.io.intReadPorts := VecInit(rat.io.intReadPorts.map(x => VecInit(x.map(_.data))))
335  rename.io.fpReadPorts := VecInit(rat.io.fpReadPorts.map(x => VecInit(x.map(_.data))))
336  rename.io.vecReadPorts := VecInit(rat.io.vecReadPorts.map(x => VecInit(x.map(_.data))))
337  rename.io.debug_int_rat := rat.io.debug_int_rat
338  rename.io.debug_fp_rat := rat.io.debug_fp_rat
339  rename.io.debug_vec_rat := rat.io.debug_vec_rat
340  rename.io.debug_vconfig_rat := rat.io.debug_vconfig_rat
341
342  // pipeline between rename and dispatch
343  for (i <- 0 until RenameWidth) {
344    PipelineConnect(rename.io.out(i), dispatch.io.fromRename(i), dispatch.io.recv(i), s1_s3_redirect.valid)
345  }
346
347  dispatch.io.hartId := io.fromTop.hartId
348  dispatch.io.redirect := s1_s3_redirect
349  dispatch.io.enqRob <> rob.io.enq
350  dispatch.io.singleStep := RegNext(io.csrCtrl.singlestep)
351
352  intDq.io.enq <> dispatch.io.toIntDq
353  intDq.io.redirect <> s2_s4_redirect
354
355  fpDq.io.enq <> dispatch.io.toFpDq
356  fpDq.io.redirect <> s2_s4_redirect
357
358  lsDq.io.enq <> dispatch.io.toLsDq
359  lsDq.io.redirect <> s2_s4_redirect
360
361  io.toIssueBlock.intUops <> intDq.io.deq
362  io.toIssueBlock.vfUops  <> fpDq.io.deq
363  io.toIssueBlock.memUops <> lsDq.io.deq
364  io.toIssueBlock.allocPregs <> dispatch.io.allocPregs
365  io.toIssueBlock.flush   <> s2_s4_redirect
366
367  pcMem.io.wen.head   := RegNext(io.frontend.fromFtq.pc_mem_wen)
368  pcMem.io.waddr.head := RegNext(io.frontend.fromFtq.pc_mem_waddr)
369  pcMem.io.wdata.head := RegNext(io.frontend.fromFtq.pc_mem_wdata)
370  targetMem.io.wen.head := RegNext(io.frontend.fromFtq.pc_mem_wen)
371  targetMem.io.waddr.head := RegNext(io.frontend.fromFtq.pc_mem_waddr)
372  targetMem.io.wdata.head := RegNext(io.frontend.fromFtq.pc_mem_wdata.startAddr)
373
374  private val jumpPcVec         : Vec[UInt] = Wire(Vec(params.numPcReadPort, UInt(VAddrData().dataWidth.W)))
375  private val jumpTargetReadVec : Vec[UInt] = Wire(Vec(params.numPcReadPort, UInt(VAddrData().dataWidth.W)))
376  private val jumpTargetVec     : Vec[UInt] = Wire(Vec(params.numPcReadPort, UInt(VAddrData().dataWidth.W)))
377  io.toIssueBlock.pcVec := jumpPcVec
378  io.toIssueBlock.targetVec := jumpTargetVec
379
380  io.toDataPath.flush := s2_s4_redirect
381  io.toExuBlock.flush := s2_s4_redirect
382
383  for ((pcMemIdx, i) <- pcMemRdIndexes("exu").zipWithIndex) {
384    pcMem.io.raddr(pcMemIdx) := intDq.io.deqNext(i).ftqPtr.value
385    jumpPcVec(i) := pcMem.io.rdata(pcMemIdx).getPc(RegNext(intDq.io.deqNext(i).ftqOffset))
386  }
387
388  val dqOuts = Seq(io.toIssueBlock.intUops) ++ Seq(io.toIssueBlock.vfUops) ++ Seq(io.toIssueBlock.memUops)
389  dqOuts.zipWithIndex.foreach { case (dqOut, dqIdx) =>
390    dqOut.map(_.bits.pc).zipWithIndex.map{ case (pc, portIdx) =>
391      if(params.allSchdParams(dqIdx).numPcReadPort > 0){
392        val realJumpPcVec = jumpPcVec.drop(params.allSchdParams.take(dqIdx).map(_.numPcReadPort).sum).take(params.allSchdParams(dqIdx).numPcReadPort)
393        pc := realJumpPcVec(portIdx)
394      }
395    }
396  }
397
398  private val newestTarget: UInt = io.frontend.fromFtq.newest_entry_target
399  for (i <- 0 until numTargetMemRead) {
400    val targetPtr = intDq.io.deqNext(i).ftqPtr
401    // target pc stored in next entry
402    targetMem.io.raddr(i) := (targetPtr + 1.U).value
403    jumpTargetReadVec(i) := targetMem.io.rdata(i)
404    val needNewestTarget = RegNext(targetPtr === io.frontend.fromFtq.newest_entry_ptr)
405    jumpTargetVec(i) := Mux(
406      needNewestTarget,
407      RegNext(newestTarget),
408      jumpTargetReadVec(i)
409    )
410  }
411
412  rob.io.hartId := io.fromTop.hartId
413  rob.io.redirect := s1_s3_redirect
414  rob.io.writeback := delayedNotFlushedWriteBack
415
416  io.redirect := s1_s3_redirect
417
418  // rob to int block
419  io.robio.csr <> rob.io.csr
420  // When wfi is disabled, it will not block ROB commit.
421  rob.io.csr.wfiEvent := io.robio.csr.wfiEvent
422  rob.io.wfi_enable := decode.io.csrCtrl.wfi_enable
423
424  io.toTop.cpuHalt := DelayN(rob.io.cpu_halt, 5)
425
426  io.robio.csr.perfinfo.retiredInstr <> RegNext(rob.io.csr.perfinfo.retiredInstr)
427  io.robio.exception := rob.io.exception
428  io.robio.exception.bits.pc := s1_robFlushPc
429
430  // rob to mem block
431  io.robio.lsq <> rob.io.lsq
432
433  io.debug_int_rat := rat.io.diff_int_rat
434  io.debug_fp_rat := rat.io.diff_fp_rat
435  io.debug_vec_rat := rat.io.diff_vec_rat
436  io.debug_vconfig_rat := rat.io.diff_vconfig_rat
437
438  io.perfInfo.ctrlInfo.robFull := RegNext(rob.io.robFull)
439  io.perfInfo.ctrlInfo.intdqFull := RegNext(intDq.io.dqFull)
440  io.perfInfo.ctrlInfo.fpdqFull := RegNext(fpDq.io.dqFull)
441  io.perfInfo.ctrlInfo.lsdqFull := RegNext(lsDq.io.dqFull)
442
443  val pfevent = Module(new PFEvent)
444  pfevent.io.distribute_csr := RegNext(io.csrCtrl.distribute_csr)
445  val csrevents = pfevent.io.hpmevent.slice(8,16)
446
447  val perfinfo = IO(new Bundle(){
448    val perfEventsRs      = Input(Vec(params.IqCnt, new PerfEvent))
449    val perfEventsEu0     = Input(Vec(6, new PerfEvent))
450    val perfEventsEu1     = Input(Vec(6, new PerfEvent))
451  })
452
453  val allPerfEvents = Seq(decode, rename, dispatch, intDq, fpDq, lsDq, rob).flatMap(_.getPerf)
454  val hpmEvents = allPerfEvents ++ perfinfo.perfEventsEu0 ++ perfinfo.perfEventsEu1 ++ perfinfo.perfEventsRs
455  val perfEvents = HPerfMonitor(csrevents, hpmEvents).getPerfEvents
456  generatePerfEvent()
457}
458
459class CtrlBlockIO()(implicit p: Parameters, params: BackendParams) extends XSBundle {
460  val fromTop = new Bundle {
461    val hartId = Input(UInt(8.W))
462  }
463  val toTop = new Bundle {
464    val cpuHalt = Output(Bool())
465  }
466  val frontend = Flipped(new FrontendToCtrlIO())
467  val toIssueBlock = new Bundle {
468    val flush = ValidIO(new Redirect)
469    val allocPregs = Vec(RenameWidth, Output(new ResetPregStateReq))
470    val intUops = Vec(dpParams.IntDqDeqWidth, DecoupledIO(new DynInst))
471    val vfUops = Vec(dpParams.FpDqDeqWidth, DecoupledIO(new DynInst))
472    val memUops = Vec(dpParams.LsDqDeqWidth, DecoupledIO(new DynInst))
473    val pcVec = Output(Vec(params.numPcReadPort, UInt(VAddrData().dataWidth.W)))
474    val targetVec = Output(Vec(params.numPcReadPort, UInt(VAddrData().dataWidth.W)))
475  }
476  val fromDataPath = new Bundle{
477    val vtype = Input(new VType)
478  }
479  val toDataPath = new Bundle {
480    val vtypeAddr = Output(UInt(PhyRegIdxWidth.W))
481    val flush = ValidIO(new Redirect)
482  }
483  val toExuBlock = new Bundle {
484    val flush = ValidIO(new Redirect)
485  }
486  val fromWB = new Bundle {
487    val wbData = Flipped(MixedVec(params.genWrite2CtrlBundles))
488  }
489  val redirect = ValidIO(new Redirect)
490  val fromMem = new Bundle {
491    val stIn = Vec(params.StaCnt, Flipped(ValidIO(new DynInst))) // use storeSetHit, ssid, robIdx
492    val violation = Flipped(ValidIO(new Redirect))
493  }
494  val memLdPcRead = Vec(params.LduCnt, Flipped(new FtqRead(UInt(VAddrBits.W))))
495  val csrCtrl = Input(new CustomCSRCtrlIO)
496  val robio = new Bundle {
497    val csr = new RobCSRIO
498    val exception = ValidIO(new ExceptionInfo)
499    val lsq = new RobLsqIO
500  }
501
502  val perfInfo = Output(new Bundle{
503    val ctrlInfo = new Bundle {
504      val robFull   = Bool()
505      val intdqFull = Bool()
506      val fpdqFull  = Bool()
507      val lsdqFull  = Bool()
508    }
509  })
510  val debug_int_rat = Vec(32, Output(UInt(PhyRegIdxWidth.W)))
511  val debug_fp_rat = Vec(32, Output(UInt(PhyRegIdxWidth.W)))
512  val debug_vec_rat = Vec(32, Output(UInt(PhyRegIdxWidth.W)))
513  val debug_vconfig_rat = Output(UInt(PhyRegIdxWidth.W)) // TODO: use me
514
515}
516
517class NamedIndexes(namedCnt: Seq[(String, Int)]) {
518  require(namedCnt.map(_._1).distinct.size == namedCnt.size, "namedCnt should not have the same name")
519
520  val maxIdx = namedCnt.map(_._2).sum
521  val nameRangeMap: Map[String, (Int, Int)] = namedCnt.indices.map { i =>
522    val begin = namedCnt.slice(0, i).map(_._2).sum
523    val end = begin + namedCnt(i)._2
524    (namedCnt(i)._1, (begin, end))
525  }.toMap
526
527  def apply(name: String): Seq[Int] = {
528    require(nameRangeMap.contains(name))
529    nameRangeMap(name)._1 until nameRangeMap(name)._2
530  }
531}
532