xref: /XiangShan/src/main/scala/xiangshan/backend/CtrlBlock.scala (revision fd7603d9dcacd32d717add69961a1f448e49757c)
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 difftest._
23import freechips.rocketchip.diplomacy.{LazyModule, LazyModuleImp}
24import utils._
25import xiangshan._
26import xiangshan.backend.decode.{DecodeStage, ImmUnion}
27import xiangshan.backend.dispatch.{Dispatch, DispatchQueue}
28import xiangshan.backend.fu.PFEvent
29import xiangshan.backend.rename.{Rename, RenameTableWrapper}
30import xiangshan.backend.rob.{Rob, RobCSRIO, RobLsqIO}
31import xiangshan.frontend.FtqRead
32import xiangshan.mem.mdp.{LFST, SSIT, WaitTable}
33
34class CtrlToFtqIO(implicit p: Parameters) extends XSBundle {
35  val rob_commits = Vec(CommitWidth, Valid(new RobCommitInfo))
36  val stage2Redirect = Valid(new Redirect)
37}
38
39class RedirectGenerator(implicit p: Parameters) extends XSModule
40  with HasCircularQueuePtrHelper {
41  val numRedirect = exuParameters.JmpCnt + exuParameters.AluCnt
42  val io = IO(new Bundle() {
43    val hartId = Input(UInt(8.W))
44    val exuMispredict = Vec(numRedirect, Flipped(ValidIO(new ExuOutput)))
45    val loadReplay = Flipped(ValidIO(new Redirect))
46    val flush = Input(Bool())
47    val stage1PcRead = Vec(numRedirect+1, new FtqRead(UInt(VAddrBits.W)))
48    val stage2Redirect = ValidIO(new Redirect)
49    val stage3Redirect = ValidIO(new Redirect)
50    val memPredUpdate = Output(new MemPredUpdateReq)
51    val memPredPcRead = new FtqRead(UInt(VAddrBits.W)) // read req send form stage 2
52  })
53  /*
54        LoadQueue  Jump  ALU0  ALU1  ALU2  ALU3   exception    Stage1
55          |         |      |    |     |     |         |
56          |============= reg & compare =====|         |       ========
57                            |                         |
58                            |                         |
59                            |                         |        Stage2
60                            |                         |
61                    redirect (flush backend)          |
62                    |                                 |
63               === reg ===                            |       ========
64                    |                                 |
65                    |----- mux (exception first) -----|        Stage3
66                            |
67                redirect (send to frontend)
68   */
69  private class Wrapper(val n: Int) extends Bundle {
70    val redirect = new Redirect
71    val valid = Bool()
72    val idx = UInt(log2Up(n).W)
73  }
74  def selectOldestRedirect(xs: Seq[Valid[Redirect]]): Vec[Bool] = {
75    val compareVec = (0 until xs.length).map(i => (0 until i).map(j => isAfter(xs(j).bits.robIdx, xs(i).bits.robIdx)))
76    val resultOnehot = VecInit((0 until xs.length).map(i => Cat((0 until xs.length).map(j =>
77      (if (j < i) !xs(j).valid || compareVec(i)(j)
78      else if (j == i) xs(i).valid
79      else !xs(j).valid || !compareVec(j)(i))
80    )).andR))
81    resultOnehot
82  }
83
84  val redirects = io.exuMispredict.map(_.bits.redirect) :+ io.loadReplay.bits
85  val stage1FtqReadPcs =
86    (io.stage1PcRead zip redirects).map{ case (r, redirect) =>
87      r(redirect.ftqIdx, redirect.ftqOffset)
88    }
89
90  def getRedirect(exuOut: Valid[ExuOutput]): ValidIO[Redirect] = {
91    val redirect = Wire(Valid(new Redirect))
92    redirect.valid := exuOut.valid && exuOut.bits.redirect.cfiUpdate.isMisPred
93    redirect.bits := exuOut.bits.redirect
94    redirect
95  }
96
97  val jumpOut = io.exuMispredict.head
98  val allRedirect = VecInit(io.exuMispredict.map(x => getRedirect(x)) :+ io.loadReplay)
99  val oldestOneHot = selectOldestRedirect(allRedirect)
100  val needFlushVec = VecInit(allRedirect.map(_.bits.robIdx.needFlush(io.stage2Redirect) || io.flush))
101  val oldestValid = VecInit(oldestOneHot.zip(needFlushVec).map{ case (v, f) => v && !f }).asUInt.orR
102  val oldestExuOutput = Mux1H(io.exuMispredict.indices.map(oldestOneHot), io.exuMispredict)
103  val oldestRedirect = Mux1H(oldestOneHot, allRedirect)
104
105  val s1_jumpTarget = RegEnable(jumpOut.bits.redirect.cfiUpdate.target, jumpOut.valid)
106  val s1_imm12_reg = RegNext(oldestExuOutput.bits.uop.ctrl.imm(11, 0))
107  val s1_pd = RegNext(oldestExuOutput.bits.uop.cf.pd)
108  val s1_redirect_bits_reg = RegNext(oldestRedirect.bits)
109  val s1_redirect_valid_reg = RegNext(oldestValid)
110  val s1_redirect_onehot = RegNext(oldestOneHot)
111
112  // stage1 -> stage2
113  io.stage2Redirect.valid := s1_redirect_valid_reg && !io.flush
114  io.stage2Redirect.bits := s1_redirect_bits_reg
115
116  val s1_isReplay = s1_redirect_onehot.last
117  val s1_isJump = s1_redirect_onehot.head
118  val real_pc = Mux1H(s1_redirect_onehot, stage1FtqReadPcs)
119  val brTarget = real_pc + SignExt(ImmUnion.B.toImm32(s1_imm12_reg), XLEN)
120  val snpc = real_pc + Mux(s1_pd.isRVC, 2.U, 4.U)
121  val target = Mux(s1_isReplay,
122    real_pc, // replay from itself
123    Mux(s1_redirect_bits_reg.cfiUpdate.taken,
124      Mux(s1_isJump, s1_jumpTarget, brTarget),
125      snpc
126    )
127  )
128
129  val stage2CfiUpdate = io.stage2Redirect.bits.cfiUpdate
130  stage2CfiUpdate.pc := real_pc
131  stage2CfiUpdate.pd := s1_pd
132  stage2CfiUpdate.predTaken := s1_redirect_bits_reg.cfiUpdate.predTaken
133  stage2CfiUpdate.target := target
134  stage2CfiUpdate.taken := s1_redirect_bits_reg.cfiUpdate.taken
135  stage2CfiUpdate.isMisPred := s1_redirect_bits_reg.cfiUpdate.isMisPred
136
137  val s2_target = RegEnable(target, enable = s1_redirect_valid_reg)
138  val s2_pc = RegEnable(real_pc, enable = s1_redirect_valid_reg)
139  val s2_redirect_bits_reg = RegEnable(s1_redirect_bits_reg, enable = s1_redirect_valid_reg)
140  val s2_redirect_valid_reg = RegNext(s1_redirect_valid_reg && !io.flush, init = false.B)
141
142  io.stage3Redirect.valid := s2_redirect_valid_reg
143  io.stage3Redirect.bits := s2_redirect_bits_reg
144
145  // get pc from ftq
146  // valid only if redirect is caused by load violation
147  // store_pc is used to update store set
148  val store_pc = io.memPredPcRead(s1_redirect_bits_reg.stFtqIdx, s1_redirect_bits_reg.stFtqOffset)
149
150  // update load violation predictor if load violation redirect triggered
151  io.memPredUpdate.valid := RegNext(s1_isReplay && s1_redirect_valid_reg, init = false.B)
152  // update wait table
153  io.memPredUpdate.waddr := RegNext(XORFold(real_pc(VAddrBits-1, 1), MemPredPCWidth))
154  io.memPredUpdate.wdata := true.B
155  // update store set
156  io.memPredUpdate.ldpc := RegNext(XORFold(real_pc(VAddrBits-1, 1), MemPredPCWidth))
157  // store pc is ready 1 cycle after s1_isReplay is judged
158  io.memPredUpdate.stpc := XORFold(store_pc(VAddrBits-1, 1), MemPredPCWidth)
159
160  // recover runahead checkpoint if redirect
161  if (!env.FPGAPlatform) {
162    val runahead_redirect = Module(new DifftestRunaheadRedirectEvent)
163    runahead_redirect.io.clock := clock
164    runahead_redirect.io.coreid := io.hartId
165    runahead_redirect.io.valid := io.stage3Redirect.valid
166    runahead_redirect.io.pc :=  s2_pc // for debug only
167    runahead_redirect.io.target_pc := s2_target // for debug only
168    runahead_redirect.io.checkpoint_id := io.stage3Redirect.bits.debug_runahead_checkpoint_id // make sure it is right
169  }
170}
171
172class CtrlBlock(implicit p: Parameters) extends LazyModule
173  with HasWritebackSink with HasWritebackSource {
174  val rob = LazyModule(new Rob)
175
176  override def addWritebackSink(source: Seq[HasWritebackSource], index: Option[Seq[Int]]): HasWritebackSink = {
177    rob.addWritebackSink(Seq(this), Some(Seq(writebackSinks.length)))
178    super.addWritebackSink(source, index)
179  }
180
181  lazy val module = new CtrlBlockImp(this)
182
183  override lazy val writebackSourceParams: Seq[WritebackSourceParams] = {
184    writebackSinksParams
185  }
186  override lazy val writebackSourceImp: HasWritebackSourceImp = module
187
188  override def generateWritebackIO(
189    thisMod: Option[HasWritebackSource] = None,
190    thisModImp: Option[HasWritebackSourceImp] = None
191  ): Unit = {
192    module.io.writeback.zip(writebackSinksImp(thisMod, thisModImp)).foreach(x => x._1 := x._2)
193  }
194}
195
196class CtrlBlockImp(outer: CtrlBlock)(implicit p: Parameters) extends LazyModuleImp(outer)
197  with HasXSParameter
198  with HasCircularQueuePtrHelper
199  with HasWritebackSourceImp
200  with HasPerfEvents
201{
202  val writebackLengths = outer.writebackSinksParams.map(_.length)
203
204  val io = IO(new Bundle {
205    val hartId = Input(UInt(8.W))
206    val frontend = Flipped(new FrontendToCtrlIO)
207    val allocPregs = Vec(RenameWidth, Output(new ResetPregStateReq))
208    val dispatch = Vec(3*dpParams.IntDqDeqWidth, DecoupledIO(new MicroOp))
209    // from int block
210    val exuRedirect = Vec(exuParameters.AluCnt + exuParameters.JmpCnt, Flipped(ValidIO(new ExuOutput)))
211    val stIn = Vec(exuParameters.StuCnt, Flipped(ValidIO(new ExuInput)))
212    val memoryViolation = Flipped(ValidIO(new Redirect))
213    val jumpPc = Output(UInt(VAddrBits.W))
214    val jalr_target = Output(UInt(VAddrBits.W))
215    val robio = new Bundle {
216      // to int block
217      val toCSR = new RobCSRIO
218      val exception = ValidIO(new ExceptionInfo)
219      // to mem block
220      val lsq = new RobLsqIO
221    }
222    val csrCtrl = Input(new CustomCSRCtrlIO)
223    val perfInfo = Output(new Bundle{
224      val ctrlInfo = new Bundle {
225        val robFull   = Input(Bool())
226        val intdqFull = Input(Bool())
227        val fpdqFull  = Input(Bool())
228        val lsdqFull  = Input(Bool())
229      }
230    })
231    val writeback = MixedVec(writebackLengths.map(num => Vec(num, Flipped(ValidIO(new ExuOutput)))))
232    // redirect out
233    val redirect = ValidIO(new Redirect)
234    val debug_int_rat = Vec(32, Output(UInt(PhyRegIdxWidth.W)))
235    val debug_fp_rat = Vec(32, Output(UInt(PhyRegIdxWidth.W)))
236  })
237
238  override def writebackSource: Option[Seq[Seq[Valid[ExuOutput]]]] = {
239    Some(io.writeback.map(writeback => {
240      val exuOutput = WireInit(writeback)
241      val timer = GTimer()
242      for ((wb_next, wb) <- exuOutput.zip(writeback)) {
243        wb_next.valid := RegNext(wb.valid && !wb.bits.uop.robIdx.needFlush(stage2Redirect))
244        wb_next.bits := RegNext(wb.bits)
245        wb_next.bits.uop.debugInfo.writebackTime := timer
246      }
247      exuOutput
248    }))
249  }
250
251  val decode = Module(new DecodeStage)
252  val rat = Module(new RenameTableWrapper)
253  val ssit = Module(new SSIT)
254  val waittable = Module(new WaitTable)
255  val rename = Module(new Rename)
256  val dispatch = Module(new Dispatch)
257  val intDq = Module(new DispatchQueue(dpParams.IntDqSize, RenameWidth, dpParams.IntDqDeqWidth))
258  val fpDq = Module(new DispatchQueue(dpParams.FpDqSize, RenameWidth, dpParams.FpDqDeqWidth))
259  val lsDq = Module(new DispatchQueue(dpParams.LsDqSize, RenameWidth, dpParams.LsDqDeqWidth))
260  val redirectGen = Module(new RedirectGenerator)
261
262  val rob = outer.rob.module
263
264  val robPcRead = io.frontend.fromFtq.getRobFlushPcRead
265  val flushPC = robPcRead(rob.io.flushOut.bits.ftqIdx, rob.io.flushOut.bits.ftqOffset)
266
267  val flushRedirect = Wire(Valid(new Redirect))
268  flushRedirect.valid := RegNext(rob.io.flushOut.valid)
269  flushRedirect.bits := RegEnable(rob.io.flushOut.bits, rob.io.flushOut.valid)
270  flushRedirect.bits.cfiUpdate.target := Mux(io.robio.toCSR.isXRet || rob.io.exception.valid,
271    io.robio.toCSR.trapTarget,
272    Mux(flushRedirect.bits.flushItself(),
273      flushPC, // replay inst
274      flushPC + 4.U // flush pipe
275    )
276  )
277
278  val flushRedirectReg = Wire(Valid(new Redirect))
279  flushRedirectReg.valid := RegNext(flushRedirect.valid, init = false.B)
280  flushRedirectReg.bits := RegEnable(flushRedirect.bits, enable = flushRedirect.valid)
281
282  val stage2Redirect = Mux(flushRedirect.valid, flushRedirect, redirectGen.io.stage2Redirect)
283  val stage3Redirect = Mux(flushRedirectReg.valid, flushRedirectReg, redirectGen.io.stage3Redirect)
284
285  val exuRedirect = io.exuRedirect.map(x => {
286    val valid = x.valid && x.bits.redirectValid
287    val killedByOlder = x.bits.uop.robIdx.needFlush(stage2Redirect)
288    val delayed = Wire(Valid(new ExuOutput))
289    delayed.valid := RegNext(valid && !killedByOlder, init = false.B)
290    delayed.bits := RegEnable(x.bits, x.valid)
291    delayed
292  })
293  val loadReplay = Wire(Valid(new Redirect))
294  loadReplay.valid := RegNext(io.memoryViolation.valid &&
295    !io.memoryViolation.bits.robIdx.needFlush(stage2Redirect),
296    init = false.B
297  )
298  loadReplay.bits := RegEnable(io.memoryViolation.bits, io.memoryViolation.valid)
299  io.frontend.fromFtq.getRedirectPcRead <> redirectGen.io.stage1PcRead
300  io.frontend.fromFtq.getMemPredPcRead <> redirectGen.io.memPredPcRead
301  redirectGen.io.hartId := io.hartId
302  redirectGen.io.exuMispredict <> exuRedirect
303  redirectGen.io.loadReplay <> loadReplay
304  redirectGen.io.flush := flushRedirect.valid
305
306  val frontendFlush = DelayN(flushRedirect, 5)
307  val frontendStage2Redirect = Mux(frontendFlush.valid, frontendFlush, redirectGen.io.stage2Redirect)
308  for (i <- 0 until CommitWidth) {
309    io.frontend.toFtq.rob_commits(i).valid := RegNext(rob.io.commits.valid(i) && !rob.io.commits.isWalk)
310    io.frontend.toFtq.rob_commits(i).bits := RegNext(rob.io.commits.info(i))
311  }
312  io.frontend.toFtq.stage2Redirect := frontendStage2Redirect
313  val pendingRedirect = RegInit(false.B)
314  when (stage2Redirect.valid) {
315    pendingRedirect := true.B
316  }.elsewhen (RegNext(io.frontend.toFtq.stage2Redirect.valid)) {
317    pendingRedirect := false.B
318  }
319
320  decode.io.in <> io.frontend.cfVec
321  decode.io.csrCtrl := RegNext(io.csrCtrl)
322
323  // memory dependency predict
324  // when decode, send fold pc to mdp
325  for (i <- 0 until DecodeWidth) {
326    val mdp_foldpc = Mux(
327      decode.io.out(i).fire(),
328      decode.io.in(i).bits.foldpc,
329      rename.io.in(i).bits.cf.foldpc
330    )
331    ssit.io.raddr(i) := mdp_foldpc
332    waittable.io.raddr(i) := mdp_foldpc
333  }
334  // currently, we only update mdp info when isReplay
335  ssit.io.update <> RegNext(redirectGen.io.memPredUpdate)
336  ssit.io.csrCtrl := RegNext(io.csrCtrl)
337  waittable.io.update <> RegNext(redirectGen.io.memPredUpdate)
338  waittable.io.csrCtrl := RegNext(io.csrCtrl)
339
340  // LFST lookup and update
341  val lfst = Module(new LFST)
342  lfst.io.redirect <> RegNext(io.redirect)
343  lfst.io.storeIssue <> RegNext(io.stIn)
344  lfst.io.csrCtrl <> RegNext(io.csrCtrl)
345  lfst.io.dispatch <> dispatch.io.lfst
346
347  rat.io.robCommits := rob.io.commits
348  for ((r, i) <- rat.io.intReadPorts.zipWithIndex) {
349    val raddr = decode.io.out(i).bits.ctrl.lsrc.take(2) :+ decode.io.out(i).bits.ctrl.ldest
350    r.map(_.addr).zip(raddr).foreach(x => x._1 := x._2)
351    rename.io.intReadPorts(i) := r.map(_.data)
352    r.foreach(_.hold := !rename.io.in(i).ready)
353  }
354  rat.io.intRenamePorts := rename.io.intRenamePorts
355  for ((r, i) <- rat.io.fpReadPorts.zipWithIndex) {
356    val raddr = decode.io.out(i).bits.ctrl.lsrc.take(3) :+ decode.io.out(i).bits.ctrl.ldest
357    r.map(_.addr).zip(raddr).foreach(x => x._1 := x._2)
358    rename.io.fpReadPorts(i) := r.map(_.data)
359    r.foreach(_.hold := !rename.io.in(i).ready)
360  }
361  rat.io.fpRenamePorts := rename.io.fpRenamePorts
362  rat.io.debug_int_rat <> io.debug_int_rat
363  rat.io.debug_fp_rat <> io.debug_fp_rat
364
365  // pipeline between decode and rename
366  for (i <- 0 until RenameWidth) {
367    PipelineConnect(decode.io.out(i), rename.io.in(i), rename.io.in(i).ready,
368      stage2Redirect.valid || pendingRedirect)
369  }
370
371  rename.io.redirect <> stage2Redirect
372  rename.io.robCommits <> rob.io.commits
373  rename.io.ssit <> ssit.io.rdata
374  rename.io.waittable <> RegNext(waittable.io.rdata)
375
376  // pipeline between rename and dispatch
377  for (i <- 0 until RenameWidth) {
378    PipelineConnect(rename.io.out(i), dispatch.io.fromRename(i), dispatch.io.recv(i), stage2Redirect.valid)
379  }
380
381  dispatch.io.hartId := io.hartId
382  dispatch.io.redirect <> stage2Redirect
383  dispatch.io.enqRob <> rob.io.enq
384  dispatch.io.toIntDq <> intDq.io.enq
385  dispatch.io.toFpDq <> fpDq.io.enq
386  dispatch.io.toLsDq <> lsDq.io.enq
387  dispatch.io.allocPregs <> io.allocPregs
388  dispatch.io.singleStep := false.B
389
390  intDq.io.redirect <> stage2Redirect
391  fpDq.io.redirect <> stage2Redirect
392  lsDq.io.redirect <> stage2Redirect
393
394  io.dispatch <> intDq.io.deq ++ lsDq.io.deq ++ fpDq.io.deq
395
396  val pingpong = RegInit(false.B)
397  pingpong := !pingpong
398  val jumpInst = Mux(pingpong && (exuParameters.AluCnt > 2).B, io.dispatch(2).bits, io.dispatch(0).bits)
399  val jumpPcRead = io.frontend.fromFtq.getJumpPcRead
400  io.jumpPc := jumpPcRead(jumpInst.cf.ftqPtr, jumpInst.cf.ftqOffset)
401  val jumpTargetRead = io.frontend.fromFtq.target_read
402  io.jalr_target := jumpTargetRead(jumpInst.cf.ftqPtr, jumpInst.cf.ftqOffset)
403
404  rob.io.hartId := io.hartId
405  rob.io.redirect <> stage2Redirect
406  outer.rob.generateWritebackIO(Some(outer), Some(this))
407
408  io.redirect <> stage2Redirect
409
410  // rob to int block
411  io.robio.toCSR <> rob.io.csr
412  io.robio.toCSR.perfinfo.retiredInstr <> RegNext(rob.io.csr.perfinfo.retiredInstr)
413  io.robio.exception := rob.io.exception
414  io.robio.exception.bits.uop.cf.pc := flushPC
415
416  // rob to mem block
417  io.robio.lsq <> rob.io.lsq
418
419  io.perfInfo.ctrlInfo.robFull := RegNext(rob.io.robFull)
420  io.perfInfo.ctrlInfo.intdqFull := RegNext(intDq.io.dqFull)
421  io.perfInfo.ctrlInfo.fpdqFull := RegNext(fpDq.io.dqFull)
422  io.perfInfo.ctrlInfo.lsdqFull := RegNext(lsDq.io.dqFull)
423
424  val pfevent = Module(new PFEvent)
425  pfevent.io.distribute_csr := RegNext(io.csrCtrl.distribute_csr)
426  val csrevents = pfevent.io.hpmevent.slice(8,16)
427
428  val perfinfo = IO(new Bundle(){
429    val perfEventsRs      = Input(Vec(NumRs, new PerfEvent))
430    val perfEventsEu0     = Input(Vec(6, new PerfEvent))
431    val perfEventsEu1     = Input(Vec(6, new PerfEvent))
432  })
433
434  val allPerfEvents = Seq(decode, rename, dispatch, intDq, fpDq, lsDq, rob).flatMap(_.getPerf)
435  val hpmEvents = allPerfEvents ++ perfinfo.perfEventsEu0 ++ perfinfo.perfEventsEu1 ++ perfinfo.perfEventsRs
436  val perfEvents = HPerfMonitor(csrevents, hpmEvents).getPerfEvents
437  generatePerfEvent()
438}
439