xref: /XiangShan/src/main/scala/xiangshan/backend/CtrlBlock.scala (revision f7063a43ab34da917ba6c670d21871314340c550)
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 org.chipsalliance.cde.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.{DebugLSIO, DebugLsInfoBundle, LsTopdownInfo, MemCtrl, RedirectGenerator}
29import xiangshan.backend.datapath.DataConfig.VAddrData
30import xiangshan.backend.decode.{DecodeStage, FusionDecoder}
31import xiangshan.backend.dispatch.{CoreDispatchTopDownIO, Dispatch, DispatchQueue}
32import xiangshan.backend.fu.PFEvent
33import xiangshan.backend.fu.vector.Bundles.VType
34import xiangshan.backend.rename.{Rename, RenameTableWrapper, SnapshotGenerator}
35import xiangshan.backend.rob.{Rob, RobCSRIO, RobCoreTopDownIO, RobDebugRollingIO, RobLsqIO, RobPtr}
36import xiangshan.frontend.{FtqPtr, FtqRead, Ftq_RF_Components}
37import xiangshan.mem.{LqPtr, LsqEnqIO}
38import xiangshan.backend.issue.{IntScheduler, VfScheduler, MemScheduler}
39
40class CtrlToFtqIO(implicit p: Parameters) extends XSBundle {
41  val rob_commits = Vec(CommitWidth, Valid(new RobCommitInfo))
42  val redirect = Valid(new Redirect)
43  val ftqIdxAhead = Vec(BackendRedirectNum, Valid(new FtqPtr))
44  val ftqIdxSelOH = Valid(UInt((BackendRedirectNum).W))
45}
46
47class CtrlBlock(params: BackendParams)(implicit p: Parameters) extends LazyModule {
48  override def shouldBeInlined: Boolean = false
49
50  val rob = LazyModule(new Rob(params))
51
52  lazy val module = new CtrlBlockImp(this)(p, params)
53
54  val gpaMem = LazyModule(new GPAMem())
55}
56
57class CtrlBlockImp(
58  override val wrapper: CtrlBlock
59)(implicit
60  p: Parameters,
61  params: BackendParams
62) extends LazyModuleImp(wrapper)
63  with HasXSParameter
64  with HasCircularQueuePtrHelper
65  with HasPerfEvents
66{
67  val pcMemRdIndexes = new NamedIndexes(Seq(
68    "redirect"  -> 1,
69    "memPred"   -> 1,
70    "robFlush"  -> 1,
71    "load"      -> params.LduCnt,
72    "hybrid"    -> params.HyuCnt,
73    "store"     -> (if(EnableStorePrefetchSMS) params.StaCnt else 0)
74  ))
75
76  private val numPcMemReadForExu = params.numPcReadPort
77  private val numPcMemRead = pcMemRdIndexes.maxIdx
78
79  // now pcMem read for exu is moved to PcTargetMem (OG0)
80  println(s"pcMem read num: $numPcMemRead")
81  println(s"pcMem read num for exu: $numPcMemReadForExu")
82
83  val io = IO(new CtrlBlockIO())
84
85  val gpaMem = wrapper.gpaMem.module
86  val decode = Module(new DecodeStage)
87  val fusionDecoder = Module(new FusionDecoder)
88  val rat = Module(new RenameTableWrapper)
89  val rename = Module(new Rename)
90  val dispatch = Module(new Dispatch)
91  val intDq0 = Module(new DispatchQueue(dpParams.IntDqSize, RenameWidth, dpParams.IntDqDeqWidth/2, dqIndex = 0))
92  val intDq1 = Module(new DispatchQueue(dpParams.IntDqSize, RenameWidth, dpParams.IntDqDeqWidth/2, dqIndex = 1))
93  val fpDq = Module(new DispatchQueue(dpParams.FpDqSize, RenameWidth, dpParams.FpDqDeqWidth))
94  val lsDq = Module(new DispatchQueue(dpParams.LsDqSize, RenameWidth, dpParams.LsDqDeqWidth))
95  val redirectGen = Module(new RedirectGenerator)
96  private def hasRen: Boolean = true
97  private val pcMem = Module(new SyncDataModuleTemplate(new Ftq_RF_Components, FtqSize, numPcMemRead, 1, "BackendPC", hasRen = hasRen))
98  private val rob = wrapper.rob.module
99  private val memCtrl = Module(new MemCtrl(params))
100
101  private val disableFusion = decode.io.csrCtrl.singlestep || !decode.io.csrCtrl.fusion_enable
102
103  private val s0_robFlushRedirect = rob.io.flushOut
104  private val s1_robFlushRedirect = Wire(Valid(new Redirect))
105  s1_robFlushRedirect.valid := GatedValidRegNext(s0_robFlushRedirect.valid, false.B)
106  s1_robFlushRedirect.bits := RegEnable(s0_robFlushRedirect.bits, s0_robFlushRedirect.valid)
107
108  pcMem.io.ren.get(pcMemRdIndexes("robFlush").head) := s0_robFlushRedirect.valid
109  pcMem.io.raddr(pcMemRdIndexes("robFlush").head) := s0_robFlushRedirect.bits.ftqIdx.value
110  private val s1_robFlushPc = pcMem.io.rdata(pcMemRdIndexes("robFlush").head).getPc(RegEnable(s0_robFlushRedirect.bits.ftqOffset, s0_robFlushRedirect.valid))
111  private val s3_redirectGen = redirectGen.io.stage2Redirect
112  private val s1_s3_redirect = Mux(s1_robFlushRedirect.valid, s1_robFlushRedirect, s3_redirectGen)
113  private val s2_s4_pendingRedirectValid = RegInit(false.B)
114  when (s1_s3_redirect.valid) {
115    s2_s4_pendingRedirectValid := true.B
116  }.elsewhen (GatedValidRegNext(io.frontend.toFtq.redirect.valid)) {
117    s2_s4_pendingRedirectValid := false.B
118  }
119
120  // Redirect will be RegNext at ExuBlocks and IssueBlocks
121  val s2_s4_redirect = RegNextWithEnable(s1_s3_redirect)
122  val s3_s5_redirect = RegNextWithEnable(s2_s4_redirect)
123
124  private val delayedNotFlushedWriteBack = io.fromWB.wbData.map(x => {
125    val valid = x.valid
126    val killedByOlder = x.bits.robIdx.needFlush(Seq(s1_s3_redirect, s2_s4_redirect, s3_s5_redirect))
127    val delayed = Wire(Valid(new ExuOutput(x.bits.params)))
128    delayed.valid := GatedValidRegNext(valid && !killedByOlder)
129    delayed.bits := RegEnable(x.bits, x.valid)
130    delayed.bits.debugInfo.writebackTime := GTimer()
131    delayed
132  }).toSeq
133
134  val wbDataNoStd = io.fromWB.wbData.filter(!_.bits.params.hasStdFu)
135  val intScheWbData = io.fromWB.wbData.filter(_.bits.params.schdType.isInstanceOf[IntScheduler])
136  val vfScheWbData = io.fromWB.wbData.filter(_.bits.params.schdType.isInstanceOf[VfScheduler])
137  val writeFpVecWbData = io.fromWB.wbData.filter(x => x.bits.params.writeFpRf || x.bits.params.writeVecRf)
138  val memVloadWbData = io.fromWB.wbData.filter(x => x.bits.params.schdType.isInstanceOf[MemScheduler] && x.bits.params.hasVLoadFu)
139  private val delayedNotFlushedWriteBackNums = wbDataNoStd.map(x => {
140    val valid = x.valid
141    val killedByOlder = x.bits.robIdx.needFlush(Seq(s1_s3_redirect, s2_s4_redirect, s3_s5_redirect))
142    val delayed = Wire(Valid(UInt(io.fromWB.wbData.size.U.getWidth.W)))
143    delayed.valid := GatedValidRegNext(valid && !killedByOlder)
144    val isIntSche = intScheWbData.contains(x)
145    val isVfSche = vfScheWbData.contains(x)
146    val isMemVload = memVloadWbData.contains(x)
147    val canSameRobidxWbData = if (isIntSche || isVfSche) {
148      intScheWbData ++ vfScheWbData
149    } else if (isMemVload) {
150      memVloadWbData
151    } else {
152      Seq(x)
153    }
154    val sameRobidxBools = VecInit(canSameRobidxWbData.map( wb => {
155      val killedByOlderThat = wb.bits.robIdx.needFlush(Seq(s1_s3_redirect, s2_s4_redirect, s3_s5_redirect))
156      (wb.bits.robIdx === x.bits.robIdx) && wb.valid && x.valid && !killedByOlderThat && !killedByOlder
157    }).toSeq)
158    delayed.bits := RegEnable(PopCount(sameRobidxBools), x.valid)
159    delayed
160  }).toSeq
161
162  private val exuPredecode = VecInit(
163    delayedNotFlushedWriteBack.filter(_.bits.redirect.nonEmpty).map(x => x.bits.predecodeInfo.get).toSeq
164  )
165
166  private val exuRedirects: Seq[ValidIO[Redirect]] = delayedNotFlushedWriteBack.filter(_.bits.redirect.nonEmpty).map(x => {
167    val out = Wire(Valid(new Redirect()))
168    out.valid := x.valid && x.bits.redirect.get.valid && x.bits.redirect.get.bits.cfiUpdate.isMisPred
169    out.bits := x.bits.redirect.get.bits
170    out.bits.debugIsCtrl := true.B
171    out.bits.debugIsMemVio := false.B
172    out
173  }).toSeq
174
175  private val memViolation = io.fromMem.violation
176  val loadReplay = Wire(ValidIO(new Redirect))
177  loadReplay.valid := GatedValidRegNext(memViolation.valid &&
178    !memViolation.bits.robIdx.needFlush(Seq(s1_s3_redirect, s2_s4_redirect))
179  )
180  loadReplay.bits := RegEnable(memViolation.bits, memViolation.valid)
181  loadReplay.bits.debugIsCtrl := false.B
182  loadReplay.bits.debugIsMemVio := true.B
183
184  pcMem.io.ren.get(pcMemRdIndexes("redirect").head) := redirectGen.io.redirectPcRead.vld
185  pcMem.io.raddr(pcMemRdIndexes("redirect").head) := redirectGen.io.redirectPcRead.ptr.value
186  redirectGen.io.redirectPcRead.data := pcMem.io.rdata(pcMemRdIndexes("redirect").head).getPc(RegEnable(redirectGen.io.redirectPcRead.offset, redirectGen.io.redirectPcRead.vld))
187  pcMem.io.ren.get(pcMemRdIndexes("memPred").head) := redirectGen.io.memPredPcRead.vld
188  pcMem.io.raddr(pcMemRdIndexes("memPred").head) := redirectGen.io.memPredPcRead.ptr.value
189  redirectGen.io.memPredPcRead.data := pcMem.io.rdata(pcMemRdIndexes("memPred").head).getPc(RegEnable(redirectGen.io.memPredPcRead.offset, redirectGen.io.memPredPcRead.vld))
190
191  for ((pcMemIdx, i) <- pcMemRdIndexes("load").zipWithIndex) {
192    // load read pcMem (s0) -> get rdata (s1) -> reg next in Memblock (s2) -> reg next in Memblock (s3) -> consumed by pf (s3)
193    pcMem.io.ren.get(pcMemIdx) := io.memLdPcRead(i).vld
194    pcMem.io.raddr(pcMemIdx) := io.memLdPcRead(i).ptr.value
195    io.memLdPcRead(i).data := pcMem.io.rdata(pcMemIdx).getPc(RegEnable(io.memLdPcRead(i).offset, io.memLdPcRead(i).vld))
196  }
197
198  for ((pcMemIdx, i) <- pcMemRdIndexes("hybrid").zipWithIndex) {
199    // load read pcMem (s0) -> get rdata (s1) -> reg next in Memblock (s2) -> reg next in Memblock (s3) -> consumed by pf (s3)
200    pcMem.io.ren.get(pcMemIdx) := io.memHyPcRead(i).vld
201    pcMem.io.raddr(pcMemIdx) := io.memHyPcRead(i).ptr.value
202    io.memHyPcRead(i).data := pcMem.io.rdata(pcMemIdx).getPc(RegEnable(io.memHyPcRead(i).offset, io.memHyPcRead(i).vld))
203  }
204
205  if (EnableStorePrefetchSMS) {
206    for ((pcMemIdx, i) <- pcMemRdIndexes("store").zipWithIndex) {
207      pcMem.io.ren.get(pcMemIdx) := io.memStPcRead(i).vld
208      pcMem.io.raddr(pcMemIdx) := io.memStPcRead(i).ptr.value
209      io.memStPcRead(i).data := pcMem.io.rdata(pcMemIdx).getPc(RegEnable(io.memStPcRead(i).offset, io.memStPcRead(i).vld))
210    }
211  } else {
212    io.memStPcRead.foreach(_.data := 0.U)
213  }
214
215  redirectGen.io.hartId := io.fromTop.hartId
216  redirectGen.io.exuRedirect := exuRedirects.toSeq
217  redirectGen.io.exuOutPredecode := exuPredecode // guarded by exuRedirect.valid
218  redirectGen.io.loadReplay <> loadReplay
219
220  redirectGen.io.robFlush := s1_robFlushRedirect.valid
221
222  val s5_flushFromRobValidAhead = DelayN(s1_robFlushRedirect.valid, 4)
223  val s6_flushFromRobValid = GatedValidRegNext(s5_flushFromRobValidAhead)
224  val frontendFlushBits = RegEnable(s1_robFlushRedirect.bits, s1_robFlushRedirect.valid) // ??
225  // When ROB commits an instruction with a flush, we notify the frontend of the flush without the commit.
226  // Flushes to frontend may be delayed by some cycles and commit before flush causes errors.
227  // Thus, we make all flush reasons to behave the same as exceptions for frontend.
228  for (i <- 0 until CommitWidth) {
229    // why flushOut: instructions with flushPipe are not commited to frontend
230    // If we commit them to frontend, it will cause flush after commit, which is not acceptable by frontend.
231    val s1_isCommit = rob.io.commits.commitValid(i) && rob.io.commits.isCommit && !s0_robFlushRedirect.valid
232    io.frontend.toFtq.rob_commits(i).valid := GatedValidRegNext(s1_isCommit)
233    io.frontend.toFtq.rob_commits(i).bits := RegEnable(rob.io.commits.info(i), s1_isCommit)
234  }
235  io.frontend.toFtq.redirect.valid := s6_flushFromRobValid || s3_redirectGen.valid
236  io.frontend.toFtq.redirect.bits := Mux(s6_flushFromRobValid, frontendFlushBits, s3_redirectGen.bits)
237  io.frontend.toFtq.ftqIdxSelOH.valid := s6_flushFromRobValid || redirectGen.io.stage2Redirect.valid
238  io.frontend.toFtq.ftqIdxSelOH.bits := Cat(s6_flushFromRobValid, redirectGen.io.stage2oldestOH & Fill(NumRedirect + 1, !s6_flushFromRobValid))
239
240  //jmp/brh
241  for (i <- 0 until NumRedirect) {
242    io.frontend.toFtq.ftqIdxAhead(i).valid := exuRedirects(i).valid && exuRedirects(i).bits.cfiUpdate.isMisPred && !s1_robFlushRedirect.valid && !s5_flushFromRobValidAhead
243    io.frontend.toFtq.ftqIdxAhead(i).bits := exuRedirects(i).bits.ftqIdx
244  }
245  //loadreplay
246  io.frontend.toFtq.ftqIdxAhead(NumRedirect).valid := loadReplay.valid && !s1_robFlushRedirect.valid && !s5_flushFromRobValidAhead
247  io.frontend.toFtq.ftqIdxAhead(NumRedirect).bits := loadReplay.bits.ftqIdx
248  //exception
249  io.frontend.toFtq.ftqIdxAhead.last.valid := s5_flushFromRobValidAhead
250  io.frontend.toFtq.ftqIdxAhead.last.bits := frontendFlushBits.ftqIdx
251
252  io.frontend.canAccept := decode.io.canAccept
253
254  // Be careful here:
255  // T0: rob.io.flushOut, s0_robFlushRedirect
256  // T1: s1_robFlushRedirect, rob.io.exception.valid
257  // T2: csr.redirect.valid
258  // T3: csr.exception.valid
259  // T4: csr.trapTarget
260  // T5: ctrlBlock.trapTarget
261  // T6: io.frontend.toFtq.stage2Redirect.valid
262  val s2_robFlushPc = RegEnable(Mux(s1_robFlushRedirect.bits.flushItself(),
263    s1_robFlushPc, // replay inst
264    s1_robFlushPc + Mux(s1_robFlushRedirect.bits.isRVC, 2.U, 4.U) // flush pipe
265  ), s1_robFlushRedirect.valid)
266  private val s2_csrIsXRet = io.robio.csr.isXRet
267  private val s5_csrIsTrap = DelayN(rob.io.exception.valid, 4)
268  private val s2_s5_trapTargetFromCsr = io.robio.csr.trapTarget
269
270  val flushTarget = Mux(s2_csrIsXRet || s5_csrIsTrap, s2_s5_trapTargetFromCsr, s2_robFlushPc)
271  when (s6_flushFromRobValid) {
272    io.frontend.toFtq.redirect.bits.level := RedirectLevel.flush
273    io.frontend.toFtq.redirect.bits.cfiUpdate.target := RegEnable(flushTarget, s5_flushFromRobValidAhead)
274  }
275
276  for (i <- 0 until DecodeWidth) {
277    gpaMem.io.fromIFU := io.frontend.fromIfu
278    gpaMem.io.exceptionReadAddr.valid := rob.io.readGPAMemAddr.valid
279    gpaMem.io.exceptionReadAddr.bits.ftqPtr := rob.io.readGPAMemAddr.bits.ftqPtr
280    gpaMem.io.exceptionReadAddr.bits.ftqOffset := rob.io.readGPAMemAddr.bits.ftqOffset
281  }
282
283  // vtype commit
284  decode.io.isResumeVType := rob.io.toDecode.isResumeVType
285  decode.io.commitVType := rob.io.toDecode.commitVType
286  decode.io.walkVType := rob.io.toDecode.walkVType
287
288  decode.io.redirect := s1_s3_redirect.valid || s2_s4_pendingRedirectValid
289
290  decode.io.in.zip(io.frontend.cfVec).foreach { case (decodeIn, frontendCf) =>
291    decodeIn.valid := frontendCf.valid
292    frontendCf.ready := decodeIn.ready
293    decodeIn.bits.connectCtrlFlow(frontendCf.bits)
294  }
295  decode.io.csrCtrl := RegNext(io.csrCtrl)
296  decode.io.intRat <> rat.io.intReadPorts
297  decode.io.fpRat <> rat.io.fpReadPorts
298  decode.io.vecRat <> rat.io.vecReadPorts
299  decode.io.fusion := 0.U.asTypeOf(decode.io.fusion) // Todo
300  decode.io.stallReason.in <> io.frontend.stallReason
301
302  // snapshot check
303  class CFIRobIdx extends Bundle {
304    val robIdx = Vec(RenameWidth, new RobPtr)
305    val isCFI = Vec(RenameWidth, Bool())
306  }
307  val genSnapshot = Cat(rename.io.out.map(out => out.fire && out.bits.snapshot)).orR
308  val snpt = Module(new SnapshotGenerator(0.U.asTypeOf(new CFIRobIdx)))
309  snpt.io.enq := genSnapshot
310  snpt.io.enqData.robIdx := rename.io.out.map(_.bits.robIdx)
311  snpt.io.enqData.isCFI := rename.io.out.map(_.bits.snapshot)
312  snpt.io.deq := snpt.io.valids(snpt.io.deqPtr.value) && rob.io.commits.isCommit &&
313    Cat(rob.io.commits.commitValid.zip(rob.io.commits.robIdx).map(x => x._1 && x._2 === snpt.io.snapshots(snpt.io.deqPtr.value).robIdx.head)).orR
314  snpt.io.redirect := s1_s3_redirect.valid
315  val flushVec = VecInit(snpt.io.snapshots.map { snapshot =>
316    val notCFIMask = snapshot.isCFI.map(~_)
317    val shouldFlush = snapshot.robIdx.map(robIdx => robIdx >= s1_s3_redirect.bits.robIdx || robIdx.value === s1_s3_redirect.bits.robIdx.value)
318    val shouldFlushMask = (1 to RenameWidth).map(shouldFlush take _ reduce (_ || _))
319    s1_s3_redirect.valid && Cat(shouldFlushMask.zip(notCFIMask).map(x => x._1 | x._2)).andR
320  })
321  val flushVecNext = flushVec zip snpt.io.valids map (x => GatedValidRegNext(x._1 && x._2, false.B))
322  snpt.io.flushVec := flushVecNext
323
324  val useSnpt = VecInit.tabulate(RenameSnapshotNum)(idx =>
325    snpt.io.valids(idx) && (s1_s3_redirect.bits.robIdx > snpt.io.snapshots(idx).robIdx.head ||
326      !s1_s3_redirect.bits.flushItself() && s1_s3_redirect.bits.robIdx === snpt.io.snapshots(idx).robIdx.head)
327  ).reduceTree(_ || _)
328  val snptSelect = MuxCase(
329    0.U(log2Ceil(RenameSnapshotNum).W),
330    (1 to RenameSnapshotNum).map(i => (snpt.io.enqPtr - i.U).value).map(idx =>
331      (snpt.io.valids(idx) && (s1_s3_redirect.bits.robIdx > snpt.io.snapshots(idx).robIdx.head ||
332        !s1_s3_redirect.bits.flushItself() && s1_s3_redirect.bits.robIdx === snpt.io.snapshots(idx).robIdx.head), idx)
333    )
334  )
335
336  rob.io.snpt.snptEnq := DontCare
337  rob.io.snpt.snptDeq := snpt.io.deq
338  rob.io.snpt.useSnpt := useSnpt
339  rob.io.snpt.snptSelect := snptSelect
340  rob.io.snpt.flushVec := flushVecNext
341  rat.io.snpt.snptEnq := genSnapshot
342  rat.io.snpt.snptDeq := snpt.io.deq
343  rat.io.snpt.useSnpt := useSnpt
344  rat.io.snpt.snptSelect := snptSelect
345  rat.io.snpt.flushVec := flushVec
346
347  val decodeHasException = decode.io.out.map(x => x.bits.exceptionVec(instrPageFault) || x.bits.exceptionVec(instrAccessFault))
348  // fusion decoder
349  for (i <- 0 until DecodeWidth) {
350    fusionDecoder.io.in(i).valid := decode.io.out(i).valid && !(decodeHasException(i) || disableFusion)
351    fusionDecoder.io.in(i).bits := decode.io.out(i).bits.instr
352    if (i > 0) {
353      fusionDecoder.io.inReady(i - 1) := decode.io.out(i).ready
354    }
355  }
356
357  private val decodePipeRename = Wire(Vec(RenameWidth, DecoupledIO(new DecodedInst)))
358
359  for (i <- 0 until RenameWidth) {
360    PipelineConnect(decode.io.out(i), decodePipeRename(i), rename.io.in(i).ready,
361      s1_s3_redirect.valid || s2_s4_pendingRedirectValid, moduleName = Some("decodePipeRenameModule"))
362
363    decodePipeRename(i).ready := rename.io.in(i).ready
364    rename.io.in(i).valid := decodePipeRename(i).valid && !fusionDecoder.io.clear(i)
365    rename.io.in(i).bits := decodePipeRename(i).bits
366  }
367
368  for (i <- 0 until RenameWidth - 1) {
369    fusionDecoder.io.dec(i) := decodePipeRename(i).bits
370    rename.io.fusionInfo(i) := fusionDecoder.io.info(i)
371
372    // update the first RenameWidth - 1 instructions
373    decode.io.fusion(i) := fusionDecoder.io.out(i).valid && rename.io.out(i).fire
374    when (fusionDecoder.io.out(i).valid) {
375      fusionDecoder.io.out(i).bits.update(rename.io.in(i).bits)
376      // TODO: remove this dirty code for ftq update
377      val sameFtqPtr = rename.io.in(i).bits.ftqPtr.value === rename.io.in(i + 1).bits.ftqPtr.value
378      val ftqOffset0 = rename.io.in(i).bits.ftqOffset
379      val ftqOffset1 = rename.io.in(i + 1).bits.ftqOffset
380      val ftqOffsetDiff = ftqOffset1 - ftqOffset0
381      val cond1 = sameFtqPtr && ftqOffsetDiff === 1.U
382      val cond2 = sameFtqPtr && ftqOffsetDiff === 2.U
383      val cond3 = !sameFtqPtr && ftqOffset1 === 0.U
384      val cond4 = !sameFtqPtr && ftqOffset1 === 1.U
385      rename.io.in(i).bits.commitType := Mux(cond1, 4.U, Mux(cond2, 5.U, Mux(cond3, 6.U, 7.U)))
386      XSError(!cond1 && !cond2 && !cond3 && !cond4, p"new condition $sameFtqPtr $ftqOffset0 $ftqOffset1\n")
387    }
388
389  }
390
391  // memory dependency predict
392  // when decode, send fold pc to mdp
393  private val mdpFlodPcVecVld = Wire(Vec(DecodeWidth, Bool()))
394  private val mdpFlodPcVec = Wire(Vec(DecodeWidth, UInt(MemPredPCWidth.W)))
395  for (i <- 0 until DecodeWidth) {
396    mdpFlodPcVecVld(i) := decode.io.out(i).fire || GatedValidRegNext(decode.io.out(i).fire)
397    mdpFlodPcVec(i) := Mux(
398      decode.io.out(i).fire,
399      decode.io.in(i).bits.foldpc,
400      rename.io.in(i).bits.foldpc
401    )
402  }
403
404  // currently, we only update mdp info when isReplay
405  memCtrl.io.redirect := s1_s3_redirect
406  memCtrl.io.csrCtrl := io.csrCtrl                          // RegNext in memCtrl
407  memCtrl.io.stIn := io.fromMem.stIn                        // RegNext in memCtrl
408  memCtrl.io.memPredUpdate := redirectGen.io.memPredUpdate  // RegNext in memCtrl
409  memCtrl.io.mdpFoldPcVecVld := mdpFlodPcVecVld
410  memCtrl.io.mdpFlodPcVec := mdpFlodPcVec
411  memCtrl.io.dispatchLFSTio <> dispatch.io.lfst
412
413  rat.io.redirect := s1_s3_redirect.valid
414  rat.io.rabCommits := rob.io.rabCommits
415  rat.io.diffCommits.foreach(_ := rob.io.diffCommits.get)
416  rat.io.intRenamePorts := rename.io.intRenamePorts
417  rat.io.fpRenamePorts := rename.io.fpRenamePorts
418  rat.io.vecRenamePorts := rename.io.vecRenamePorts
419
420  rename.io.redirect := s1_s3_redirect
421  rename.io.rabCommits := rob.io.rabCommits
422  rename.io.waittable := (memCtrl.io.waitTable2Rename zip decode.io.out).map{ case(waittable2rename, decodeOut) =>
423    RegEnable(waittable2rename, decodeOut.fire)
424  }
425  rename.io.ssit := memCtrl.io.ssit2Rename
426  rename.io.intReadPorts := VecInit(rat.io.intReadPorts.map(x => VecInit(x.map(_.data))))
427  rename.io.fpReadPorts := VecInit(rat.io.fpReadPorts.map(x => VecInit(x.map(_.data))))
428  rename.io.vecReadPorts := VecInit(rat.io.vecReadPorts.map(x => VecInit(x.map(_.data))))
429  rename.io.int_need_free := rat.io.int_need_free
430  rename.io.int_old_pdest := rat.io.int_old_pdest
431  rename.io.fp_old_pdest := rat.io.fp_old_pdest
432  rename.io.vec_old_pdest := rat.io.vec_old_pdest
433  rename.io.debug_int_rat.foreach(_ := rat.io.debug_int_rat.get)
434  rename.io.debug_fp_rat.foreach(_ := rat.io.debug_fp_rat.get)
435  rename.io.debug_vec_rat.foreach(_ := rat.io.debug_vec_rat.get)
436  rename.io.debug_vconfig_rat.foreach(_ := rat.io.debug_vconfig_rat.get)
437  rename.io.stallReason.in <> decode.io.stallReason.out
438  rename.io.snpt.snptEnq := DontCare
439  rename.io.snpt.snptDeq := snpt.io.deq
440  rename.io.snpt.useSnpt := useSnpt
441  rename.io.snpt.snptSelect := snptSelect
442  rename.io.snptIsFull := snpt.io.valids.asUInt.andR
443  rename.io.snpt.flushVec := flushVecNext
444  rename.io.snptLastEnq.valid := !isEmpty(snpt.io.enqPtr, snpt.io.deqPtr)
445  rename.io.snptLastEnq.bits := snpt.io.snapshots((snpt.io.enqPtr - 1.U).value).robIdx.head
446
447  val renameOut = Wire(chiselTypeOf(rename.io.out))
448  renameOut <> rename.io.out
449  // pass all snapshot in the first element for correctness of blockBackward
450  renameOut.tail.foreach(_.bits.snapshot := false.B)
451  renameOut.head.bits.snapshot := Mux(isFull(snpt.io.enqPtr, snpt.io.deqPtr),
452    false.B,
453    Cat(rename.io.out.map(out => out.valid && out.bits.snapshot)).orR
454  )
455
456
457  // pipeline between rename and dispatch
458   for (i <- 0 until RenameWidth) {
459     PipelineConnect(renameOut(i), dispatch.io.fromRename(i), dispatch.io.recv(i), s1_s3_redirect.valid)
460   }
461  dispatch.io.IQValidNumVec := io.IQValidNumVec
462  dispatch.io.fromIntDQ.intDQ0ValidDeq0Num := intDq0.io.validDeq0Num
463  dispatch.io.fromIntDQ.intDQ0ValidDeq1Num := intDq0.io.validDeq1Num
464  dispatch.io.fromIntDQ.intDQ1ValidDeq0Num := intDq1.io.validDeq0Num
465  dispatch.io.fromIntDQ.intDQ1ValidDeq1Num := intDq1.io.validDeq1Num
466
467  dispatch.io.hartId := io.fromTop.hartId
468  dispatch.io.redirect := s1_s3_redirect
469  dispatch.io.enqRob <> rob.io.enq
470  dispatch.io.robHead := rob.io.debugRobHead
471  dispatch.io.stallReason <> rename.io.stallReason.out
472  dispatch.io.lqCanAccept := io.lqCanAccept
473  dispatch.io.sqCanAccept := io.sqCanAccept
474  dispatch.io.robHeadNotReady := rob.io.headNotReady
475  dispatch.io.robFull := rob.io.robFull
476  dispatch.io.singleStep := GatedValidRegNext(io.csrCtrl.singlestep)
477
478  intDq0.io.enq <> dispatch.io.toIntDq0
479  intDq0.io.redirect <> s2_s4_redirect
480  intDq1.io.enq <> dispatch.io.toIntDq1
481  intDq1.io.redirect <> s2_s4_redirect
482
483  fpDq.io.enq <> dispatch.io.toFpDq
484  fpDq.io.redirect <> s2_s4_redirect
485
486  lsDq.io.enq <> dispatch.io.toLsDq
487  lsDq.io.redirect <> s2_s4_redirect
488
489  io.toIssueBlock.intUops <> (intDq0.io.deq :++ intDq1.io.deq)
490  io.toIssueBlock.vfUops  <> fpDq.io.deq
491  io.toIssueBlock.memUops <> lsDq.io.deq
492  io.toIssueBlock.allocPregs <> dispatch.io.allocPregs
493  io.toIssueBlock.flush   <> s2_s4_redirect
494
495  pcMem.io.wen.head   := GatedValidRegNext(io.frontend.fromFtq.pc_mem_wen)
496  pcMem.io.waddr.head := RegEnable(io.frontend.fromFtq.pc_mem_waddr, io.frontend.fromFtq.pc_mem_wen)
497  pcMem.io.wdata.head := RegEnable(io.frontend.fromFtq.pc_mem_wdata, io.frontend.fromFtq.pc_mem_wen)
498
499  io.toDataPath.flush := s2_s4_redirect
500  io.toExuBlock.flush := s2_s4_redirect
501
502
503  rob.io.hartId := io.fromTop.hartId
504  rob.io.redirect := s1_s3_redirect
505  rob.io.writeback := delayedNotFlushedWriteBack
506  rob.io.writebackNums := VecInit(delayedNotFlushedWriteBackNums)
507  rob.io.readGPAMemData := gpaMem.io.exceptionReadData
508
509  io.redirect := s1_s3_redirect
510
511  // rob to int block
512  io.robio.csr <> rob.io.csr
513  // When wfi is disabled, it will not block ROB commit.
514  rob.io.csr.wfiEvent := io.robio.csr.wfiEvent
515  rob.io.wfi_enable := decode.io.csrCtrl.wfi_enable
516
517  io.toTop.cpuHalt := DelayN(rob.io.cpu_halt, 5)
518
519  io.robio.csr.perfinfo.retiredInstr <> RegNext(rob.io.csr.perfinfo.retiredInstr)
520  io.robio.exception := rob.io.exception
521  io.robio.exception.bits.pc := s1_robFlushPc
522  io.robio.exception.bits.gpaddr := 0.U // Todo: get gpaddr gpaMem
523
524  // rob to mem block
525  io.robio.lsq <> rob.io.lsq
526
527  io.debug_int_rat    .foreach(_ := rat.io.diff_int_rat.get)
528  io.debug_fp_rat     .foreach(_ := rat.io.diff_fp_rat.get)
529  io.debug_vec_rat    .foreach(_ := rat.io.diff_vec_rat.get)
530  io.debug_vconfig_rat.foreach(_ := rat.io.diff_vconfig_rat.get)
531
532  rob.io.debug_ls := io.robio.debug_ls
533  rob.io.debugHeadLsIssue := io.robio.robHeadLsIssue
534  rob.io.lsTopdownInfo := io.robio.lsTopdownInfo
535  rob.io.debugEnqLsq := io.debugEnqLsq
536
537  io.robio.robDeqPtr := rob.io.robDeqPtr
538
539  // rob to backend
540  io.robio.commitVType := rob.io.toDecode.commitVType
541  // exu block to decode
542  decode.io.vsetvlVType := io.robio.vsetvlVType
543
544  io.debugTopDown.fromRob := rob.io.debugTopDown.toCore
545  dispatch.io.debugTopDown.fromRob := rob.io.debugTopDown.toDispatch
546  dispatch.io.debugTopDown.fromCore := io.debugTopDown.fromCore
547  io.debugRolling := rob.io.debugRolling
548
549  io.perfInfo.ctrlInfo.robFull := GatedValidRegNext(rob.io.robFull)
550  io.perfInfo.ctrlInfo.intdqFull := GatedValidRegNext(intDq0.io.dqFull || intDq1.io.dqFull)
551  io.perfInfo.ctrlInfo.fpdqFull := GatedValidRegNext(fpDq.io.dqFull)
552  io.perfInfo.ctrlInfo.lsdqFull := GatedValidRegNext(lsDq.io.dqFull)
553
554  val pfevent = Module(new PFEvent)
555  pfevent.io.distribute_csr := RegNext(io.csrCtrl.distribute_csr)
556  val csrevents = pfevent.io.hpmevent.slice(8,16)
557
558  val perfinfo = IO(new Bundle(){
559    val perfEventsRs      = Input(Vec(params.IqCnt, new PerfEvent))
560    val perfEventsEu0     = Input(Vec(6, new PerfEvent))
561    val perfEventsEu1     = Input(Vec(6, new PerfEvent))
562  })
563
564  val perfFromUnits = Seq(decode, rename, dispatch, intDq0, intDq1, fpDq, lsDq, rob).flatMap(_.getPerfEvents)
565  val perfFromIO    = perfinfo.perfEventsEu0.map(x => ("perfEventsEu0", x.value)) ++
566                        perfinfo.perfEventsEu1.map(x => ("perfEventsEu1", x.value)) ++
567                        perfinfo.perfEventsRs.map(x => ("perfEventsRs", x.value))
568  val perfBlock     = Seq()
569  // let index = 0 be no event
570  val allPerfEvents = Seq(("noEvent", 0.U)) ++ perfFromUnits ++ perfFromIO ++ perfBlock
571
572  if (printEventCoding) {
573    for (((name, inc), i) <- allPerfEvents.zipWithIndex) {
574      println("CtrlBlock perfEvents Set", name, inc, i)
575    }
576  }
577
578  val allPerfInc = allPerfEvents.map(_._2.asTypeOf(new PerfEvent))
579  val perfEvents = HPerfMonitor(csrevents, allPerfInc).getPerfEvents
580  generatePerfEvent()
581}
582
583class CtrlBlockIO()(implicit p: Parameters, params: BackendParams) extends XSBundle {
584  val fromTop = new Bundle {
585    val hartId = Input(UInt(8.W))
586  }
587  val toTop = new Bundle {
588    val cpuHalt = Output(Bool())
589  }
590  val frontend = Flipped(new FrontendToCtrlIO())
591  val toIssueBlock = new Bundle {
592    val flush = ValidIO(new Redirect)
593    val allocPregs = Vec(RenameWidth, Output(new ResetPregStateReq))
594    val intUops = Vec(dpParams.IntDqDeqWidth, DecoupledIO(new DynInst))
595    val vfUops = Vec(dpParams.FpDqDeqWidth, DecoupledIO(new DynInst))
596    val memUops = Vec(dpParams.LsDqDeqWidth, DecoupledIO(new DynInst))
597  }
598  val toDataPath = new Bundle {
599    val flush = ValidIO(new Redirect)
600  }
601  val toExuBlock = new Bundle {
602    val flush = ValidIO(new Redirect)
603  }
604  val IQValidNumVec = Input(MixedVec(params.genIQValidNumBundle))
605  val fromWB = new Bundle {
606    val wbData = Flipped(MixedVec(params.genWrite2CtrlBundles))
607  }
608  val redirect = ValidIO(new Redirect)
609  val fromMem = new Bundle {
610    val stIn = Vec(params.StaExuCnt, Flipped(ValidIO(new DynInst))) // use storeSetHit, ssid, robIdx
611    val violation = Flipped(ValidIO(new Redirect))
612  }
613  val memLdPcRead = Vec(params.LduCnt, Flipped(new FtqRead(UInt(VAddrBits.W))))
614  val memStPcRead = Vec(params.StaCnt, Flipped(new FtqRead(UInt(VAddrBits.W))))
615  val memHyPcRead = Vec(params.HyuCnt, Flipped(new FtqRead(UInt(VAddrBits.W))))
616
617  val csrCtrl = Input(new CustomCSRCtrlIO)
618  val robio = new Bundle {
619    val csr = new RobCSRIO
620    val exception = ValidIO(new ExceptionInfo)
621    val lsq = new RobLsqIO
622    val lsTopdownInfo = Vec(params.LduCnt + params.HyuCnt, Input(new LsTopdownInfo))
623    val debug_ls = Input(new DebugLSIO())
624    val robHeadLsIssue = Input(Bool())
625    val robDeqPtr = Output(new RobPtr)
626    val vsetvlVType = Input(VType())
627    val commitVType = new Bundle {
628      val vtype = Output(ValidIO(VType()))
629      val hasVsetvl = Output(Bool())
630    }
631  }
632
633  val perfInfo = Output(new Bundle{
634    val ctrlInfo = new Bundle {
635      val robFull   = Bool()
636      val intdqFull = Bool()
637      val fpdqFull  = Bool()
638      val lsdqFull  = Bool()
639    }
640  })
641  val debug_int_rat     = if (params.debugEn) Some(Vec(32, Output(UInt(PhyRegIdxWidth.W)))) else None
642  val debug_fp_rat      = if (params.debugEn) Some(Vec(32, Output(UInt(PhyRegIdxWidth.W)))) else None
643  val debug_vec_rat     = if (params.debugEn) Some(Vec(32, Output(UInt(PhyRegIdxWidth.W)))) else None
644  val debug_vconfig_rat = if (params.debugEn) Some(Output(UInt(PhyRegIdxWidth.W))) else None // TODO: use me
645
646  val sqCanAccept = Input(Bool())
647  val lqCanAccept = Input(Bool())
648
649  val debugTopDown = new Bundle {
650    val fromRob = new RobCoreTopDownIO
651    val fromCore = new CoreDispatchTopDownIO
652  }
653  val debugRolling = new RobDebugRollingIO
654  val debugEnqLsq = Input(new LsqEnqIO)
655}
656
657class NamedIndexes(namedCnt: Seq[(String, Int)]) {
658  require(namedCnt.map(_._1).distinct.size == namedCnt.size, "namedCnt should not have the same name")
659
660  val maxIdx = namedCnt.map(_._2).sum
661  val nameRangeMap: Map[String, (Int, Int)] = namedCnt.indices.map { i =>
662    val begin = namedCnt.slice(0, i).map(_._2).sum
663    val end = begin + namedCnt(i)._2
664    (namedCnt(i)._1, (begin, end))
665  }.toMap
666
667  def apply(name: String): Seq[Int] = {
668    require(nameRangeMap.contains(name))
669    nameRangeMap(name)._1 until nameRangeMap(name)._2
670  }
671}
672