xref: /XiangShan/src/main/scala/xiangshan/frontend/BPU.scala (revision d077b11804222346941c6a7dc7188e89b46579a4)
1package xiangshan.frontend
2
3import chisel3._
4import chisel3.util._
5import utils._
6import xiangshan._
7import xiangshan.backend.ALUOpType
8import xiangshan.backend.JumpOpType
9
10class TableAddr(val idxBits: Int, val banks: Int) extends XSBundle {
11  def tagBits = VAddrBits - idxBits - 1
12
13  val tag = UInt(tagBits.W)
14  val idx = UInt(idxBits.W)
15  val offset = UInt(1.W)
16
17  def fromUInt(x: UInt) = x.asTypeOf(UInt(VAddrBits.W)).asTypeOf(this)
18  def getTag(x: UInt) = fromUInt(x).tag
19  def getIdx(x: UInt) = fromUInt(x).idx
20  def getBank(x: UInt) = getIdx(x)(log2Up(banks) - 1, 0)
21  def getBankIdx(x: UInt) = getIdx(x)(idxBits - 1, log2Up(banks))
22}
23
24class PredictorResponse extends XSBundle {
25  class UbtbResp extends XSBundle {
26  // the valid bits indicates whether a target is hit
27    val targets = Vec(PredictWidth, UInt(VAddrBits.W))
28    val hits = Vec(PredictWidth, Bool())
29    val takens = Vec(PredictWidth, Bool())
30    val notTakens = Vec(PredictWidth, Bool())
31    val is_RVC = Vec(PredictWidth, Bool())
32  }
33  class BtbResp extends XSBundle {
34  // the valid bits indicates whether a target is hit
35    val targets = Vec(PredictWidth, UInt(VAddrBits.W))
36    val hits = Vec(PredictWidth, Bool())
37    val types = Vec(PredictWidth, UInt(2.W))
38    val isRVC = Vec(PredictWidth, Bool())
39  }
40  class BimResp extends XSBundle {
41    val ctrs = Vec(PredictWidth, UInt(2.W))
42  }
43  class TageResp extends XSBundle {
44  // the valid bits indicates whether a prediction is hit
45    val takens = Vec(PredictWidth, Bool())
46    val hits = Vec(PredictWidth, Bool())
47  }
48
49  val ubtb = new UbtbResp
50  val btb = new BtbResp
51  val bim = new BimResp
52  val tage = new TageResp
53}
54
55abstract class BasePredictor extends XSModule {
56  val metaLen = 0
57
58  // An implementation MUST extend the IO bundle with a response
59  // and the special input from other predictors, as well as
60  // the metas to store in BRQ
61  abstract class Resp extends XSBundle {}
62  abstract class FromOthers extends XSBundle {}
63  abstract class Meta extends XSBundle {}
64
65  class DefaultBasePredictorIO extends XSBundle {
66    val flush = Input(Bool())
67    val pc = Flipped(ValidIO(UInt(VAddrBits.W)))
68    val hist = Input(UInt(HistoryLength.W))
69    val inMask = Input(UInt(PredictWidth.W))
70    val update = Flipped(ValidIO(new BranchUpdateInfoWithHist))
71  }
72
73  val io = new DefaultBasePredictorIO
74
75  // circular shifting
76  def circularShiftLeft(source: UInt, len: Int, shamt: UInt): UInt = {
77    val res = Wire(UInt(len.W))
78    val higher = source << shamt
79    val lower = source >> (len.U - shamt)
80    res := higher | lower
81    res
82  }
83
84  def circularShiftRight(source: UInt, len: Int, shamt: UInt): UInt = {
85    val res = Wire(UInt(len.W))
86    val higher = source << (len.U - shamt)
87    val lower = source >> shamt
88    res := higher | lower
89    res
90  }
91}
92
93class BPUStageIO extends XSBundle {
94  val pc = UInt(VAddrBits.W)
95  val mask = UInt(PredictWidth.W)
96  val resp = new PredictorResponse
97  val target = UInt(VAddrBits.W)
98  val brInfo = Vec(PredictWidth, new BranchInfo)
99}
100
101
102class BPUStage extends XSModule {
103  class DefaultIO extends XSBundle {
104    val flush = Input(Bool())
105    val in = Flipped(Decoupled(new BPUStageIO))
106    val pred = Decoupled(new BranchPrediction)
107    val out = Decoupled(new BPUStageIO)
108    val predecode = Flipped(ValidIO(new Predecode))
109  }
110  val io = IO(new DefaultIO)
111
112  val predValid = RegInit(false.B)
113
114  io.in.ready := !predValid || io.out.fire() && io.pred.fire()
115
116  def npc(pc: UInt, instCount: UInt) = pc + (instCount << 1.U)
117
118  val inFire = io.in.fire()
119  val inLatch = RegEnable(io.in.bits, inFire)
120
121  val outFire = io.out.fire()
122
123  // Each stage has its own logic to decide
124  // takens, notTakens and target
125
126  val takens = VecInit((0 until PredictWidth).map(_ => false.B))
127  val notTakens = VecInit((0 until PredictWidth).map(_ => false.B))
128  val jmpIdx = PriorityEncoder(takens)
129  val hasNTBr = (0 until PredictWidth).map(i => i.U <= jmpIdx && notTakens(i)).reduce(_||_)
130  val taken = takens.reduce(_||_)
131  // get the last valid inst
132  // val lastValidPos = MuxCase(0.U, (PredictWidth-1 to 0).map(i => (inLatch.mask(i), i.U)))
133  val lastValidPos = PriorityMux(Reverse(inLatch.mask), (PredictWidth-1 to 0 by -1).map(i => i.U))
134  val lastHit   = WireInit(false.B)
135  val lastIsRVC = WireInit(false.B)
136  // val lastValidPos = WireInit(0.U(log2Up(PredictWidth).W))
137  // for (i <- 0 until PredictWidth) {
138  //   when (inLatch.mask(i)) { lastValidPos := i.U }
139  // }
140  val targetSrc = VecInit((0 until PredictWidth).map(i => 0.U(VAddrBits.W)))
141  val target = Mux(taken, targetSrc(jmpIdx), npc(inLatch.pc, PopCount(inLatch.mask)))
142
143  io.pred.bits <> DontCare
144  io.pred.bits.redirect := target =/= inLatch.target
145  io.pred.bits.taken := taken
146  io.pred.bits.jmpIdx := jmpIdx
147  io.pred.bits.hasNotTakenBrs := hasNTBr
148  io.pred.bits.target := target
149  io.pred.bits.saveHalfRVI := ((lastValidPos === jmpIdx && taken) || !taken ) && !lastIsRVC && lastHit
150
151  io.out.bits <> DontCare
152  io.out.bits.pc := inLatch.pc
153  io.out.bits.mask := inLatch.mask
154  io.out.bits.target := target
155  io.out.bits.resp <> inLatch.resp
156  io.out.bits.brInfo := inLatch.brInfo
157
158  // Default logic
159  //  pred.ready not taken into consideration
160  //  could be broken
161  when (io.flush)     { predValid := false.B }
162  .elsewhen (inFire)  { predValid := true.B }
163  .elsewhen (outFire) { predValid := false.B }
164  .otherwise          { predValid := predValid }
165
166  io.out.valid  := predValid && !io.flush
167  io.pred.valid := predValid && !io.flush
168
169  XSDebug(io.in.fire(), "in:(%d %d) pc=%x, mask=%b, target=%x\n",
170    io.in.valid, io.in.ready, io.in.bits.pc, io.in.bits.mask, io.in.bits.target)
171  XSDebug(io.out.fire(), "out:(%d %d) pc=%x, mask=%b, target=%x\n",
172    io.out.valid, io.out.ready, io.out.bits.pc, io.out.bits.mask, io.out.bits.target)
173  XSDebug("flush=%d\n", io.flush)
174  XSDebug("taken=%d, takens=%b, notTakens=%b, jmpIdx=%d, hasNTBr=%d, lastValidPos=%d, target=%x\n",
175    taken, takens.asUInt, notTakens.asUInt, jmpIdx, hasNTBr, lastValidPos, target)
176  val p = io.pred.bits
177  XSDebug(io.pred.fire(), "outPred: redirect=%d, taken=%d, jmpIdx=%d, hasNTBrs=%d, target=%x, saveHalfRVI=%d\n",
178    p.redirect, p.taken, p.jmpIdx, p.hasNotTakenBrs, p.target, p.saveHalfRVI)
179}
180
181class BPUStage1 extends BPUStage {
182
183  // 'overrides' default logic
184  // when flush, the prediction should also starts
185  when (io.flush || inFire) { predValid := true.B }
186  .elsewhen(outFire)        { predValid := false.B }
187  .otherwise                { predValid := predValid }
188  io.in.ready := !predValid || io.out.fire() && io.pred.fire() || io.flush
189  // io.out.valid := predValid
190
191  // ubtb is accessed with inLatch pc in s1,
192  // so we use io.in instead of inLatch
193  val ubtbResp = io.in.bits.resp.ubtb
194  // the read operation is already masked, so we do not need to mask here
195  takens    := VecInit((0 until PredictWidth).map(i => ubtbResp.hits(i) && ubtbResp.takens(i)))
196  notTakens := VecInit((0 until PredictWidth).map(i => ubtbResp.hits(i) && ubtbResp.notTakens(i)))
197  targetSrc := ubtbResp.targets
198
199  lastIsRVC := ubtbResp.is_RVC(lastValidPos)
200  lastHit   := ubtbResp.hits(lastValidPos)
201
202  // resp and brInfo are from the components,
203  // so it does not need to be latched
204  io.out.bits.resp <> io.in.bits.resp
205  io.out.bits.brInfo := io.in.bits.brInfo
206}
207
208class BPUStage2 extends BPUStage {
209
210  // Use latched response from s1
211  val btbResp = inLatch.resp.btb
212  val bimResp = inLatch.resp.bim
213  takens    := VecInit((0 until PredictWidth).map(i => btbResp.hits(i) && (btbResp.types(i) === BrType.branch && bimResp.ctrs(i)(1) || btbResp.types(i) === BrType.jal)))
214  notTakens := VecInit((0 until PredictWidth).map(i => btbResp.hits(i) && btbResp.types(i) === BrType.branch && !bimResp.ctrs(i)(1)))
215  targetSrc := btbResp.targets
216
217  lastIsRVC := btbResp.isRVC(lastValidPos)
218  lastHit   := btbResp.hits(lastValidPos)
219}
220
221class BPUStage3 extends BPUStage {
222
223  io.out.valid := predValid && io.predecode.valid && !io.flush
224
225  // TAGE has its own pipelines and the
226  // response comes directly from s3,
227  // so we do not use those from inLatch
228  val tageResp = io.in.bits.resp.tage
229  val tageValidTakens = VecInit((0 until PredictWidth).map( i => tageResp.takens(i) && tageResp.hits(i)))
230
231  val pdMask = io.predecode.bits.mask
232  val pds    = io.predecode.bits.pd
233
234  val btbHits   = inLatch.resp.btb.hits.asUInt
235  val bimTakens = VecInit(inLatch.resp.bim.ctrs.map(_(1)))
236
237  val brs   = pdMask & Reverse(Cat(pds.map(_.isBr)))
238  val jals  = pdMask & Reverse(Cat(pds.map(_.isJal)))
239  val jalrs = pdMask & Reverse(Cat(pds.map(_.isJalr)))
240  // val calls = pdMask & Reverse(Cat(pds.map(_.isCall)))
241  // val rets  = pdMask & Reverse(Cat(pds.map(_.isRet)))
242
243  // val callIdx = PriorityEncoder(calls)
244  // val retIdx  = PriorityEncoder(rets)
245
246  val brTakens =
247    if (EnableBPD) {
248      brs & Reverse(Cat((0 until PredictWidth).map(i => tageValidTakens(i))))
249    } else {
250      brs & Reverse(Cat((0 until PredictWidth).map(i => bimTakens(i))))
251    }
252
253  // predict taken only if btb has a target
254  takens := VecInit((0 until PredictWidth).map(i => (brTakens(i) || jalrs(i)) && btbHits(i) || jals(i)))
255  // Whether should we count in branches that are not recorded in btb?
256  // PS: Currently counted in. Whenever tage does not provide a valid
257  //     taken prediction, the branch is counted as a not taken branch
258  notTakens := (if (EnableBPD) { VecInit((0 until PredictWidth).map(i => brs(i) && !tageValidTakens(i)))}
259                else           { VecInit((0 until PredictWidth).map(i => brs(i) && !bimTakens(i)))})
260  targetSrc := inLatch.resp.btb.targets
261
262  lastIsRVC := pds(lastValidPos).isRVC
263  lastHit   := pdMask(lastValidPos)
264
265  // Wrap tage resp and tage meta in
266  // This is ugly
267  io.out.bits.resp.tage <> io.in.bits.resp.tage
268  for (i <- 0 until PredictWidth) {
269    io.out.bits.brInfo(i).tageMeta := io.in.bits.brInfo(i).tageMeta
270  }
271
272  XSDebug(io.predecode.valid, "predecode: mask:%b\n", io.predecode.bits.mask)
273  for (i <- 0 until PredictWidth) {
274    val p = io.predecode.bits.pd(i)
275      XSDebug(io.predecode.valid, "predecode(%d): brType:%d, br:%d, jal:%d, jalr:%d, call:%d, ret:%d, RVC:%d, excType:%d\n",
276        i.U, p.brType, p.isBr, p.isJal, p.isJalr, p.isCall, p.isRet, p.isRVC, p.excType)
277  }
278}
279
280trait BranchPredictorComponents extends HasXSParameter {
281  val ubtb = Module(new MicroBTB)
282  val btb = Module(new BTB)
283  val bim = Module(new BIM)
284  val tage = (if(EnableBPD) { Module(new Tage) }
285              else          { Module(new FakeTage) })
286  val preds = Seq(ubtb, btb, bim, tage)
287  preds.map(_.io := DontCare)
288}
289
290class BPUReq extends XSBundle {
291  val pc = UInt(VAddrBits.W)
292  val hist = UInt(HistoryLength.W)
293  val inMask = UInt(PredictWidth.W)
294}
295
296class BranchUpdateInfoWithHist extends XSBundle {
297  val ui = new BranchUpdateInfo
298  val hist = UInt(HistoryLength.W)
299}
300
301object BranchUpdateInfoWithHist {
302  def apply (brInfo: BranchUpdateInfo, hist: UInt) = {
303    val b = Wire(new BranchUpdateInfoWithHist)
304    b.ui <> brInfo
305    b.hist := hist
306    b
307  }
308}
309
310abstract class BaseBPU extends XSModule with BranchPredictorComponents{
311  val io = IO(new Bundle() {
312    // from backend
313    val inOrderBrInfo = Flipped(ValidIO(new BranchUpdateInfoWithHist))
314    // from ifu, frontend redirect
315    val flush = Input(Vec(3, Bool()))
316    // from if1
317    val in = Flipped(ValidIO(new BPUReq))
318    // to if2/if3/if4
319    val out = Vec(3, Decoupled(new BranchPrediction))
320    // from if4
321    val predecode = Flipped(ValidIO(new Predecode))
322    // to if4, some bpu info used for updating
323    val branchInfo = Decoupled(Vec(PredictWidth, new BranchInfo))
324  })
325
326  def npc(pc: UInt, instCount: UInt) = pc + (instCount << 1.U)
327
328  preds.map(_.io.update <> io.inOrderBrInfo)
329
330  val s1 = Module(new BPUStage1)
331  val s2 = Module(new BPUStage2)
332  val s3 = Module(new BPUStage3)
333
334  s1.io.flush := io.flush(0)
335  s2.io.flush := io.flush(1)
336  s3.io.flush := io.flush(2)
337
338  s1.io.in <> DontCare
339  s2.io.in <> s1.io.out
340  s3.io.in <> s2.io.out
341
342  io.out(0) <> s1.io.pred
343  io.out(1) <> s2.io.pred
344  io.out(2) <> s3.io.pred
345
346  s1.io.predecode <> DontCare
347  s2.io.predecode <> DontCare
348  s3.io.predecode <> io.predecode
349
350  io.branchInfo.valid := s3.io.out.valid
351  io.branchInfo.bits := s3.io.out.bits.brInfo
352  s3.io.out.ready := io.branchInfo.ready
353
354  XSDebug(io.branchInfo.fire(), "branchInfo sent!\n")
355  for (i <- 0 until PredictWidth) {
356    val b = io.branchInfo.bits(i)
357    XSDebug(io.branchInfo.fire(), "brInfo(%d): ubtbWrWay:%d, ubtbHit:%d, btbWrWay:%d, bimCtr:%d\n",
358      i.U, b.ubtbWriteWay, b.ubtbHits, b.btbWriteWay, b.bimCtr)
359    val t = b.tageMeta
360    XSDebug(io.branchInfo.fire(), "  tageMeta: pvder(%d):%d, altDiffers:%d, pvderU:%d, pvderCtr:%d, allocate(%d):%d\n",
361      t.provider.valid, t.provider.bits, t.altDiffers, t.providerU, t.providerCtr, t.allocate.valid, t.allocate.bits)
362  }
363}
364
365
366class FakeBPU extends BaseBPU {
367  io.out.foreach(i => {
368    // Provide not takens
369    i.valid := true.B
370    i.bits <> DontCare
371    i.bits.redirect := false.B
372  })
373  io.branchInfo <> DontCare
374}
375
376class BPU extends BaseBPU {
377
378  //**********************Stage 1****************************//
379  val s1_fire = s1.io.in.fire()
380  val s1_resp_in = Wire(new PredictorResponse)
381  val s1_brInfo_in = Wire(Vec(PredictWidth, new BranchInfo))
382
383  s1_resp_in := DontCare
384  s1_brInfo_in := DontCare
385
386  val s1_inLatch = RegEnable(io.in, s1_fire)
387  ubtb.io.flush := io.flush(0) // TODO: fix this
388  ubtb.io.pc.valid := s1_inLatch.valid
389  ubtb.io.pc.bits := s1_inLatch.bits.pc
390  ubtb.io.inMask := s1_inLatch.bits.inMask
391
392  // Wrap ubtb response into resp_in and brInfo_in
393  s1_resp_in.ubtb <> ubtb.io.out
394  for (i <- 0 until PredictWidth) {
395    s1_brInfo_in(i).ubtbWriteWay := ubtb.io.uBTBBranchInfo.writeWay(i)
396    s1_brInfo_in(i).ubtbHits := ubtb.io.uBTBBranchInfo.hits(i)
397  }
398
399  btb.io.flush := io.flush(0) // TODO: fix this
400  btb.io.pc.valid := io.in.valid
401  btb.io.pc.bits := io.in.bits.pc
402  btb.io.inMask := io.in.bits.inMask
403
404  // Wrap btb response into resp_in and brInfo_in
405  s1_resp_in.btb <> btb.io.resp
406  for (i <- 0 until PredictWidth) {
407    s1_brInfo_in(i).btbWriteWay := btb.io.meta.writeWay(i)
408  }
409
410  bim.io.flush := io.flush(0) // TODO: fix this
411  bim.io.pc.valid := io.in.valid
412  bim.io.pc.bits := io.in.bits.pc
413  bim.io.inMask := io.in.bits.inMask
414
415  // Wrap bim response into resp_in and brInfo_in
416  s1_resp_in.bim <> bim.io.resp
417  for (i <- 0 until PredictWidth) {
418    s1_brInfo_in(i).bimCtr := bim.io.meta.ctrs(i)
419  }
420
421
422  s1.io.in.valid := io.in.valid
423  s1.io.in.bits.pc := io.in.bits.pc
424  s1.io.in.bits.mask := io.in.bits.inMask
425  s1.io.in.bits.target := npc(s1_inLatch.bits.pc, PopCount(s1_inLatch.bits.inMask)) // Deault target npc
426  s1.io.in.bits.resp := s1_resp_in
427  s1.io.in.bits.brInfo <> s1_brInfo_in
428
429  //**********************Stage 2****************************//
430  tage.io.flush := io.flush(1) // TODO: fix this
431  tage.io.pc.valid := s1.io.out.fire()
432  tage.io.pc.bits := s1.io.out.bits.pc // PC from s1
433  tage.io.hist := io.in.bits.hist // The inst is from s1
434  tage.io.inMask := s1.io.out.bits.mask
435  tage.io.s3Fire := s3.io.in.fire() // Tell tage to march 1 stage
436  tage.io.bim <> s1.io.out.bits.resp.bim // Use bim results from s1
437
438  //**********************Stage 3****************************//
439  // Wrap tage response and meta into s3.io.in.bits
440  // This is ugly
441
442  s3.io.in.bits.resp.tage <> tage.io.resp
443  for (i <- 0 until PredictWidth) {
444    s3.io.in.bits.brInfo(i).tageMeta := tage.io.meta(i)
445  }
446
447}
448