xref: /XiangShan/src/main/scala/xiangshan/backend/CtrlBlock.scala (revision e0d9a9f061877f2c083a9363bc4b3e8254998aa0)
1/***************************************************************************************
2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3*
4* XiangShan is licensed under Mulan PSL v2.
5* You can use this software according to the terms and conditions of the Mulan PSL v2.
6* You may obtain a copy of Mulan PSL v2 at:
7*          http://license.coscl.org.cn/MulanPSL2
8*
9* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
10* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
11* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
12*
13* See the Mulan PSL v2 for more details.
14***************************************************************************************/
15
16package xiangshan.backend
17
18import chipsalliance.rocketchip.config.Parameters
19import chisel3._
20import chisel3.util._
21import utils._
22import xiangshan._
23import xiangshan.backend.decode.{DecodeStage, ImmUnion}
24import xiangshan.backend.rename.{BusyTable, Rename}
25import xiangshan.backend.dispatch.Dispatch
26import xiangshan.backend.exu._
27import xiangshan.frontend.{FtqRead, HasFtqHelper}
28import xiangshan.backend.roq.{Roq, RoqCSRIO, RoqLsqIO, RoqPtr}
29import xiangshan.mem.LsqEnqIO
30
31class CtrlToIntBlockIO(implicit p: Parameters) extends XSBundle {
32  val enqIqCtrl = Vec(exuParameters.IntExuCnt, DecoupledIO(new MicroOp))
33  val readRf = Vec(NRIntReadPorts, Output(UInt(PhyRegIdxWidth.W)))
34  val jumpPc = Output(UInt(VAddrBits.W))
35  val jalr_target = Output(UInt(VAddrBits.W))
36  // int block only uses port 0~7
37  val readPortIndex = Vec(exuParameters.IntExuCnt, Output(UInt(log2Ceil(8 / 2).W))) // TODO parameterize 8 here
38  val redirect = ValidIO(new Redirect)
39  val flush = Output(Bool())
40  val debug_rat = Vec(32, Output(UInt(PhyRegIdxWidth.W)))
41}
42
43class CtrlToFpBlockIO(implicit p: Parameters) extends XSBundle {
44  val enqIqCtrl = Vec(exuParameters.FpExuCnt, DecoupledIO(new MicroOp))
45  val readRf = Vec(NRFpReadPorts, Output(UInt(PhyRegIdxWidth.W)))
46  // fp block uses port 0~11
47  val readPortIndex = Vec(exuParameters.FpExuCnt, Output(UInt(log2Ceil((NRFpReadPorts - exuParameters.StuCnt) / 3).W)))
48  val redirect = ValidIO(new Redirect)
49  val flush = Output(Bool())
50  val debug_rat = Vec(32, Output(UInt(PhyRegIdxWidth.W)))
51}
52
53class CtrlToLsBlockIO(implicit p: Parameters) extends XSBundle {
54  val enqIqCtrl = Vec(exuParameters.LsExuCnt, DecoupledIO(new MicroOp))
55  val enqLsq = Flipped(new LsqEnqIO)
56  val memPredUpdate = Vec(StorePipelineWidth, Input(new MemPredUpdateReq))
57  val redirect = ValidIO(new Redirect)
58  val flush = Output(Bool())
59}
60
61class RedirectGenerator(implicit p: Parameters) extends XSModule
62  with HasCircularQueuePtrHelper with HasFtqHelper {
63  val numRedirect = exuParameters.JmpCnt + exuParameters.AluCnt
64  val io = IO(new Bundle() {
65    val exuMispredict = Vec(numRedirect, Flipped(ValidIO(new ExuOutput)))
66    val loadReplay = Flipped(ValidIO(new Redirect))
67    val flush = Input(Bool())
68    val stage1FtqRead = Vec(numRedirect + 1, new FtqRead)
69    val stage2FtqRead = new FtqRead
70    val stage2Redirect = ValidIO(new Redirect)
71    val stage3Redirect = ValidIO(new Redirect)
72    val memPredUpdate = Output(new MemPredUpdateReq)
73    val memPredFtqRead = new FtqRead // read req send form stage 2
74  })
75  /*
76        LoadQueue  Jump  ALU0  ALU1  ALU2  ALU3   exception    Stage1
77          |         |      |    |     |     |         |
78          |============= reg & compare =====|         |       ========
79                            |                         |
80                            |                         |
81                            |                         |        Stage2
82                            |                         |
83                    redirect (flush backend)          |
84                    |                                 |
85               === reg ===                            |       ========
86                    |                                 |
87                    |----- mux (exception first) -----|        Stage3
88                            |
89                redirect (send to frontend)
90   */
91  private class Wrapper(val n: Int) extends Bundle {
92    val redirect = new Redirect
93    val valid = Bool()
94    val idx = UInt(log2Up(n).W)
95  }
96  def selectOldestRedirect(xs: Seq[Valid[Redirect]]): Vec[Bool] = {
97    val compareVec = (0 until xs.length).map(i => (0 until i).map(j => isAfter(xs(j).bits.roqIdx, xs(i).bits.roqIdx)))
98    val resultOnehot = VecInit((0 until xs.length).map(i => Cat((0 until xs.length).map(j =>
99      (if (j < i) !xs(j).valid || compareVec(i)(j)
100      else if (j == i) xs(i).valid
101      else !xs(j).valid || !compareVec(j)(i))
102    )).andR))
103    resultOnehot
104  }
105
106  for((ptr, redirect) <- io.stage1FtqRead.map(_.ptr).zip(
107    io.exuMispredict.map(_.bits.redirect) :+ io.loadReplay.bits
108  )){ ptr := redirect.ftqIdx }
109
110  def getRedirect(exuOut: Valid[ExuOutput]): ValidIO[Redirect] = {
111    val redirect = Wire(Valid(new Redirect))
112    redirect.valid := exuOut.valid && exuOut.bits.redirect.cfiUpdate.isMisPred
113    redirect.bits := exuOut.bits.redirect
114    redirect
115  }
116
117  val jumpOut = io.exuMispredict.head
118  val allRedirect = VecInit(io.exuMispredict.map(x => getRedirect(x)) :+ io.loadReplay)
119  val oldestOneHot = selectOldestRedirect(allRedirect)
120  val needFlushVec = VecInit(allRedirect.map(_.bits.roqIdx.needFlush(io.stage2Redirect, io.flush)))
121  val oldestValid = VecInit(oldestOneHot.zip(needFlushVec).map{ case (v, f) => v && !f }).asUInt.orR
122  val oldestExuOutput = Mux1H((0 until 5).map(oldestOneHot), io.exuMispredict)
123  val oldestRedirect = Mux1H(oldestOneHot, allRedirect)
124
125  val s1_jumpTarget = RegEnable(jumpOut.bits.redirect.cfiUpdate.target, jumpOut.valid)
126  val s1_imm12_reg = RegNext(oldestExuOutput.bits.uop.ctrl.imm(11, 0))
127  val s1_pd = RegNext(oldestExuOutput.bits.uop.cf.pd)
128  val s1_redirect_bits_reg = RegNext(oldestRedirect.bits)
129  val s1_redirect_valid_reg = RegNext(oldestValid)
130  val s1_redirect_onehot = RegNext(oldestOneHot)
131
132  // stage1 -> stage2
133  io.stage2Redirect.valid := s1_redirect_valid_reg && !io.flush
134  io.stage2Redirect.bits := s1_redirect_bits_reg
135  io.stage2Redirect.bits.cfiUpdate := DontCare
136  // at stage2, we read ftq to get pc
137  io.stage2FtqRead.ptr := s1_redirect_bits_reg.ftqIdx
138
139  val s1_isReplay = s1_redirect_onehot(5)
140  val s1_isJump = s1_redirect_onehot(0)
141  val ftqRead = Mux1H(s1_redirect_onehot, io.stage1FtqRead).entry
142  val cfiUpdate_pc = Cat(
143    ftqRead.ftqPC.head(VAddrBits - s1_redirect_bits_reg.ftqOffset.getWidth - instOffsetBits),
144    s1_redirect_bits_reg.ftqOffset,
145    0.U(instOffsetBits.W)
146  )
147  val real_pc = GetPcByFtq(
148    ftqRead.ftqPC, s1_redirect_bits_reg.ftqOffset,
149    ftqRead.lastPacketPC.valid,
150    ftqRead.lastPacketPC.bits
151  )
152  val brTarget = real_pc + SignExt(ImmUnion.B.toImm32(s1_imm12_reg), XLEN)
153  val snpc = real_pc + Mux(s1_pd.isRVC, 2.U, 4.U)
154  val target = Mux(s1_isReplay,
155    real_pc, // repaly from itself
156    Mux(s1_redirect_bits_reg.cfiUpdate.taken,
157      Mux(s1_isJump, s1_jumpTarget, brTarget),
158      snpc
159    )
160  )
161
162  // get pc from ftq
163  io.memPredFtqRead.ptr := s1_redirect_bits_reg.stFtqIdx
164  // valid only if redirect is caused by load violation
165  // store_pc is used to update store set
166  val memPredFtqRead = io.memPredFtqRead.entry
167  val store_pc = GetPcByFtq(memPredFtqRead.ftqPC, RegNext(s1_redirect_bits_reg).stFtqOffset,
168    memPredFtqRead.lastPacketPC.valid,
169    memPredFtqRead.lastPacketPC.bits
170  )
171
172  // update load violation predictor if load violation redirect triggered
173  io.memPredUpdate.valid := RegNext(s1_isReplay && s1_redirect_valid_reg, init = false.B)
174  // update wait table
175  io.memPredUpdate.waddr := RegNext(XORFold(real_pc(VAddrBits-1, 1), MemPredPCWidth))
176  io.memPredUpdate.wdata := true.B
177  // update store set
178  io.memPredUpdate.ldpc := RegNext(XORFold(real_pc(VAddrBits-1, 1), MemPredPCWidth))
179  // store pc is ready 1 cycle after s1_isReplay is judged
180  io.memPredUpdate.stpc := XORFold(store_pc(VAddrBits-1, 1), MemPredPCWidth)
181
182
183  val s2_br_mask = RegEnable(ftqRead.br_mask, enable = s1_redirect_valid_reg)
184  val s2_sawNotTakenBranch = RegEnable(VecInit((0 until PredictWidth).map{ i =>
185      if(i == 0) false.B else Cat(ftqRead.br_mask.take(i)).orR()
186    })(s1_redirect_bits_reg.ftqOffset), enable = s1_redirect_valid_reg)
187  val s2_hist = RegEnable(ftqRead.hist, enable = s1_redirect_valid_reg)
188  val s2_target = RegEnable(target, enable = s1_redirect_valid_reg)
189  val s2_pd = RegEnable(s1_pd, enable = s1_redirect_valid_reg)
190  val s2_cfiUpdata_pc = RegEnable(cfiUpdate_pc, enable = s1_redirect_valid_reg)
191  val s2_redirect_bits_reg = RegEnable(s1_redirect_bits_reg, enable = s1_redirect_valid_reg)
192  val s2_redirect_valid_reg = RegNext(s1_redirect_valid_reg && !io.flush, init = false.B)
193  val s2_ftqRead = io.stage2FtqRead.entry
194
195  io.stage3Redirect.valid := s2_redirect_valid_reg
196  io.stage3Redirect.bits := s2_redirect_bits_reg
197  val stage3CfiUpdate = io.stage3Redirect.bits.cfiUpdate
198  stage3CfiUpdate.pc := s2_cfiUpdata_pc
199  stage3CfiUpdate.pd := s2_pd
200  stage3CfiUpdate.rasSp := s2_ftqRead.rasSp
201  stage3CfiUpdate.rasEntry := s2_ftqRead.rasTop
202  stage3CfiUpdate.predHist := s2_ftqRead.predHist
203  stage3CfiUpdate.specCnt := s2_ftqRead.specCnt
204  stage3CfiUpdate.hist := s2_hist
205  stage3CfiUpdate.predTaken := s2_redirect_bits_reg.cfiUpdate.predTaken
206  stage3CfiUpdate.sawNotTakenBranch := s2_sawNotTakenBranch
207  stage3CfiUpdate.target := s2_target
208  stage3CfiUpdate.taken := s2_redirect_bits_reg.cfiUpdate.taken
209  stage3CfiUpdate.isMisPred := s2_redirect_bits_reg.cfiUpdate.isMisPred
210}
211
212class CtrlBlock(implicit p: Parameters) extends XSModule
213  with HasCircularQueuePtrHelper with HasFtqHelper {
214  val io = IO(new Bundle {
215    val frontend = Flipped(new FrontendToBackendIO)
216    val fromIntBlock = Flipped(new IntBlockToCtrlIO)
217    val fromFpBlock = Flipped(new FpBlockToCtrlIO)
218    val fromLsBlock = Flipped(new LsBlockToCtrlIO)
219    val toIntBlock = new CtrlToIntBlockIO
220    val toFpBlock = new CtrlToFpBlockIO
221    val toLsBlock = new CtrlToLsBlockIO
222    val roqio = new Bundle {
223      // to int block
224      val toCSR = new RoqCSRIO
225      val exception = ValidIO(new ExceptionInfo)
226      // to mem block
227      val lsq = new RoqLsqIO
228    }
229    val csrCtrl = Input(new CustomCSRCtrlIO)
230    val perfInfo = Output(new Bundle{
231      val ctrlInfo = new Bundle {
232        val roqFull   = Input(Bool())
233        val intdqFull = Input(Bool())
234        val fpdqFull  = Input(Bool())
235        val lsdqFull  = Input(Bool())
236      }
237    })
238  })
239
240  val decode = Module(new DecodeStage)
241  val rename = Module(new Rename)
242  val dispatch = Module(new Dispatch)
243  val intBusyTable = Module(new BusyTable(NRIntReadPorts, NRIntWritePorts))
244  val fpBusyTable = Module(new BusyTable(NRFpReadPorts, NRFpWritePorts))
245  val redirectGen = Module(new RedirectGenerator)
246
247  val roqWbSize = NRIntWritePorts + NRFpWritePorts + exuParameters.StuCnt
248  val roq = Module(new Roq(roqWbSize))
249
250  val backendRedirect = redirectGen.io.stage2Redirect
251  val frontendRedirect = redirectGen.io.stage3Redirect
252  val flush = roq.io.flushOut.valid
253  val flushReg = RegNext(flush)
254
255  val exuRedirect = io.fromIntBlock.exuRedirect.map(x => {
256    val valid = x.valid && x.bits.redirectValid
257    val killedByOlder = x.bits.uop.roqIdx.needFlush(backendRedirect, flushReg)
258    val delayed = Wire(Valid(new ExuOutput))
259    delayed.valid := RegNext(valid && !killedByOlder, init = false.B)
260    delayed.bits := RegEnable(x.bits, x.valid)
261    delayed
262  })
263  val loadReplay = Wire(Valid(new Redirect))
264  loadReplay.valid := RegNext(io.fromLsBlock.replay.valid &&
265    !io.fromLsBlock.replay.bits.roqIdx.needFlush(backendRedirect, flushReg),
266    init = false.B
267  )
268  loadReplay.bits := RegEnable(io.fromLsBlock.replay.bits, io.fromLsBlock.replay.valid)
269  VecInit(io.frontend.fromFtq.ftqRead.tail.dropRight(2)) <> redirectGen.io.stage1FtqRead
270  io.frontend.fromFtq.ftqRead.dropRight(1).last <> redirectGen.io.memPredFtqRead
271  io.frontend.fromFtq.cfiRead <> redirectGen.io.stage2FtqRead
272  redirectGen.io.exuMispredict <> exuRedirect
273  redirectGen.io.loadReplay <> loadReplay
274  redirectGen.io.flush := flushReg
275
276  for(i <- 0 until CommitWidth){
277    io.frontend.toFtq.roq_commits(i).valid := roq.io.commits.valid(i) && !roq.io.commits.isWalk
278    io.frontend.toFtq.roq_commits(i).bits := roq.io.commits.info(i)
279  }
280  io.frontend.toFtq.redirect <> backendRedirect
281  io.frontend.toFtq.flush := flushReg
282  io.frontend.toFtq.flushIdx := RegNext(roq.io.flushOut.bits.ftqIdx)
283  io.frontend.toFtq.flushOffset := RegNext(roq.io.flushOut.bits.ftqOffset)
284  io.frontend.toFtq.frontendRedirect <> frontendRedirect
285  io.frontend.toFtq.exuWriteback <> exuRedirect
286
287  io.frontend.fromFtq.ftqRead.last.ptr := roq.io.flushOut.bits.ftqIdx
288  val flushPC = GetPcByFtq(
289    io.frontend.fromFtq.ftqRead.last.entry.ftqPC,
290    RegEnable(roq.io.flushOut.bits.ftqOffset, roq.io.flushOut.valid),
291    io.frontend.fromFtq.ftqRead.last.entry.lastPacketPC.valid,
292    io.frontend.fromFtq.ftqRead.last.entry.lastPacketPC.bits
293  )
294
295  val flushRedirect = Wire(Valid(new Redirect))
296  flushRedirect.valid := flushReg
297  flushRedirect.bits := DontCare
298  flushRedirect.bits.ftqIdx := RegEnable(roq.io.flushOut.bits.ftqIdx, flush)
299  flushRedirect.bits.interrupt := true.B
300  flushRedirect.bits.cfiUpdate.target := Mux(io.roqio.toCSR.isXRet || roq.io.exception.valid,
301    io.roqio.toCSR.trapTarget,
302    flushPC + 4.U // flush pipe
303  )
304  val flushRedirectReg = Wire(Valid(new Redirect))
305  flushRedirectReg.valid := RegNext(flushRedirect.valid, init = false.B)
306  flushRedirectReg.bits := RegEnable(flushRedirect.bits, enable = flushRedirect.valid)
307
308  io.frontend.redirect_cfiUpdate := Mux(flushRedirectReg.valid, flushRedirectReg, frontendRedirect)
309
310  decode.io.in <> io.frontend.cfVec
311  // currently, we only update wait table when isReplay
312  decode.io.memPredUpdate(0) <> RegNext(redirectGen.io.memPredUpdate)
313  decode.io.memPredUpdate(1) := DontCare
314  decode.io.memPredUpdate(1).valid := false.B
315  // decode.io.memPredUpdate <> io.toLsBlock.memPredUpdate
316  decode.io.csrCtrl := RegNext(io.csrCtrl)
317
318
319  val jumpInst = dispatch.io.enqIQCtrl(0).bits
320  val ftqOffsetReg = Reg(UInt(log2Up(PredictWidth).W))
321  ftqOffsetReg := jumpInst.cf.ftqOffset
322  io.frontend.fromFtq.ftqRead(0).ptr := jumpInst.cf.ftqPtr // jump
323  io.toIntBlock.jumpPc := GetPcByFtq(
324    io.frontend.fromFtq.ftqRead(0).entry.ftqPC, ftqOffsetReg,
325    io.frontend.fromFtq.ftqRead(0).entry.lastPacketPC.valid,
326    io.frontend.fromFtq.ftqRead(0).entry.lastPacketPC.bits
327  )
328  io.toIntBlock.jalr_target := io.frontend.fromFtq.ftqRead(0).entry.target
329
330  // pipeline between decode and dispatch
331  for (i <- 0 until RenameWidth) {
332    PipelineConnect(decode.io.out(i), rename.io.in(i), rename.io.in(i).ready,
333      flushReg || io.frontend.redirect_cfiUpdate.valid)
334  }
335
336  rename.io.redirect <> backendRedirect
337  rename.io.flush := flushReg
338  rename.io.roqCommits <> roq.io.commits
339  rename.io.out <> dispatch.io.fromRename
340  rename.io.renameBypass <> dispatch.io.renameBypass
341  rename.io.dispatchInfo <> dispatch.io.preDpInfo
342  rename.io.csrCtrl <> RegNext(io.csrCtrl)
343
344  dispatch.io.redirect <> backendRedirect
345  dispatch.io.flush := flushReg
346  dispatch.io.enqRoq <> roq.io.enq
347  dispatch.io.enqLsq <> io.toLsBlock.enqLsq
348  dispatch.io.readIntRf <> io.toIntBlock.readRf
349  dispatch.io.readFpRf <> io.toFpBlock.readRf
350  dispatch.io.allocPregs.zipWithIndex.foreach { case (preg, i) =>
351    intBusyTable.io.allocPregs(i).valid := preg.isInt
352    fpBusyTable.io.allocPregs(i).valid := preg.isFp
353    intBusyTable.io.allocPregs(i).bits := preg.preg
354    fpBusyTable.io.allocPregs(i).bits := preg.preg
355  }
356  dispatch.io.numExist <> io.fromIntBlock.numExist ++ io.fromFpBlock.numExist ++ io.fromLsBlock.numExist
357  dispatch.io.enqIQCtrl <> io.toIntBlock.enqIqCtrl ++ io.toFpBlock.enqIqCtrl ++ io.toLsBlock.enqIqCtrl
358//  dispatch.io.enqIQData <> io.toIntBlock.enqIqData ++ io.toFpBlock.enqIqData ++ io.toLsBlock.enqIqData
359  dispatch.io.csrCtrl <> io.csrCtrl
360  dispatch.io.storeIssue <> io.fromLsBlock.stIn
361
362
363  fpBusyTable.io.flush := flushReg
364  intBusyTable.io.flush := flushReg
365  for((wb, setPhyRegRdy) <- io.fromIntBlock.wbRegs.zip(intBusyTable.io.wbPregs)){
366    setPhyRegRdy.valid := wb.valid && wb.bits.uop.ctrl.rfWen
367    setPhyRegRdy.bits := wb.bits.uop.pdest
368  }
369  for((wb, setPhyRegRdy) <- io.fromFpBlock.wbRegs.zip(fpBusyTable.io.wbPregs)){
370    setPhyRegRdy.valid := wb.valid && wb.bits.uop.ctrl.fpWen
371    setPhyRegRdy.bits := wb.bits.uop.pdest
372  }
373  intBusyTable.io.read <> dispatch.io.readIntState
374  fpBusyTable.io.read <> dispatch.io.readFpState
375
376  roq.io.redirect <> backendRedirect
377  val exeWbResults = VecInit(io.fromIntBlock.wbRegs ++ io.fromFpBlock.wbRegs ++ io.fromLsBlock.stOut)
378  for((roq_wb, wb) <- roq.io.exeWbResults.zip(exeWbResults)) {
379    roq_wb.valid := RegNext(wb.valid && !wb.bits.uop.roqIdx.needFlush(backendRedirect, flushReg))
380    roq_wb.bits := RegNext(wb.bits)
381  }
382
383  // TODO: is 'backendRedirect' necesscary?
384  io.toIntBlock.redirect <> backendRedirect
385  io.toIntBlock.flush <> flushReg
386  io.toIntBlock.debug_rat <> rename.io.debug_int_rat
387  io.toFpBlock.redirect <> backendRedirect
388  io.toFpBlock.flush <> flushReg
389  io.toFpBlock.debug_rat <> rename.io.debug_fp_rat
390  io.toLsBlock.redirect <> backendRedirect
391  io.toLsBlock.flush <> flushReg
392
393  dispatch.io.readPortIndex.intIndex <> io.toIntBlock.readPortIndex
394  dispatch.io.readPortIndex.fpIndex <> io.toFpBlock.readPortIndex
395
396  // roq to int block
397  io.roqio.toCSR <> roq.io.csr
398  io.roqio.toCSR.perfinfo.retiredInstr <> RegNext(roq.io.csr.perfinfo.retiredInstr)
399  io.roqio.exception := roq.io.exception
400  io.roqio.exception.bits.uop.cf.pc := flushPC
401  // roq to mem block
402  io.roqio.lsq <> roq.io.lsq
403
404  io.perfInfo.ctrlInfo.roqFull := RegNext(roq.io.roqFull)
405  io.perfInfo.ctrlInfo.intdqFull := RegNext(dispatch.io.ctrlInfo.intdqFull)
406  io.perfInfo.ctrlInfo.fpdqFull := RegNext(dispatch.io.ctrlInfo.fpdqFull)
407  io.perfInfo.ctrlInfo.lsdqFull := RegNext(dispatch.io.ctrlInfo.lsdqFull)
408}
409