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