xref: /XiangShan/src/main/scala/xiangshan/backend/CtrlBlock.scala (revision 94aa21c6009c2f39c5c5dae9c87260c78887efcc)
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, ExuVec, StaticInst, TrapInstInfo}
28import xiangshan.backend.ctrlblock.{DebugLSIO, DebugLsInfoBundle, LsTopdownInfo, MemCtrl, RedirectGenerator}
29import xiangshan.backend.datapath.DataConfig.{FpData, IntData, V0Data, VAddrData, VecData, VlData}
30import xiangshan.backend.decode.{DecodeStage, FusionDecoder}
31import xiangshan.backend.dispatch.{CoreDispatchTopDownIO, Dispatch, DispatchQueue}
32import xiangshan.backend.dispatch.NewDispatch
33import xiangshan.backend.fu.PFEvent
34import xiangshan.backend.fu.vector.Bundles.{VType, Vl}
35import xiangshan.backend.fu.wrapper.CSRToDecode
36import xiangshan.backend.rename.{Rename, RenameTableWrapper, SnapshotGenerator}
37import xiangshan.backend.rob.{Rob, RobCSRIO, RobCoreTopDownIO, RobDebugRollingIO, RobLsqIO, RobPtr}
38import xiangshan.frontend.{FtqPtr, FtqRead, Ftq_RF_Components}
39import xiangshan.mem.{LqPtr, LsqEnqIO, SqPtr}
40import xiangshan.backend.issue.{FpScheduler, IntScheduler, MemScheduler, VfScheduler}
41import xiangshan.backend.trace._
42
43class CtrlToFtqIO(implicit p: Parameters) extends XSBundle {
44  val rob_commits = Vec(CommitWidth, Valid(new RobCommitInfo))
45  val redirect = Valid(new Redirect)
46  val ftqIdxAhead = Vec(BackendRedirectNum, Valid(new FtqPtr))
47  val ftqIdxSelOH = Valid(UInt((BackendRedirectNum).W))
48}
49
50class CtrlBlock(params: BackendParams)(implicit p: Parameters) extends LazyModule {
51  override def shouldBeInlined: Boolean = false
52
53  val rob = LazyModule(new Rob(params))
54
55  lazy val module = new CtrlBlockImp(this)(p, params)
56
57  val gpaMem = LazyModule(new GPAMem())
58}
59
60class CtrlBlockImp(
61  override val wrapper: CtrlBlock
62)(implicit
63  p: Parameters,
64  params: BackendParams
65) extends LazyModuleImp(wrapper)
66  with HasXSParameter
67  with HasCircularQueuePtrHelper
68  with HasPerfEvents
69  with HasCriticalErrors
70{
71  val pcMemRdIndexes = new NamedIndexes(Seq(
72    "redirect"  -> 1,
73    "memPred"   -> 1,
74    "robFlush"  -> 1,
75    "bjuPc"     -> params.BrhCnt,
76    "bjuTarget" -> params.BrhCnt,
77    "load"      -> params.LduCnt,
78    "hybrid"    -> params.HyuCnt,
79    "store"     -> (if(EnableStorePrefetchSMS) params.StaCnt else 0),
80    "trace"     -> TraceGroupNum
81  ))
82
83  private val numPcMemReadForExu = params.numPcReadPort
84  private val numPcMemRead = pcMemRdIndexes.maxIdx
85
86  // now pcMem read for exu is moved to PcTargetMem (OG0)
87  println(s"pcMem read num: $numPcMemRead")
88  println(s"pcMem read num for exu: $numPcMemReadForExu")
89
90  val io = IO(new CtrlBlockIO())
91
92  val dispatch = Module(new NewDispatch)
93  val gpaMem = wrapper.gpaMem.module
94  val decode = Module(new DecodeStage)
95  val fusionDecoder = Module(new FusionDecoder)
96  val rat = Module(new RenameTableWrapper)
97  val rename = Module(new Rename)
98  val redirectGen = Module(new RedirectGenerator)
99  private def hasRen: Boolean = true
100  private val pcMem = Module(new SyncDataModuleTemplate(new Ftq_RF_Components, FtqSize, numPcMemRead, 1, "BackendPC", hasRen = hasRen))
101  private val rob = wrapper.rob.module
102  private val memCtrl = Module(new MemCtrl(params))
103
104  private val disableFusion = decode.io.csrCtrl.singlestep || !decode.io.csrCtrl.fusion_enable
105
106  private val s0_robFlushRedirect = rob.io.flushOut
107  private val s1_robFlushRedirect = Wire(Valid(new Redirect))
108  s1_robFlushRedirect.valid := GatedValidRegNext(s0_robFlushRedirect.valid, false.B)
109  s1_robFlushRedirect.bits := RegEnable(s0_robFlushRedirect.bits, s0_robFlushRedirect.valid)
110
111  pcMem.io.ren.get(pcMemRdIndexes("robFlush").head) := s0_robFlushRedirect.valid
112  pcMem.io.raddr(pcMemRdIndexes("robFlush").head) := s0_robFlushRedirect.bits.ftqIdx.value
113  private val s1_robFlushPc = pcMem.io.rdata(pcMemRdIndexes("robFlush").head).startAddr + (RegEnable(s0_robFlushRedirect.bits.ftqOffset, s0_robFlushRedirect.valid) << instOffsetBits)
114  private val s3_redirectGen = redirectGen.io.stage2Redirect
115  private val s1_s3_redirect = Mux(s1_robFlushRedirect.valid, s1_robFlushRedirect, s3_redirectGen)
116  private val s2_s4_pendingRedirectValid = RegInit(false.B)
117  when (s1_s3_redirect.valid) {
118    s2_s4_pendingRedirectValid := true.B
119  }.elsewhen (GatedValidRegNext(io.frontend.toFtq.redirect.valid)) {
120    s2_s4_pendingRedirectValid := false.B
121  }
122
123  // Redirect will be RegNext at ExuBlocks and IssueBlocks
124  val s2_s4_redirect = RegNextWithEnable(s1_s3_redirect)
125  val s3_s5_redirect = RegNextWithEnable(s2_s4_redirect)
126
127  private val delayedNotFlushedWriteBack = io.fromWB.wbData.map(x => {
128    val valid = x.valid
129    val killedByOlder = x.bits.robIdx.needFlush(Seq(s1_s3_redirect, s2_s4_redirect))
130    val delayed = Wire(Valid(new ExuOutput(x.bits.params)))
131    delayed.valid := GatedValidRegNext(valid && !killedByOlder)
132    delayed.bits := RegEnable(x.bits, x.valid)
133    delayed.bits.debugInfo.writebackTime := GTimer()
134    delayed
135  }).toSeq
136  private val delayedWriteBack = Wire(chiselTypeOf(io.fromWB.wbData))
137  delayedWriteBack.zipWithIndex.map{ case (x,i) =>
138    x.valid := GatedValidRegNext(io.fromWB.wbData(i).valid)
139    x.bits := delayedNotFlushedWriteBack(i).bits
140  }
141  val delayedNotFlushedWriteBackNeedFlush = Wire(Vec(params.allExuParams.filter(_.needExceptionGen).length, Bool()))
142  delayedNotFlushedWriteBackNeedFlush := delayedNotFlushedWriteBack.filter(_.bits.params.needExceptionGen).map{ x =>
143    x.bits.exceptionVec.get.asUInt.orR || x.bits.flushPipe.getOrElse(false.B) || x.bits.replay.getOrElse(false.B) ||
144      (if (x.bits.trigger.nonEmpty) TriggerAction.isDmode(x.bits.trigger.get) else false.B)
145  }
146
147  val wbDataNoStd = io.fromWB.wbData.filter(!_.bits.params.hasStdFu)
148  val intScheWbData = io.fromWB.wbData.filter(_.bits.params.schdType.isInstanceOf[IntScheduler])
149  val fpScheWbData = io.fromWB.wbData.filter(_.bits.params.schdType.isInstanceOf[FpScheduler])
150  val vfScheWbData = io.fromWB.wbData.filter(_.bits.params.schdType.isInstanceOf[VfScheduler])
151  val intCanCompress = intScheWbData.filter(_.bits.params.CanCompress)
152  val i2vWbData = intScheWbData.filter(_.bits.params.writeVecRf)
153  val f2vWbData = fpScheWbData.filter(_.bits.params.writeVecRf)
154  val memVloadWbData = io.fromWB.wbData.filter(x => x.bits.params.schdType.isInstanceOf[MemScheduler] && x.bits.params.hasVLoadFu)
155  private val delayedNotFlushedWriteBackNums = wbDataNoStd.map(x => {
156    val valid = x.valid
157    val killedByOlder = x.bits.robIdx.needFlush(Seq(s1_s3_redirect, s2_s4_redirect, s3_s5_redirect))
158    val delayed = Wire(Valid(UInt(io.fromWB.wbData.size.U.getWidth.W)))
159    delayed.valid := GatedValidRegNext(valid && !killedByOlder)
160    val isIntSche = intCanCompress.contains(x)
161    val isFpSche = fpScheWbData.contains(x)
162    val isVfSche = vfScheWbData.contains(x)
163    val isMemVload = memVloadWbData.contains(x)
164    val isi2v = i2vWbData.contains(x)
165    val isf2v = f2vWbData.contains(x)
166    val canSameRobidxWbData = if(isVfSche) {
167      i2vWbData ++ f2vWbData ++ vfScheWbData
168    } else if(isi2v) {
169      intCanCompress ++ fpScheWbData ++ vfScheWbData
170    } else if (isf2v) {
171      intCanCompress ++ fpScheWbData ++ vfScheWbData
172    } else if (isIntSche) {
173      intCanCompress ++ fpScheWbData
174    } else if (isFpSche) {
175      intCanCompress ++ fpScheWbData
176    }  else if (isMemVload) {
177      memVloadWbData
178    } else {
179      Seq(x)
180    }
181    val sameRobidxBools = VecInit(canSameRobidxWbData.map( wb => {
182      val killedByOlderThat = wb.bits.robIdx.needFlush(Seq(s1_s3_redirect, s2_s4_redirect, s3_s5_redirect))
183      (wb.bits.robIdx === x.bits.robIdx) && wb.valid && x.valid && !killedByOlderThat && !killedByOlder
184    }).toSeq)
185    delayed.bits := RegEnable(PopCount(sameRobidxBools), x.valid)
186    delayed
187  }).toSeq
188
189  private val exuPredecode = VecInit(
190    io.fromWB.wbData.filter(_.bits.redirect.nonEmpty).map(x => x.bits.predecodeInfo.get).toSeq
191  )
192
193  private val exuRedirects: Seq[ValidIO[Redirect]] = io.fromWB.wbData.filter(_.bits.redirect.nonEmpty).map(x => {
194    val out = Wire(Valid(new Redirect()))
195    out.valid := x.valid && x.bits.redirect.get.valid && x.bits.redirect.get.bits.cfiUpdate.isMisPred && !x.bits.robIdx.needFlush(Seq(s1_s3_redirect, s2_s4_redirect))
196    out.bits := x.bits.redirect.get.bits
197    out.bits.debugIsCtrl := true.B
198    out.bits.debugIsMemVio := false.B
199    // for fix timing, next cycle assgin
200    out.bits.cfiUpdate.backendIAF := false.B
201    out.bits.cfiUpdate.backendIPF := false.B
202    out.bits.cfiUpdate.backendIGPF := false.B
203    out
204  }).toSeq
205  private val oldestOneHot = Redirect.selectOldestRedirect(exuRedirects)
206  private val oldestExuRedirect = Mux1H(oldestOneHot, exuRedirects)
207  private val oldestExuPredecode = Mux1H(oldestOneHot, exuPredecode)
208
209  private val memViolation = io.fromMem.violation
210  val loadReplay = Wire(ValidIO(new Redirect))
211  loadReplay.valid := GatedValidRegNext(memViolation.valid)
212  loadReplay.bits := RegEnable(memViolation.bits, memViolation.valid)
213  loadReplay.bits.debugIsCtrl := false.B
214  loadReplay.bits.debugIsMemVio := true.B
215
216  pcMem.io.ren.get(pcMemRdIndexes("redirect").head) := memViolation.valid
217  pcMem.io.raddr(pcMemRdIndexes("redirect").head) := memViolation.bits.ftqIdx.value
218  pcMem.io.ren.get(pcMemRdIndexes("memPred").head) := memViolation.valid
219  pcMem.io.raddr(pcMemRdIndexes("memPred").head) := memViolation.bits.stFtqIdx.value
220  redirectGen.io.memPredPcRead.data := pcMem.io.rdata(pcMemRdIndexes("memPred").head).startAddr + (RegEnable(memViolation.bits.stFtqOffset, memViolation.valid) << instOffsetBits)
221
222  for ((pcMemIdx, i) <- pcMemRdIndexes("bjuPc").zipWithIndex) {
223    val ren = io.toDataPath.pcToDataPathIO.fromDataPathValid(i)
224    val raddr = io.toDataPath.pcToDataPathIO.fromDataPathFtqPtr(i).value
225    val roffset = io.toDataPath.pcToDataPathIO.fromDataPathFtqOffset(i)
226    pcMem.io.ren.get(pcMemIdx) := ren
227    pcMem.io.raddr(pcMemIdx) := raddr
228    io.toDataPath.pcToDataPathIO.toDataPathPC(i) := pcMem.io.rdata(pcMemIdx).startAddr
229  }
230
231  val newestEn = RegNext(io.frontend.fromFtq.newest_entry_en)
232  val newestTarget = RegEnable(io.frontend.fromFtq.newest_entry_target, io.frontend.fromFtq.newest_entry_en)
233  val newestPtr = RegEnable(io.frontend.fromFtq.newest_entry_ptr, io.frontend.fromFtq.newest_entry_en)
234  val newestTargetNext = RegEnable(newestTarget, newestEn)
235  for ((pcMemIdx, i) <- pcMemRdIndexes("bjuTarget").zipWithIndex) {
236    val ren = io.toDataPath.pcToDataPathIO.fromDataPathValid(i)
237    val baseAddr = io.toDataPath.pcToDataPathIO.fromDataPathFtqPtr(i).value
238    val raddr = io.toDataPath.pcToDataPathIO.fromDataPathFtqPtr(i).value + 1.U
239    pcMem.io.ren.get(pcMemIdx) := ren
240    pcMem.io.raddr(pcMemIdx) := raddr
241    val needNewest = RegNext(baseAddr === newestPtr.value)
242    io.toDataPath.pcToDataPathIO.toDataPathTargetPC(i) := Mux(needNewest, newestTargetNext, pcMem.io.rdata(pcMemIdx).startAddr)
243  }
244
245  val baseIdx = params.BrhCnt
246  for ((pcMemIdx, i) <- pcMemRdIndexes("load").zipWithIndex) {
247    // load read pcMem (s0) -> get rdata (s1) -> reg next in Memblock (s2) -> reg next in Memblock (s3) -> consumed by pf (s3)
248    val ren = io.toDataPath.pcToDataPathIO.fromDataPathValid(baseIdx+i)
249    val raddr = io.toDataPath.pcToDataPathIO.fromDataPathFtqPtr(baseIdx+i).value
250    val roffset = io.toDataPath.pcToDataPathIO.fromDataPathFtqOffset(baseIdx+i)
251    pcMem.io.ren.get(pcMemIdx) := ren
252    pcMem.io.raddr(pcMemIdx) := raddr
253    io.toDataPath.pcToDataPathIO.toDataPathPC(baseIdx+i) := pcMem.io.rdata(pcMemIdx).startAddr
254  }
255
256  for ((pcMemIdx, i) <- pcMemRdIndexes("hybrid").zipWithIndex) {
257    // load read pcMem (s0) -> get rdata (s1) -> reg next in Memblock (s2) -> reg next in Memblock (s3) -> consumed by pf (s3)
258    pcMem.io.ren.get(pcMemIdx) := io.memHyPcRead(i).valid
259    pcMem.io.raddr(pcMemIdx) := io.memHyPcRead(i).ptr.value
260    io.memHyPcRead(i).data := pcMem.io.rdata(pcMemIdx).startAddr + (RegEnable(io.memHyPcRead(i).offset, io.memHyPcRead(i).valid) << instOffsetBits)
261  }
262
263  if (EnableStorePrefetchSMS) {
264    for ((pcMemIdx, i) <- pcMemRdIndexes("store").zipWithIndex) {
265      pcMem.io.ren.get(pcMemIdx) := io.memStPcRead(i).valid
266      pcMem.io.raddr(pcMemIdx) := io.memStPcRead(i).ptr.value
267      io.memStPcRead(i).data := pcMem.io.rdata(pcMemIdx).startAddr + (RegEnable(io.memStPcRead(i).offset, io.memStPcRead(i).valid) << instOffsetBits)
268    }
269  } else {
270    io.memStPcRead.foreach(_.data := 0.U)
271  }
272
273  /**
274   * trace begin
275   */
276  val trace = Module(new Trace)
277  trace.io.in.fromEncoder.stall  := io.traceCoreInterface.fromEncoder.stall
278  trace.io.in.fromEncoder.enable := io.traceCoreInterface.fromEncoder.enable
279  trace.io.in.fromRob            := rob.io.trace.traceCommitInfo
280  rob.io.trace.blockCommit       := trace.io.out.blockRobCommit
281  val tracePcStart = Wire(Vec(TraceGroupNum, UInt(IaddrWidth.W)))
282  for ((pcMemIdx, i) <- pcMemRdIndexes("trace").zipWithIndex) {
283    val traceValid = trace.toPcMem.blocks(i).valid
284    pcMem.io.ren.get(pcMemIdx) := traceValid
285    pcMem.io.raddr(pcMemIdx) := trace.toPcMem.blocks(i).bits.ftqIdx.get.value
286    tracePcStart(i) := pcMem.io.rdata(pcMemIdx).startAddr
287  }
288
289  // Trap/Xret only occur in block(0).
290  val tracePriv = Mux(Itype.isTrapOrXret(trace.toEncoder.blocks(0).bits.tracePipe.itype),
291    io.fromCSR.traceCSR.lastPriv,
292    io.fromCSR.traceCSR.currentPriv
293  )
294  io.traceCoreInterface.toEncoder.trap.cause := io.fromCSR.traceCSR.cause.asUInt
295  io.traceCoreInterface.toEncoder.trap.tval  := io.fromCSR.traceCSR.tval.asUInt
296  io.traceCoreInterface.toEncoder.priv       := tracePriv
297  (0 until TraceGroupNum).foreach(i => {
298    io.traceCoreInterface.toEncoder.groups(i).valid := trace.io.out.toEncoder.blocks(i).valid
299    io.traceCoreInterface.toEncoder.groups(i).bits.iaddr := tracePcStart(i)
300    io.traceCoreInterface.toEncoder.groups(i).bits.ftqOffset.foreach(_ := trace.io.out.toEncoder.blocks(i).bits.ftqOffset.getOrElse(0.U))
301    io.traceCoreInterface.toEncoder.groups(i).bits.itype := trace.io.out.toEncoder.blocks(i).bits.tracePipe.itype
302    io.traceCoreInterface.toEncoder.groups(i).bits.iretire := trace.io.out.toEncoder.blocks(i).bits.tracePipe.iretire
303    io.traceCoreInterface.toEncoder.groups(i).bits.ilastsize := trace.io.out.toEncoder.blocks(i).bits.tracePipe.ilastsize
304  })
305  /**
306   * trace end
307   */
308
309
310  redirectGen.io.hartId := io.fromTop.hartId
311  redirectGen.io.oldestExuRedirect.valid := GatedValidRegNext(oldestExuRedirect.valid)
312  redirectGen.io.oldestExuRedirect.bits := RegEnable(oldestExuRedirect.bits, oldestExuRedirect.valid)
313  redirectGen.io.instrAddrTransType := RegNext(io.fromCSR.instrAddrTransType)
314  redirectGen.io.oldestExuOutPredecode.valid := GatedValidRegNext(oldestExuPredecode.valid)
315  redirectGen.io.oldestExuOutPredecode := RegEnable(oldestExuPredecode, oldestExuPredecode.valid)
316  redirectGen.io.loadReplay <> loadReplay
317  val loadRedirectOffset = Mux(memViolation.bits.flushItself(), 0.U, Mux(memViolation.bits.isRVC, 2.U, 4.U))
318  val loadRedirectPcFtqOffset = RegEnable((memViolation.bits.ftqOffset << instOffsetBits).asUInt +& loadRedirectOffset, memViolation.valid)
319  val loadRedirectPcRead = pcMem.io.rdata(pcMemRdIndexes("redirect").head).startAddr + loadRedirectPcFtqOffset
320
321  redirectGen.io.loadReplay.bits.cfiUpdate.pc := loadRedirectPcRead
322  val load_target = loadRedirectPcRead
323  redirectGen.io.loadReplay.bits.cfiUpdate.target := load_target
324
325  redirectGen.io.robFlush := s1_robFlushRedirect
326
327  val s5_flushFromRobValidAhead = DelayN(s1_robFlushRedirect.valid, 4)
328  val s6_flushFromRobValid = GatedValidRegNext(s5_flushFromRobValidAhead)
329  val frontendFlushBits = RegEnable(s1_robFlushRedirect.bits, s1_robFlushRedirect.valid) // ??
330  // When ROB commits an instruction with a flush, we notify the frontend of the flush without the commit.
331  // Flushes to frontend may be delayed by some cycles and commit before flush causes errors.
332  // Thus, we make all flush reasons to behave the same as exceptions for frontend.
333  for (i <- 0 until CommitWidth) {
334    // why flushOut: instructions with flushPipe are not commited to frontend
335    // If we commit them to frontend, it will cause flush after commit, which is not acceptable by frontend.
336    val s1_isCommit = rob.io.commits.commitValid(i) && rob.io.commits.isCommit && !s0_robFlushRedirect.valid
337    io.frontend.toFtq.rob_commits(i).valid := GatedValidRegNext(s1_isCommit)
338    io.frontend.toFtq.rob_commits(i).bits := RegEnable(rob.io.commits.info(i), s1_isCommit)
339  }
340  io.frontend.toFtq.redirect.valid := s6_flushFromRobValid || s3_redirectGen.valid
341  io.frontend.toFtq.redirect.bits := Mux(s6_flushFromRobValid, frontendFlushBits, s3_redirectGen.bits)
342  io.frontend.toFtq.ftqIdxSelOH.valid := s6_flushFromRobValid || redirectGen.io.stage2Redirect.valid
343  io.frontend.toFtq.ftqIdxSelOH.bits := Cat(s6_flushFromRobValid, redirectGen.io.stage2oldestOH & Fill(NumRedirect + 1, !s6_flushFromRobValid))
344
345  //jmp/brh, sel oldest first, only use one read port
346  io.frontend.toFtq.ftqIdxAhead(0).valid := RegNext(oldestExuRedirect.valid) && !s1_robFlushRedirect.valid && !s5_flushFromRobValidAhead
347  io.frontend.toFtq.ftqIdxAhead(0).bits := RegEnable(oldestExuRedirect.bits.ftqIdx, oldestExuRedirect.valid)
348  //loadreplay
349  io.frontend.toFtq.ftqIdxAhead(NumRedirect).valid := loadReplay.valid && !s1_robFlushRedirect.valid && !s5_flushFromRobValidAhead
350  io.frontend.toFtq.ftqIdxAhead(NumRedirect).bits := loadReplay.bits.ftqIdx
351  //exception
352  io.frontend.toFtq.ftqIdxAhead.last.valid := s5_flushFromRobValidAhead
353  io.frontend.toFtq.ftqIdxAhead.last.bits := frontendFlushBits.ftqIdx
354
355  // Be careful here:
356  // T0: rob.io.flushOut, s0_robFlushRedirect
357  // T1: s1_robFlushRedirect, rob.io.exception.valid
358  // T2: csr.redirect.valid
359  // T3: csr.exception.valid
360  // T4: csr.trapTarget
361  // T5: ctrlBlock.trapTarget
362  // T6: io.frontend.toFtq.stage2Redirect.valid
363  val s2_robFlushPc = RegEnable(Mux(s1_robFlushRedirect.bits.flushItself(),
364    s1_robFlushPc, // replay inst
365    s1_robFlushPc + Mux(s1_robFlushRedirect.bits.isRVC, 2.U, 4.U) // flush pipe
366  ), s1_robFlushRedirect.valid)
367  private val s5_csrIsTrap = DelayN(rob.io.exception.valid, 4)
368  private val s5_trapTargetFromCsr = io.robio.csr.trapTarget
369
370  val flushTarget = Mux(s5_csrIsTrap, s5_trapTargetFromCsr.pc, s2_robFlushPc)
371  val s5_trapTargetIAF = Mux(s5_csrIsTrap, s5_trapTargetFromCsr.raiseIAF, false.B)
372  val s5_trapTargetIPF = Mux(s5_csrIsTrap, s5_trapTargetFromCsr.raiseIPF, false.B)
373  val s5_trapTargetIGPF = Mux(s5_csrIsTrap, s5_trapTargetFromCsr.raiseIGPF, false.B)
374  when (s6_flushFromRobValid) {
375    io.frontend.toFtq.redirect.bits.level := RedirectLevel.flush
376    io.frontend.toFtq.redirect.bits.cfiUpdate.target := RegEnable(flushTarget, s5_flushFromRobValidAhead)
377    io.frontend.toFtq.redirect.bits.cfiUpdate.backendIAF := RegEnable(s5_trapTargetIAF, s5_flushFromRobValidAhead)
378    io.frontend.toFtq.redirect.bits.cfiUpdate.backendIPF := RegEnable(s5_trapTargetIPF, s5_flushFromRobValidAhead)
379    io.frontend.toFtq.redirect.bits.cfiUpdate.backendIGPF := RegEnable(s5_trapTargetIGPF, s5_flushFromRobValidAhead)
380  }
381
382  for (i <- 0 until DecodeWidth) {
383    gpaMem.io.fromIFU := io.frontend.fromIfu
384    gpaMem.io.exceptionReadAddr.valid := rob.io.readGPAMemAddr.valid
385    gpaMem.io.exceptionReadAddr.bits.ftqPtr := rob.io.readGPAMemAddr.bits.ftqPtr
386    gpaMem.io.exceptionReadAddr.bits.ftqOffset := rob.io.readGPAMemAddr.bits.ftqOffset
387  }
388
389  // vtype commit
390  decode.io.fromCSR := io.fromCSR.toDecode
391  decode.io.fromRob.isResumeVType := rob.io.toDecode.isResumeVType
392  decode.io.fromRob.walkToArchVType := rob.io.toDecode.walkToArchVType
393  decode.io.fromRob.commitVType := rob.io.toDecode.commitVType
394  decode.io.fromRob.walkVType := rob.io.toDecode.walkVType
395
396  decode.io.redirect := s1_s3_redirect.valid || s2_s4_pendingRedirectValid
397
398  // add decode Buf for in.ready better timing
399  val decodeBufBits = Reg(Vec(DecodeWidth, new StaticInst))
400  val decodeBufValid = RegInit(VecInit(Seq.fill(DecodeWidth)(false.B)))
401  val decodeFromFrontend = io.frontend.cfVec
402  val decodeBufNotAccept = VecInit(decodeBufValid.zip(decode.io.in).map(x => x._1 && !x._2.ready))
403  val decodeBufAcceptNum = PriorityMuxDefault(decodeBufNotAccept.zip(Seq.tabulate(DecodeWidth)(i => i.U)), DecodeWidth.U)
404  val decodeFromFrontendNotAccept = VecInit(decodeFromFrontend.zip(decode.io.in).map(x => decodeBufValid(0) || x._1.valid && !x._2.ready))
405  val decodeFromFrontendAcceptNum = PriorityMuxDefault(decodeFromFrontendNotAccept.zip(Seq.tabulate(DecodeWidth)(i => i.U)), DecodeWidth.U)
406  if (backendParams.debugEn) {
407    dontTouch(decodeBufNotAccept)
408    dontTouch(decodeBufAcceptNum)
409    dontTouch(decodeFromFrontendNotAccept)
410    dontTouch(decodeFromFrontendAcceptNum)
411  }
412  val a = decodeBufNotAccept.drop(2)
413  for (i <- 0 until DecodeWidth) {
414    // decodeBufValid update
415    when(decode.io.redirect || decodeBufValid(0) && decodeBufValid(i) && decode.io.in(i).ready && !VecInit(decodeBufNotAccept.drop(i)).asUInt.orR) {
416      decodeBufValid(i) := false.B
417    }.elsewhen(decodeBufValid(i) && VecInit(decodeBufNotAccept.drop(i)).asUInt.orR) {
418      decodeBufValid(i) := Mux(decodeBufAcceptNum > DecodeWidth.U - 1.U - i.U, false.B, decodeBufValid(i.U + decodeBufAcceptNum))
419    }.elsewhen(!decodeBufValid(0) && VecInit(decodeFromFrontendNotAccept.drop(i)).asUInt.orR) {
420      decodeBufValid(i) := Mux(decodeFromFrontendAcceptNum > DecodeWidth.U - 1.U - i.U, false.B, decodeFromFrontend(i.U + decodeFromFrontendAcceptNum).valid)
421    }
422    // decodeBufBits update
423    when(decodeBufValid(i) && VecInit(decodeBufNotAccept.drop(i)).asUInt.orR) {
424      decodeBufBits(i) := decodeBufBits(i.U + decodeBufAcceptNum)
425    }.elsewhen(!decodeBufValid(0) && VecInit(decodeFromFrontendNotAccept.drop(i)).asUInt.orR) {
426      decodeBufBits(i).connectCtrlFlow(decodeFromFrontend(i.U + decodeFromFrontendAcceptNum).bits)
427    }
428  }
429  val decodeConnectFromFrontend = Wire(Vec(DecodeWidth, new StaticInst))
430  decodeConnectFromFrontend.zip(decodeFromFrontend).map(x => x._1.connectCtrlFlow(x._2.bits))
431  decode.io.in.zipWithIndex.foreach { case (decodeIn, i) =>
432    decodeIn.valid := Mux(decodeBufValid(0), decodeBufValid(i), decodeFromFrontend(i).valid)
433    decodeFromFrontend(i).ready := decodeFromFrontend(0).valid && !decodeBufValid(0) && decodeFromFrontend(i).valid && !decode.io.redirect
434    decodeIn.bits := Mux(decodeBufValid(i), decodeBufBits(i), decodeConnectFromFrontend(i))
435  }
436  io.frontend.canAccept := !decodeBufValid(0) || !decodeFromFrontend(0).valid
437  decode.io.csrCtrl := RegNext(io.csrCtrl)
438  decode.io.intRat <> rat.io.intReadPorts
439  decode.io.fpRat <> rat.io.fpReadPorts
440  decode.io.vecRat <> rat.io.vecReadPorts
441  decode.io.v0Rat <> rat.io.v0ReadPorts
442  decode.io.vlRat <> rat.io.vlReadPorts
443  decode.io.fusion := 0.U.asTypeOf(decode.io.fusion) // Todo
444  decode.io.stallReason.in <> io.frontend.stallReason
445
446  // snapshot check
447  class CFIRobIdx extends Bundle {
448    val robIdx = Vec(RenameWidth, new RobPtr)
449    val isCFI = Vec(RenameWidth, Bool())
450  }
451  val genSnapshot = Cat(rename.io.out.map(out => out.fire && out.bits.snapshot)).orR
452  val snpt = Module(new SnapshotGenerator(0.U.asTypeOf(new CFIRobIdx)))
453  snpt.io.enq := genSnapshot
454  snpt.io.enqData.robIdx := rename.io.out.map(_.bits.robIdx)
455  snpt.io.enqData.isCFI := rename.io.out.map(_.bits.snapshot)
456  snpt.io.deq := snpt.io.valids(snpt.io.deqPtr.value) && rob.io.commits.isCommit &&
457    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
458  snpt.io.redirect := s1_s3_redirect.valid
459  val flushVec = VecInit(snpt.io.snapshots.map { snapshot =>
460    val notCFIMask = snapshot.isCFI.map(~_)
461    val shouldFlush = snapshot.robIdx.map(robIdx => robIdx >= s1_s3_redirect.bits.robIdx || robIdx.value === s1_s3_redirect.bits.robIdx.value)
462    val shouldFlushMask = (1 to RenameWidth).map(shouldFlush take _ reduce (_ || _))
463    s1_s3_redirect.valid && Cat(shouldFlushMask.zip(notCFIMask).map(x => x._1 | x._2)).andR
464  })
465  val flushVecNext = flushVec zip snpt.io.valids map (x => GatedValidRegNext(x._1 && x._2, false.B))
466  snpt.io.flushVec := flushVecNext
467
468  val redirectRobidx = s1_s3_redirect.bits.robIdx
469  val useSnpt = VecInit.tabulate(RenameSnapshotNum){ case idx =>
470    val snptRobidx = snpt.io.snapshots(idx).robIdx.head
471    // (redirectRobidx.value =/= snptRobidx.value) for only flag diffrence
472    snpt.io.valids(idx) && ((redirectRobidx > snptRobidx) && (redirectRobidx.value =/= snptRobidx.value) ||
473      !s1_s3_redirect.bits.flushItself() && redirectRobidx === snptRobidx)
474  }.reduceTree(_ || _)
475  val snptSelect = MuxCase(
476    0.U(log2Ceil(RenameSnapshotNum).W),
477    (1 to RenameSnapshotNum).map(i => (snpt.io.enqPtr - i.U).value).map(idx =>
478      (snpt.io.valids(idx) && (s1_s3_redirect.bits.robIdx > snpt.io.snapshots(idx).robIdx.head ||
479        !s1_s3_redirect.bits.flushItself() && s1_s3_redirect.bits.robIdx === snpt.io.snapshots(idx).robIdx.head), idx)
480    )
481  )
482
483  rob.io.snpt.snptEnq := DontCare
484  rob.io.snpt.snptDeq := snpt.io.deq
485  rob.io.snpt.useSnpt := useSnpt
486  rob.io.snpt.snptSelect := snptSelect
487  rob.io.snpt.flushVec := flushVecNext
488  rat.io.snpt.snptEnq := genSnapshot
489  rat.io.snpt.snptDeq := snpt.io.deq
490  rat.io.snpt.useSnpt := useSnpt
491  rat.io.snpt.snptSelect := snptSelect
492  rat.io.snpt.flushVec := flushVec
493
494  val decodeHasException = decode.io.out.map(x => x.bits.exceptionVec(instrPageFault) || x.bits.exceptionVec(instrAccessFault))
495  // fusion decoder
496  for (i <- 0 until DecodeWidth) {
497    fusionDecoder.io.in(i).valid := decode.io.out(i).valid && !(decodeHasException(i) || disableFusion)
498    fusionDecoder.io.in(i).bits := decode.io.out(i).bits.instr
499    if (i > 0) {
500      fusionDecoder.io.inReady(i - 1) := decode.io.out(i).ready
501    }
502  }
503
504  private val decodePipeRename = Wire(Vec(RenameWidth, DecoupledIO(new DecodedInst)))
505  for (i <- 0 until RenameWidth) {
506    PipelineConnect(decode.io.out(i), decodePipeRename(i), rename.io.in(i).ready,
507      s1_s3_redirect.valid || s2_s4_pendingRedirectValid, moduleName = Some("decodePipeRenameModule"))
508
509    decodePipeRename(i).ready := rename.io.in(i).ready
510    rename.io.in(i).valid := decodePipeRename(i).valid && !fusionDecoder.io.clear(i)
511    rename.io.in(i).bits := decodePipeRename(i).bits
512    dispatch.io.renameIn(i).valid := decodePipeRename(i).valid && !fusionDecoder.io.clear(i) && !decodePipeRename(i).bits.isMove
513    dispatch.io.renameIn(i).bits := decodePipeRename(i).bits
514  }
515
516  for (i <- 0 until RenameWidth - 1) {
517    fusionDecoder.io.dec(i) := decodePipeRename(i).bits
518    rename.io.fusionInfo(i) := fusionDecoder.io.info(i)
519
520    // update the first RenameWidth - 1 instructions
521    decode.io.fusion(i) := fusionDecoder.io.out(i).valid && rename.io.out(i).fire
522    // TODO: remove this dirty code for ftq update
523    val sameFtqPtr = rename.io.in(i).bits.ftqPtr.value === rename.io.in(i + 1).bits.ftqPtr.value
524    val ftqOffset0 = rename.io.in(i).bits.ftqOffset
525    val ftqOffset1 = rename.io.in(i + 1).bits.ftqOffset
526    val ftqOffsetDiff = ftqOffset1 - ftqOffset0
527    val cond1 = sameFtqPtr && ftqOffsetDiff === 1.U
528    val cond2 = sameFtqPtr && ftqOffsetDiff === 2.U
529    val cond3 = !sameFtqPtr && ftqOffset1 === 0.U
530    val cond4 = !sameFtqPtr && ftqOffset1 === 1.U
531    when (fusionDecoder.io.out(i).valid) {
532      fusionDecoder.io.out(i).bits.update(rename.io.in(i).bits)
533      fusionDecoder.io.out(i).bits.update(dispatch.io.renameIn(i).bits)
534      rename.io.in(i).bits.commitType := Mux(cond1, 4.U, Mux(cond2, 5.U, Mux(cond3, 6.U, 7.U)))
535    }
536    XSError(fusionDecoder.io.out(i).valid && !cond1 && !cond2 && !cond3 && !cond4, p"new condition $sameFtqPtr $ftqOffset0 $ftqOffset1\n")
537  }
538
539  // memory dependency predict
540  // when decode, send fold pc to mdp
541  private val mdpFlodPcVecVld = Wire(Vec(DecodeWidth, Bool()))
542  private val mdpFlodPcVec = Wire(Vec(DecodeWidth, UInt(MemPredPCWidth.W)))
543  for (i <- 0 until DecodeWidth) {
544    mdpFlodPcVecVld(i) := decode.io.out(i).fire || GatedValidRegNext(decode.io.out(i).fire)
545    mdpFlodPcVec(i) := Mux(
546      decode.io.out(i).fire,
547      decode.io.in(i).bits.foldpc,
548      rename.io.in(i).bits.foldpc
549    )
550  }
551
552  // currently, we only update mdp info when isReplay
553  memCtrl.io.redirect := s1_s3_redirect
554  memCtrl.io.csrCtrl := io.csrCtrl                          // RegNext in memCtrl
555  memCtrl.io.stIn := io.fromMem.stIn                        // RegNext in memCtrl
556  memCtrl.io.memPredUpdate := redirectGen.io.memPredUpdate  // RegNext in memCtrl
557  memCtrl.io.mdpFoldPcVecVld := mdpFlodPcVecVld
558  memCtrl.io.mdpFlodPcVec := mdpFlodPcVec
559  memCtrl.io.dispatchLFSTio <> dispatch.io.lfst
560
561  rat.io.redirect := s1_s3_redirect.valid
562  rat.io.rabCommits := rob.io.rabCommits
563  rat.io.diffCommits.foreach(_ := rob.io.diffCommits.get)
564  rat.io.intRenamePorts := rename.io.intRenamePorts
565  rat.io.fpRenamePorts := rename.io.fpRenamePorts
566  rat.io.vecRenamePorts := rename.io.vecRenamePorts
567  rat.io.v0RenamePorts := rename.io.v0RenamePorts
568  rat.io.vlRenamePorts := rename.io.vlRenamePorts
569
570  rename.io.redirect := s1_s3_redirect
571  rename.io.rabCommits := rob.io.rabCommits
572  rename.io.singleStep := GatedValidRegNext(io.csrCtrl.singlestep)
573  rename.io.waittable := (memCtrl.io.waitTable2Rename zip decode.io.out).map{ case(waittable2rename, decodeOut) =>
574    RegEnable(waittable2rename, decodeOut.fire)
575  }
576  rename.io.ssit := memCtrl.io.ssit2Rename
577  // disble mdp
578  dispatch.io.lfst.resp := 0.U.asTypeOf(dispatch.io.lfst.resp)
579  rename.io.waittable := 0.U.asTypeOf(rename.io.waittable)
580  rename.io.ssit := 0.U.asTypeOf(rename.io.ssit)
581  rename.io.intReadPorts := VecInit(rat.io.intReadPorts.map(x => VecInit(x.map(_.data))))
582  rename.io.fpReadPorts := VecInit(rat.io.fpReadPorts.map(x => VecInit(x.map(_.data))))
583  rename.io.vecReadPorts := VecInit(rat.io.vecReadPorts.map(x => VecInit(x.map(_.data))))
584  rename.io.v0ReadPorts := VecInit(rat.io.v0ReadPorts.map(x => VecInit(x.data)))
585  rename.io.vlReadPorts := VecInit(rat.io.vlReadPorts.map(x => VecInit(x.data)))
586  rename.io.int_need_free := rat.io.int_need_free
587  rename.io.int_old_pdest := rat.io.int_old_pdest
588  rename.io.fp_old_pdest := rat.io.fp_old_pdest
589  rename.io.vec_old_pdest := rat.io.vec_old_pdest
590  rename.io.v0_old_pdest := rat.io.v0_old_pdest
591  rename.io.vl_old_pdest := rat.io.vl_old_pdest
592  rename.io.debug_int_rat.foreach(_ := rat.io.debug_int_rat.get)
593  rename.io.debug_fp_rat.foreach(_ := rat.io.debug_fp_rat.get)
594  rename.io.debug_vec_rat.foreach(_ := rat.io.debug_vec_rat.get)
595  rename.io.debug_v0_rat.foreach(_ := rat.io.debug_v0_rat.get)
596  rename.io.debug_vl_rat.foreach(_ := rat.io.debug_vl_rat.get)
597  rename.io.stallReason.in <> decode.io.stallReason.out
598  rename.io.snpt.snptEnq := DontCare
599  rename.io.snpt.snptDeq := snpt.io.deq
600  rename.io.snpt.useSnpt := useSnpt
601  rename.io.snpt.snptSelect := snptSelect
602  rename.io.snptIsFull := snpt.io.valids.asUInt.andR
603  rename.io.snpt.flushVec := flushVecNext
604  rename.io.snptLastEnq.valid := !isEmpty(snpt.io.enqPtr, snpt.io.deqPtr)
605  rename.io.snptLastEnq.bits := snpt.io.snapshots((snpt.io.enqPtr - 1.U).value).robIdx.head
606
607  val renameOut = Wire(chiselTypeOf(rename.io.out))
608  renameOut <> rename.io.out
609  // pass all snapshot in the first element for correctness of blockBackward
610  renameOut.tail.foreach(_.bits.snapshot := false.B)
611  renameOut.head.bits.snapshot := Mux(isFull(snpt.io.enqPtr, snpt.io.deqPtr),
612    false.B,
613    Cat(rename.io.out.map(out => out.valid && out.bits.snapshot)).orR
614  )
615
616  // pipeline between rename and dispatch
617  PipeGroupConnect(renameOut, dispatch.io.fromRename, s1_s3_redirect.valid, dispatch.io.toRenameAllFire, "renamePipeDispatch")
618
619  dispatch.io.redirect := s1_s3_redirect
620  val enqRob = Wire(chiselTypeOf(rob.io.enq))
621  enqRob.canAccept := rob.io.enq.canAccept
622  enqRob.canAcceptForDispatch := rob.io.enq.canAcceptForDispatch
623  enqRob.isEmpty := rob.io.enq.isEmpty
624  enqRob.resp := rob.io.enq.resp
625  enqRob.needAlloc := RegNext(dispatch.io.enqRob.needAlloc)
626  enqRob.req.zip(dispatch.io.enqRob.req).map { case (sink, source) =>
627    sink.valid := RegNext(source.valid && !rob.io.redirect.valid)
628    sink.bits := RegEnable(source.bits, source.valid)
629  }
630  dispatch.io.enqRob.canAccept := enqRob.canAcceptForDispatch && !enqRob.req.map(x => x.valid && x.bits.blockBackward && enqRob.canAccept).reduce(_ || _)
631  dispatch.io.enqRob.canAcceptForDispatch := enqRob.canAcceptForDispatch
632  dispatch.io.enqRob.isEmpty := enqRob.isEmpty && !enqRob.req.map(_.valid).reduce(_ || _)
633  dispatch.io.enqRob.resp := enqRob.resp
634  rob.io.enq.needAlloc := enqRob.needAlloc
635  rob.io.enq.req := enqRob.req
636  dispatch.io.robHead := rob.io.debugRobHead
637  dispatch.io.stallReason <> rename.io.stallReason.out
638  dispatch.io.lqCanAccept := io.lqCanAccept
639  dispatch.io.sqCanAccept := io.sqCanAccept
640  dispatch.io.fromMem.lcommit := io.fromMemToDispatch.lcommit
641  dispatch.io.fromMem.scommit := io.fromMemToDispatch.scommit
642  dispatch.io.fromMem.lqDeqPtr := io.fromMemToDispatch.lqDeqPtr
643  dispatch.io.fromMem.sqDeqPtr := io.fromMemToDispatch.sqDeqPtr
644  dispatch.io.fromMem.lqCancelCnt := io.fromMemToDispatch.lqCancelCnt
645  dispatch.io.fromMem.sqCancelCnt := io.fromMemToDispatch.sqCancelCnt
646  io.toMem.lsqEnqIO <> dispatch.io.toMem.lsqEnqIO
647  dispatch.io.wakeUpAll.wakeUpInt := io.toDispatch.wakeUpInt
648  dispatch.io.wakeUpAll.wakeUpFp  := io.toDispatch.wakeUpFp
649  dispatch.io.wakeUpAll.wakeUpVec := io.toDispatch.wakeUpVec
650  dispatch.io.wakeUpAll.wakeUpMem := io.toDispatch.wakeUpMem
651  dispatch.io.IQValidNumVec := io.toDispatch.IQValidNumVec
652  dispatch.io.ldCancel := io.toDispatch.ldCancel
653  dispatch.io.og0Cancel := io.toDispatch.og0Cancel
654  dispatch.io.wbPregsInt := io.toDispatch.wbPregsInt
655  dispatch.io.wbPregsFp := io.toDispatch.wbPregsFp
656  dispatch.io.wbPregsVec := io.toDispatch.wbPregsVec
657  dispatch.io.wbPregsV0 := io.toDispatch.wbPregsV0
658  dispatch.io.wbPregsVl := io.toDispatch.wbPregsVl
659  dispatch.io.robHeadNotReady := rob.io.headNotReady
660  dispatch.io.robFull := rob.io.robFull
661  dispatch.io.singleStep := GatedValidRegNext(io.csrCtrl.singlestep)
662
663  val toIssueBlockUops = Seq(io.toIssueBlock.intUops, io.toIssueBlock.fpUops, io.toIssueBlock.vfUops, io.toIssueBlock.memUops).flatten
664  toIssueBlockUops.zip(dispatch.io.toIssueQueues).map(x => x._1 <> x._2)
665  io.toIssueBlock.flush   <> s2_s4_redirect
666
667  pcMem.io.wen.head   := GatedValidRegNext(io.frontend.fromFtq.pc_mem_wen)
668  pcMem.io.waddr.head := RegEnable(io.frontend.fromFtq.pc_mem_waddr, io.frontend.fromFtq.pc_mem_wen)
669  pcMem.io.wdata.head := RegEnable(io.frontend.fromFtq.pc_mem_wdata, io.frontend.fromFtq.pc_mem_wen)
670
671  io.toDataPath.flush := s2_s4_redirect
672  io.toExuBlock.flush := s2_s4_redirect
673
674
675  rob.io.hartId := io.fromTop.hartId
676  rob.io.redirect := s1_s3_redirect
677  rob.io.writeback := delayedNotFlushedWriteBack
678  rob.io.exuWriteback := delayedWriteBack
679  rob.io.writebackNums := VecInit(delayedNotFlushedWriteBackNums)
680  rob.io.writebackNeedFlush := delayedNotFlushedWriteBackNeedFlush
681  rob.io.readGPAMemData := gpaMem.io.exceptionReadData
682  rob.io.fromVecExcpMod.busy := io.fromVecExcpMod.busy
683
684  io.redirect := s1_s3_redirect
685
686  // rob to int block
687  io.robio.csr <> rob.io.csr
688  // When wfi is disabled, it will not block ROB commit.
689  rob.io.csr.wfiEvent := io.robio.csr.wfiEvent
690  rob.io.wfi_enable := decode.io.csrCtrl.wfi_enable
691
692  io.toTop.cpuHalt := DelayN(rob.io.cpu_halt, 5)
693
694  io.robio.csr.perfinfo.retiredInstr <> RegNext(rob.io.csr.perfinfo.retiredInstr)
695  io.robio.exception := rob.io.exception
696  io.robio.exception.bits.pc := s1_robFlushPc
697
698  // rob to mem block
699  io.robio.lsq <> rob.io.lsq
700
701  io.diff_int_rat.foreach(_ := rat.io.diff_int_rat.get)
702  io.diff_fp_rat .foreach(_ := rat.io.diff_fp_rat.get)
703  io.diff_vec_rat.foreach(_ := rat.io.diff_vec_rat.get)
704  io.diff_v0_rat .foreach(_ := rat.io.diff_v0_rat.get)
705  io.diff_vl_rat .foreach(_ := rat.io.diff_vl_rat.get)
706
707  rob.io.debug_ls := io.robio.debug_ls
708  rob.io.debugHeadLsIssue := io.robio.robHeadLsIssue
709  rob.io.lsTopdownInfo := io.robio.lsTopdownInfo
710  rob.io.csr.criticalErrorState := io.robio.csr.criticalErrorState
711  rob.io.debugEnqLsq := io.debugEnqLsq
712
713  io.robio.robDeqPtr := rob.io.robDeqPtr
714
715  io.robio.storeDebugInfo <> rob.io.storeDebugInfo
716
717  // rob to backend
718  io.robio.commitVType := rob.io.toDecode.commitVType
719  // exu block to decode
720  decode.io.vsetvlVType := io.toDecode.vsetvlVType
721  // backend to decode
722  decode.io.vstart := io.toDecode.vstart
723  // backend to rob
724  rob.io.vstartIsZero := io.toDecode.vstart === 0.U
725
726  io.toCSR.trapInstInfo := decode.io.toCSR.trapInstInfo
727
728  io.toVecExcpMod.logicPhyRegMap := rob.io.toVecExcpMod.logicPhyRegMap
729  io.toVecExcpMod.excpInfo       := rob.io.toVecExcpMod.excpInfo
730  // T  : rat receive rabCommit
731  // T+1: rat return oldPdest
732  io.toVecExcpMod.ratOldPest match {
733    case fromRat =>
734      (0 until RabCommitWidth).foreach { idx =>
735        fromRat.v0OldVdPdest(idx).valid := RegNext(
736          rat.io.rabCommits.isCommit &&
737          rat.io.rabCommits.isWalk &&
738          rat.io.rabCommits.commitValid(idx) &&
739          rat.io.rabCommits.info(idx).v0Wen
740        )
741        fromRat.v0OldVdPdest(idx).bits := rat.io.v0_old_pdest(idx)
742        fromRat.vecOldVdPdest(idx).valid := RegNext(
743          rat.io.rabCommits.isCommit &&
744          rat.io.rabCommits.isWalk &&
745          rat.io.rabCommits.commitValid(idx) &&
746          rat.io.rabCommits.info(idx).vecWen
747        )
748        fromRat.vecOldVdPdest(idx).bits := rat.io.vec_old_pdest(idx)
749      }
750  }
751
752  io.debugTopDown.fromRob := rob.io.debugTopDown.toCore
753  dispatch.io.debugTopDown.fromRob := rob.io.debugTopDown.toDispatch
754  dispatch.io.debugTopDown.fromCore := io.debugTopDown.fromCore
755  io.debugRolling := rob.io.debugRolling
756
757  io.perfInfo.ctrlInfo.robFull := GatedValidRegNext(rob.io.robFull)
758  io.perfInfo.ctrlInfo.intdqFull := false.B
759  io.perfInfo.ctrlInfo.fpdqFull := false.B
760  io.perfInfo.ctrlInfo.lsdqFull := false.B
761
762  val perfEvents = Seq(decode, rename, dispatch, rob).flatMap(_.getPerfEvents)
763  generatePerfEvent()
764
765  val criticalErrors = rob.getCriticalErrors
766  generateCriticalErrors()
767}
768
769class CtrlBlockIO()(implicit p: Parameters, params: BackendParams) extends XSBundle {
770  val fromTop = new Bundle {
771    val hartId = Input(UInt(8.W))
772  }
773  val toTop = new Bundle {
774    val cpuHalt = Output(Bool())
775  }
776  val frontend = Flipped(new FrontendToCtrlIO())
777  val fromCSR = new Bundle{
778    val toDecode = Input(new CSRToDecode)
779    val traceCSR = Input(new TraceCSR)
780    val instrAddrTransType = Input(new AddrTransType)
781  }
782  val toIssueBlock = new Bundle {
783    val flush = ValidIO(new Redirect)
784    val intUopsNum = backendParams.intSchdParams.get.issueBlockParams.map(_.numEnq).sum
785    val fpUopsNum = backendParams.fpSchdParams.get.issueBlockParams.map(_.numEnq).sum
786    val vfUopsNum = backendParams.vfSchdParams.get.issueBlockParams.map(_.numEnq).sum
787    val memUopsNum = backendParams.memSchdParams.get.issueBlockParams.filter(x => x.StdCnt == 0).map(_.numEnq).sum
788    val intUops = Vec(intUopsNum, DecoupledIO(new DynInst))
789    val fpUops = Vec(fpUopsNum, DecoupledIO(new DynInst))
790    val vfUops = Vec(vfUopsNum, DecoupledIO(new DynInst))
791    val memUops = Vec(memUopsNum, DecoupledIO(new DynInst))
792  }
793  val fromMemToDispatch = new Bundle {
794    val lcommit = Input(UInt(log2Up(CommitWidth + 1).W))
795    val scommit = Input(UInt(log2Ceil(EnsbufferWidth + 1).W)) // connected to `memBlock.io.sqDeq` instead of ROB
796    val lqDeqPtr = Input(new LqPtr)
797    val sqDeqPtr = Input(new SqPtr)
798    // from lsq
799    val lqCancelCnt = Input(UInt(log2Up(VirtualLoadQueueSize + 1).W))
800    val sqCancelCnt = Input(UInt(log2Up(StoreQueueSize + 1).W))
801  }
802  //toMem
803  val toMem = new Bundle {
804    val lsqEnqIO = Flipped(new LsqEnqIO)
805  }
806  val toDispatch = new Bundle {
807    val wakeUpInt = Flipped(backendParams.intSchdParams.get.genIQWakeUpOutValidBundle)
808    val wakeUpFp  = Flipped(backendParams.fpSchdParams.get.genIQWakeUpOutValidBundle)
809    val wakeUpVec = Flipped(backendParams.vfSchdParams.get.genIQWakeUpOutValidBundle)
810    val wakeUpMem = Flipped(backendParams.memSchdParams.get.genIQWakeUpOutValidBundle)
811    val allIssueParams = backendParams.allIssueParams.filter(_.StdCnt == 0)
812    val allExuParams = allIssueParams.map(_.exuBlockParams).flatten
813    val exuNum = allExuParams.size
814    val maxIQSize = allIssueParams.map(_.numEntries).max
815    val IQValidNumVec = Vec(exuNum, Input(UInt(maxIQSize.U.getWidth.W)))
816    val og0Cancel = Input(ExuVec())
817    val ldCancel = Vec(backendParams.LdExuCnt, Flipped(new LoadCancelIO))
818    val wbPregsInt = Vec(backendParams.numPregWb(IntData()), Flipped(ValidIO(UInt(PhyRegIdxWidth.W))))
819    val wbPregsFp = Vec(backendParams.numPregWb(FpData()), Flipped(ValidIO(UInt(PhyRegIdxWidth.W))))
820    val wbPregsVec = Vec(backendParams.numPregWb(VecData()), Flipped(ValidIO(UInt(PhyRegIdxWidth.W))))
821    val wbPregsV0 = Vec(backendParams.numPregWb(V0Data()), Flipped(ValidIO(UInt(PhyRegIdxWidth.W))))
822    val wbPregsVl = Vec(backendParams.numPregWb(VlData()), Flipped(ValidIO(UInt(PhyRegIdxWidth.W))))
823  }
824  val toDataPath = new Bundle {
825    val flush = ValidIO(new Redirect)
826    val pcToDataPathIO = new PcToDataPathIO(params)
827  }
828  val toExuBlock = new Bundle {
829    val flush = ValidIO(new Redirect)
830  }
831  val toCSR = new Bundle {
832    val trapInstInfo = Output(ValidIO(new TrapInstInfo))
833  }
834  val fromWB = new Bundle {
835    val wbData = Flipped(MixedVec(params.genWrite2CtrlBundles))
836  }
837  val redirect = ValidIO(new Redirect)
838  val fromMem = new Bundle {
839    val stIn = Vec(params.StaExuCnt, Flipped(ValidIO(new DynInst))) // use storeSetHit, ssid, robIdx
840    val violation = Flipped(ValidIO(new Redirect))
841  }
842  val memStPcRead = Vec(params.StaCnt, Flipped(new FtqRead(UInt(VAddrBits.W))))
843  val memHyPcRead = Vec(params.HyuCnt, Flipped(new FtqRead(UInt(VAddrBits.W))))
844
845  val csrCtrl = Input(new CustomCSRCtrlIO)
846  val robio = new Bundle {
847    val csr = new RobCSRIO
848    val exception = ValidIO(new ExceptionInfo)
849    val lsq = new RobLsqIO
850    val lsTopdownInfo = Vec(params.LduCnt + params.HyuCnt, Input(new LsTopdownInfo))
851    val debug_ls = Input(new DebugLSIO())
852    val robHeadLsIssue = Input(Bool())
853    val robDeqPtr = Output(new RobPtr)
854    val commitVType = new Bundle {
855      val vtype = Output(ValidIO(VType()))
856      val hasVsetvl = Output(Bool())
857    }
858
859    // store event difftest information
860    val storeDebugInfo = Vec(EnsbufferWidth, new Bundle {
861      val robidx = Input(new RobPtr)
862      val pc     = Output(UInt(VAddrBits.W))
863    })
864  }
865
866  val toDecode = new Bundle {
867    val vsetvlVType = Input(VType())
868    val vstart = Input(Vl())
869  }
870
871  val fromVecExcpMod = Input(new Bundle {
872    val busy = Bool()
873  })
874
875  val toVecExcpMod = Output(new Bundle {
876    val logicPhyRegMap = Vec(RabCommitWidth, ValidIO(new RegWriteFromRab))
877    val excpInfo = ValidIO(new VecExcpInfo)
878    val ratOldPest = new RatToVecExcpMod
879  })
880
881  val traceCoreInterface = new TraceCoreInterface(hasOffset = true)
882
883  val perfInfo = Output(new Bundle{
884    val ctrlInfo = new Bundle {
885      val robFull   = Bool()
886      val intdqFull = Bool()
887      val fpdqFull  = Bool()
888      val lsdqFull  = Bool()
889    }
890  })
891  val diff_int_rat = if (params.basicDebugEn) Some(Vec(32, Output(UInt(PhyRegIdxWidth.W)))) else None
892  val diff_fp_rat  = if (params.basicDebugEn) Some(Vec(32, Output(UInt(PhyRegIdxWidth.W)))) else None
893  val diff_vec_rat = if (params.basicDebugEn) Some(Vec(31, Output(UInt(PhyRegIdxWidth.W)))) else None
894  val diff_v0_rat  = if (params.basicDebugEn) Some(Vec(1, Output(UInt(PhyRegIdxWidth.W)))) else None
895  val diff_vl_rat  = if (params.basicDebugEn) Some(Vec(1, Output(UInt(PhyRegIdxWidth.W)))) else None
896
897  val sqCanAccept = Input(Bool())
898  val lqCanAccept = Input(Bool())
899
900  val debugTopDown = new Bundle {
901    val fromRob = new RobCoreTopDownIO
902    val fromCore = new CoreDispatchTopDownIO
903  }
904  val debugRolling = new RobDebugRollingIO
905  val debugEnqLsq = Input(new LsqEnqIO)
906}
907
908class NamedIndexes(namedCnt: Seq[(String, Int)]) {
909  require(namedCnt.map(_._1).distinct.size == namedCnt.size, "namedCnt should not have the same name")
910
911  val maxIdx = namedCnt.map(_._2).sum
912  val nameRangeMap: Map[String, (Int, Int)] = namedCnt.indices.map { i =>
913    val begin = namedCnt.slice(0, i).map(_._2).sum
914    val end = begin + namedCnt(i)._2
915    (namedCnt(i)._1, (begin, end))
916  }.toMap
917
918  def apply(name: String): Seq[Int] = {
919    require(nameRangeMap.contains(name))
920    nameRangeMap(name)._1 until nameRangeMap(name)._2
921  }
922}
923